84 lines
3.7 KiB
Python
84 lines
3.7 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()
|