Shared interval survival for CaMa and CaCu, one jobs module for every domain, Dagster train and score by domain

This commit is contained in:
Roberto Treviño
2026-11-25 23:20:52 -06:00
parent d3d9cc3950
commit e2f7e95e83
12 changed files with 661 additions and 65 deletions
+31
View File
@@ -81,3 +81,34 @@ def test_predictions_match_the_current_models(name):
np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, atol=0)
if spec.method != "logistic regression":
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()
def test_survival_matches_the_current_model_with_its_index_fixed():
"""Indexed at the first biopsy reported as carcinoma or carcinoma in situ (the current
index read only invasive carcinoma, so it indexed nobody; the reference was captured with
that fixed); out: no birth date, a death by the biopsy."""
spec = MODELS["survival"]
events = timelines("cohorte_total").drop(columns="index_date")
events["date"] = pd.to_datetime(events["date"])
events["record_number"] = "CACU" + events["person_id"].astype(str).str.zfill(4)
cases = events[(events["type"] == "biopsy") & events["value_code"].isin(["CIS", "carcinoma"])]
index = cases.groupby("person_id")["date"].min().rename("index_date")
index = index[(index >= "2018-01-01") & (index < "2027-01-01")]
born = set(events.loc[events["type"] == "birth", "person_id"])
died = events[events["type"] == "death"].groupby("person_id")["date"].min()
index = index[index.index.isin(born) & ~(died.reindex(index.index) <= index)]
events = events.merge(index, left_on="person_id", right_index=True)
model, metrics, _ = spec.train(events, pd.Timestamp(REFERENCE_CUTOFF).date())
current = json.loads((REFERENCE / "models.json").read_text())["survival"]["version"]
for name in ("n_train", "n_test", "events_train", "events_test", "stack_w_lr_12m",
"stack_w_lr_36m", "stack_w_lr_60m"): # fmt: skip
assert metrics[name] == pytest.approx(current["metrics"][name], rel=RTOL), name
found = spec.predict(model, events)
reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
both = found.merge(reference, left_on=["person_id", "horizon_years"],
right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip
assert len(both) == len(reference) == len(found)
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
("ci_high", "ic_alto")]: # fmt: skip
np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, equal_nan=True)
+49
View File
@@ -0,0 +1,49 @@
"""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)