Files
models/tests/test_cacu_models.py
T

115 lines
5.8 KiB
Python

"""The CaCu models compute what the current ones compute: fed the timelines the current
platform built for its cohorts (the reference fixtures, in its codes), each rewritten model
gives the current model's predictions.
Fixed on purpose, so left out of the comparison:
- cin2_logistic's index date: the current estimator reads P(no outcome) as a date
(1970-01-01 for everyone); the rewrite returns the index sample's date.
"""
import json
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from models.cacu.specs import MODELS
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cacu"
RTOL = 1e-6 # as captured (models.json)
# The current platform's cohort cutoff, where the logistic model's follow-up ends.
REFERENCE_CUTOFF = "2026-11-23"
TYPES = {
"citologia": "cytology", "bethesda": "bethesda", "glandular": "glandular", "vph": "hpv",
"vph_genotipo_16_18": "hpv_16_18", "biopsia": "biopsy", "colposcopia": "colposcopy",
"orden_biopsia": "biopsy_order", "tratamiento": "treatment", "antecedente": "history",
"diagnostico": "diagnosis", "nota_medica": "note", "nacimiento": "birth",
"defuncion": "death", "citologia_de_vigilancia": "surveillance_cytology", "orden": "order",
} # fmt: skip
CODES = {
"bethesda": {"NORMAL": "NILM", "LIEBG": "LSIL", "LIEAG": "HSIL"},
"biopsy": {"NORMAL": "normal", "LIEBG": "LSIL", "LIEAG": "HSIL", "CARCINOMA": "carcinoma"},
"hpv": {"POSITIVO": "positive", "NEGATIVO": "negative"},
"cytology": {"SATISFACTORIO": "satisfactory", "INSATISFACTORIO": "unsatisfactory"},
}
COHORTS = {
"cacu_cohort_surveillance": "cohorte_vigilancia",
"cacu_cohort_post_treatment": "cohorte_post_tratamiento",
}
def timelines(cohort: str) -> pd.DataFrame:
"""A reference cohort's timelines in the platform's names and codes."""
found = pd.read_parquet(REFERENCE / "cohorts" / "cacu" / cohort / "dbt" / "1.parquet")
found = found.rename(columns={
"pac_id": "person_id", "fecha_indice": "index_date", "fecha": "date", "tipo": "type",
"valor_codigo": "value_code", "valor_numerico": "value_num",
"fuente_tabla": "source_table", "fuente_id": "source_id",
}) # fmt: skip
found["type"] = found["type"].map(TYPES)
for kind, codes in CODES.items():
rows = found["type"] == kind
found.loc[rows, "value_code"] = found.loc[rows, "value_code"].replace(codes)
return found
@pytest.mark.parametrize("name", ["cin2_pim", "cancer_pim", "cin2_pim_post_treatment",
"cin2_logistic"]) # fmt: skip
def test_predictions_match_the_current_models(name):
spec = MODELS[name]
events = timelines(COHORTS[spec.cohort])
args = (REFERENCE_CUTOFF,) if spec.method == "logistic regression" else ()
model, metrics, _ = spec.train(events, *args)
reference = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet")
current = json.loads((REFERENCE / "models.json").read_text())[name]["version"]["metrics"]
assert metrics["n_train"] == current["n_train"] and metrics["n_test"] == current["n_test"]
found = spec.predict(model, events)
both = found.merge(
reference,
left_on=["person_id", "horizon_years"],
right_on=["pac_id", "horizonte_anios"],
how="outer",
indicator=True,
)
assert (both["_merge"] == "both").all(), "the same patients and horizons are scored"
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
("ci_high", "ic_alto")]: # fmt: skip
if theirs in both:
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)