"""CaMa survival measured against the SEER-trained original (Luis's pipeline, `05_curvas_supervivencia.py`): the same model, trained on the same SEER patients, gives each clinical scenario the same patients and deaths, the same observed curves (Kaplan-Meier, Weibull, fractional Weibull), and model points close to the original's. SEER is real registry data under NCI's use agreement: it is read from outside git (SEER_FILE) and nothing of it is kept. The original's outputs are read from where it ran (LUIS_RUN: its `subgrupos_*.csv`). Both missing: the test is skipped. Each SEER case becomes a timeline: a first invasive biopsy at diagnosis with its report's results, its first course of treatment a month later, and its death or last contact placed so the platform's whole months of follow-up are SEER's survival months. The model points are not the original's: it trains on every case, the platform on the earliest 70% by index date (and validates on the rest), and SEER's latest diagnoses carry few recorded deaths yet. They are checked against the survival of the cases the model learned from; their distance to the original's is printed. Slow (a quarter of an hour): SEER_SLOW=1.""" import os import re from pathlib import Path import numpy as np import pandas as pd import pytest from models import curves, survival from models.cama.specs import MODELS from models.survival import DAYS_PER_MONTH, DAYS_PER_YEAR, TRAIN_FRACTION, scenario_masks SEER = Path( os.environ.get("SEER_FILE", Path.home() / "camaSupervivencia" / "dataframe_recodificado.csv") ) RUN = Path(os.environ.get("LUIS_RUN", Path.home() / "isssteleon-data" / "luis-run")) AS_OF = pd.Timestamp("2023-12-31") # SEER's follow-up cutoff: survivors are followed to it pytestmark = [ pytest.mark.skipif( not (SEER.exists() and (RUN / "subgrupos_KM_Weibull_fraccional.csv").exists()), reason="SEER and the original's outputs are outside git", ), pytest.mark.skipif(not os.environ.get("SEER_SLOW"), reason="slow: SEER_SLOW=1"), ] CURVE = 1e-3 # the fits' agreement (maximum distance to Kaplan-Meier, shape k relative) CALIBRATION = 0.01 # the model's mean survival against its training cases' Kaplan-Meier STAGE = {"0 (in situ)": "0", "I": "I", "II": "II", "III": "III", "IV": "IV"} GRADE = {"G1": "1", "G2": "2", "G3": "3"} RECEPTOR = {"Positivo": "positive", "Negativo": "negative"} SURGERY = {"Conservadora": "breast_conserving_surgery", "Mastectomía": "mastectomy"} def _her2(subtype: str) -> str | None: return "positive" if "HER2+" in subtype else "negative" if "HER2-" in subtype else None def _age(recode: str) -> float: """The age band's lower bound, as the original reads it ("65-69 years": 65).""" found = re.search(r"\d+", str(recode)) return float(found.group()) if found else np.nan def seer_events(frame: pd.DataFrame) -> pd.DataFrame: """SEER cases as CaMa timelines (gold `cama_events` shape, indexed at diagnosis).""" months = pd.to_numeric(frame["Survival_months"], errors="coerce") frame, months = frame[months.notna()], months[months.notna()] dead = frame["Vital_status_recode_study_cutoff_used"].str.lower().str.contains("dead") person = frame["Patient_ID"].to_numpy() # Whole months from the index are SEER's. A survivor's index is months + 1/2 before the # cutoff; a death's is in its year of diagnosis (spread over the year by its id, never so # late that the death would pass the cutoff), and she dies months + 1/4 after it. So the # index dates keep SEER's calendar, which the model's split by index date reads. latest = AS_OF - pd.to_timedelta((months + 0.5) * DAYS_PER_MONTH, "D") year = pd.to_datetime(frame["Year_of_diagnosis"] + "-01-01") spread = pd.to_timedelta(frame["Patient_ID"].astype(int) % 365, "D") index = latest.where(~dead, (year + spread).where(year + spread < latest, latest)) death = index + pd.to_timedelta((months + 0.25) * DAYS_PER_MONTH, "D") birth = index - pd.to_timedelta((frame["Age_recode_with_1_year_olds_and_90"].map(_age) + 0.5) * DAYS_PER_YEAR, "D") # fmt: skip base = pd.DataFrame({"person_id": person, "index_date": index.to_numpy(), "record_number": person}) # fmt: skip rows = [base.assign(date=birth.to_numpy(), type="birth", value_code=None)] rows.append(base[dead.to_numpy()].assign(date=death[dead].to_numpy(), type="death", value_code=None)) # fmt: skip hr_negative = frame["Subtipo_molecular_cat"].str.startswith("HR-") hr_positive = frame["Subtipo_molecular_cat"].str.startswith("HR+") er = frame["Receptor_estrogeno_cat"].map(RECEPTOR) pr = frame["Receptor_progesterona_cat"].map(RECEPTOR) both_negative = er.eq("negative") & pr.eq("negative") results = { "biopsy": pd.Series("invasive", index=frame.index), "stage": frame["Estadio_cat"].map(STAGE), "grade": frame["Grado_histologico_cat"].map(GRADE), # Hormone receptors as SEER's subtype states them, which the original's scenarios read: # SEER's own columns disagree in a few cases (HR+ with both recodes negative, likely # borderline results): HR- makes both negative; HR+ with both negative leaves ER unknown. "er": er.mask(hr_negative, "negative").mask(hr_positive & both_negative, None), "pr": pr.mask(hr_negative, "negative"), "her2": frame["Subtipo_molecular_cat"].map(_her2), "histologic_type": frame["Histologic_Type_ICD_O_3"].astype(str) + "/3", } for kind, values in results.items(): rows.append(base.assign(date=index.to_numpy(), type=kind, value_code=values.to_numpy())) size = pd.to_numeric(frame["Tumor_Size_Over_Time_Recode_1988"], errors="coerce") rows.append(base.assign(date=index.to_numpy(), type="size_mm", value_code=None, value_num=size.where(size < 990).to_numpy())) # fmt: skip course = { "surgery": frame["Tratamiento_quirurgico_cat"].map(SURGERY), "chemotherapy": frame["Quimioterapia_cat"].map({"Sí": "chemotherapy"}), "radiotherapy": frame["Radioterapia_cat"].map({"Sí": "radiotherapy"}), } month_later = index + pd.Timedelta(days=30) for values in course.values(): rows.append(base.assign(date=month_later.to_numpy(), type="treatment", value_code=values.to_numpy())) # fmt: skip events = pd.concat(rows, ignore_index=True) events = events[events["type"].isin(["birth", "death"]) | events["value_code"].notna() | events.get("value_num", pd.Series(np.nan)).notna()] # fmt: skip events["value_num"] = events.get("value_num") events["source_table"], events["source_id"] = "seer", events["person_id"] return events.reset_index(drop=True) @pytest.fixture(scope="module") def trained(): events = seer_events(pd.read_csv(SEER, dtype=str)) spec = MODELS["survival"] model, metrics, data = spec.train(events, AS_OF) return spec, model, metrics, data def _original(name: str) -> pd.DataFrame: return pd.read_csv(RUN / name) def test_each_scenario_takes_the_originals_patients_and_deaths(trained): spec, _, _, data = trained members = pd.concat([data["train"], data["test"]]).reset_index(drop=True) masks = scenario_masks(members, spec.scenarios) theirs = _original("subgrupos_KM_Weibull_fraccional.csv").set_index("subgrupo") for name, row in theirs.iterrows(): mask = masks[name] assert (int(mask.sum()), int(members["event"][mask].sum())) == ( row["n"], row["fallecidos"], ), name @pytest.fixture(scope="module") def report(trained): spec, model, _, data = trained return survival.interpretability(spec, model, data) def test_each_scenarios_observed_curves_are_the_originals(report): theirs = _original("subgrupos_KM_Weibull_fraccional.csv").set_index("subgrupo") assert {e["escenario"] for e in report["escenarios"]} == set(theirs.index) for e in report["escenarios"]: row, km = theirs.loc[e["escenario"]], np.array(e["km"]["S"]) months = np.arange(len(km)) weibull = np.interp(months, e["weibull"]["t"], e["weibull"]["S"]) fractional = np.interp(months, e["weibull_fractional"]["t"], e["weibull_fractional"]["S"]) assert e["weibull"]["k"] == pytest.approx(row["k Weibull"], rel=CURVE), e["escenario"] assert np.abs(weibull - km).max() == pytest.approx(row["máx|KM−Weibull|"], abs=CURVE) assert np.abs(fractional - km).max() <= row["máx|KM−fracc.|"] + CURVE, e["escenario"] def test_the_models_points_are_the_survival_of_the_cases_it_learned_from(trained, report): spec, _, _, data = trained train = data["train"].reset_index(drop=True) masks = scenario_masks(train, spec.scenarios) theirs = _original("subgrupos_puntos_LR_HBN.csv") horizons = list(spec.borders[1:]) for e in report["escenarios"]: mask = masks[e["escenario"]] months, event = train["months"][mask].to_numpy(), train["event"][mask].to_numpy(bool) km, _, _ = curves.kaplan_meier(months, event, horizons[-1]) ours = np.array(e["points"]["COMB"]["S"]) assert ours == pytest.approx(km[horizons], abs=CALIBRATION), e["escenario"] original = theirs[(theirs["subgrupo"] == e["escenario"]) & (theirs["modelo"] == "COMB")] gap = np.abs(ours - original.sort_values("meses")["S"].to_numpy()).max() print(f"{e['escenario']}: {TRAIN_FRACTION:.0%} training, gap to the original {gap:.3f}")