Files
models/tests/test_cama_models.py
T

50 lines
2.5 KiB
Python

"""CaMa's models give the current platform's predictions on its own cohort (the reference
fixtures), read in the platform's timeline shape."""
import json
from pathlib import Path
import numpy as np
import pandas as pd
from models.cama.specs import MODELS
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cama"
TRAINED_ON = "2026-11-24" # the day the reference was trained: its follow-up ends there
TYPES = {"nacimiento": "birth", "defuncion": "death", "biopsia": "biopsy"}
CODES = {"CARCINOMA_INVASOR": "invasive", "CARCINOMA_IN_SITU": "in_situ", "BENIGNO": "benign"}
def _timelines() -> pd.DataFrame:
"""The reference cohort's members (first invasive biopsy report in the window) with their
events, as gold.cama_events gives them."""
old = pd.read_parquet(REFERENCE / "cohorts" / "cama" / "cohorte_total" / "dbt" / "1.parquet")
old = old[old["tipo"].isin(TYPES)]
events = pd.DataFrame({
"person_id": old["pac_id"].astype(str), "date": pd.to_datetime(old["fecha"]),
"type": old["tipo"].map(TYPES), "value_code": old["valor_codigo"].map(CODES),
"value_num": old["valor_numerico"], "source_table": old["fuente_tabla"],
"source_id": old["fuente_id"],
"record_number": "CAMA" + old["pac_id"].astype(str).str.zfill(4),
}) # fmt: skip
invasive = events[(events["type"] == "biopsy") & (events["value_code"] == "invasive")]
index = invasive.groupby("person_id")["date"].min().rename("index_date")
index = index[(index >= "2018-01-01") & (index < "2027-01-01")]
return events.merge(index, left_on="person_id", right_index=True)
def test_survival_matches_the_current_model():
spec = MODELS["survival"]
events = _timelines()
model, metrics, _ = spec.train(events, pd.Timestamp(TRAINED_ON).date())
current = json.loads((REFERENCE / "models.json").read_text())["survival"]["version"]
for name in ("n_train", "n_test", "stack_w_lr_6m", "stack_w_lr_12m", "stack_w_lr_18m"):
assert metrics[name] == current["metrics"][name], name
ours = spec.predict(model, events)
ref = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
ref = ref.assign(person_id=ref["pac_id"].astype(str), horizon_years=ref["horizonte_anios"])
both = ours.merge(ref, on=["person_id", "horizon_years"], validate="1:1")
assert len(both) == len(ref) == len(ours)
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()
np.testing.assert_allclose(both["probability"], both["probabilidad"], rtol=1e-6)