diff --git a/models/cacu/cancer_pim/__init__.py b/models/cacu/cancer_pim/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/models/cacu/cancer_pim/model.toml b/models/cacu/cancer_pim/model.toml new file mode 100644 index 0000000..86ac9c1 --- /dev/null +++ b/models/cacu/cancer_pim/model.toml @@ -0,0 +1,71 @@ +domain = "cacu" +scenario = "cancer_pim" +cohort = "cacu/cohorte_vigilancia" +outcome = "cancer" +# What a registered version needs to load and predict, pinned to the installed versions when it's logged. +requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"] +# The modules whose functions are the graph's nodes, in `with_modules`. +modules = ["models.cacu.cin2_pim.model", "models.cacu.cin2_pim.report", "models.steps.indexing"] +description = """ +Prototipo: riesgo acumulado de cáncer cervicouterino (biopsia de carcinoma) en la visita índice y a 1, 3 y 5 años, con un \ +modelo de mezcla prevalencia (logística) e incidencia (I-splines de PIMixture) estratificado por el VPH índice, con la \ +citología índice en las categorías de KPNC como covariable, como la columna de cáncer de las tablas de KPNC (Cheung et al. 2020), \ +con la misma cohorte y la misma fecha índice que el modelo de CIN2+ de vigilancia. Sin \ +corrección del sesgo de verificación ni validación clínica.""" + +# The dataflow's config (`with_config`); each key is an input of the nodes that name it. +# What the model's number is, as the patient's screen and the governance pages show it. +[estimand] +quantity = "Riesgo acumulado" +description = "Probabilidad de que la paciente tenga cáncer cervicouterino en la fecha índice o lo desarrolle antes de cada horizonte." +outcome = "Cáncer: biopsia de carcinoma" +index_date = "la última citología con resultado de citología y de VPH, en pacientes sin colposcopía; cada citología nueva es una nueva fecha índice. Sin la historia de visitas previas (aproximación hasta reproducir la tabla 4 de KPNC)" +horizons_unit = "años" + +[config] +horizons_years = [0.0, 1.0, 3.0, 5.0] +# The level of each risk's interval (delta method), given with the estimate; none gives no interval. +risk_interval_level = 0.95 +# From when it predicts: "ultima_citologia" is each patient's latest complete cytology (cytology and HPV results) +# before any colposcopy; patients past a colposcopy belong to the post-colposcopy scenario. Training keeps the cohort's +# index (the first cytology in the window). None predicts from the cohort's index too. +prediction_index = "ultima_citologia" +event_grades = ["CARCINOMA"] +train_fraction = 0.7 +# Provisional: a carcinoma biopsy within this window of the index date counts as prevalent. +prevalent_window_months = 6 +# The index sample's results: the first ones within these days of the index date. +index_sample_days = 30 +# The results that make a visit free of the outcome without a biopsy: every key with one of its values (KPNC: HPV-negative +# with NILM or ASC-US; Cheung et al. 2020, doi:10.1097/LGT.0000000000000528). +known_negative = { bethesda = ["NORMAL", "ASC-US"], vph = ["NEGATIVO"] } +# The incidence's baseline cumulative hazard: { family = "weibull" }, or PIMixture's weakly-parametric +# { family = "ispline", knots = k, order = o }, with k knots at quantiles of each stratum's observed times. The +# finite times are whole years 1-5, so a basis of more than 5 functions (knots + order - 2) isn't identifiable. KPNC +# table 1 is exactly order 4 with 3 knots (bayes-pim, chapter 6). +incidence = { family = "ispline", knots = 3, order = 4 } +# One mixture per value of these features; the other features enter the prevalence, and those listed here the +# incidence. KPNC: stratified by HPV, cytology as covariate (Cheung et al. 2020). +strata = ["hpv_positive"] +incidence_features = ["cytology"] +# A feature of the member's history before the index (e.g. the referral before a colposcopy); none in surveillance. +history = {} +# KPNC's index cytology categories, from least to most severe, and the codes of each from the squamous (Bethesda) and +# the glandular result; the first is the reference. With both results the more severe category wins. Adenocarcinoma +# has no KPNC row: it goes with the high-grade and malignant results. +# The scenario's index and rules, over its source cohort (models/steps/indexing.py): the same as dbt's surveillance +# cohort, applied in the pipeline. The recruitment window is the source cohort's. +[config.index] +kind = "primera_citologia" +event_grades = ["CARCINOMA"] +# PROVISIONAL (sin_definir): the data are left-truncated, so rules on earlier events read only what was recorded; +# 0 keeps everyone. Raise it once the population starts with enough history (S-CPS-20). +observacion_previa_minima_dias = 0 + +[config.cytology] +NILM = ["NORMAL"] +ASC-US = ["ASC-US"] +LSIL = ["LIEBG"] +ASC-H = ["ASC-H"] +AGC = ["AGC"] +"HSIL+" = ["LIEAG", "CIS", "ADENOCARCINOMA"] diff --git a/tests/cacu/test_cancer_pim.py b/tests/cacu/test_cancer_pim.py new file mode 100644 index 0000000..841afcc --- /dev/null +++ b/tests/cacu/test_cancer_pim.py @@ -0,0 +1,54 @@ +"""What this module covers: the `cancer_pim` scenario, the surveillance PIM with carcinoma as the outcome, through its +dataflow and its registered model. + +Fixtures: `cohort_frame`, members of `test_cin2_pim`'s design whose CIN2+ biopsies are carcinomas for a part of them. +""" + +import numpy as np +import pandas as pd +import pytest + +from models.cacu.cin2_pim import model +from models.dags import training +from tests.cacu.test_cin2_pim import cohort_frame as cin2_cohort_frame # noqa: F401 + +SCENARIO = training.Scenario.load("cacu", "cancer_pim") +SURVEILLANCE = training.Scenario.load("cacu", "cin2_pim") + + +@pytest.fixture +def cohort_frame(cin2_cohort_frame): # noqa: F811 + """`test_cin2_pim`'s members with every third LIEAG biopsy reported as carcinoma.""" + frame = cin2_cohort_frame.copy() + lieag = frame.index[(frame["tipo"] == "biopsia") & (frame["valor_codigo"] == "LIEAG")] + frame.loc[lieag[::3], "valor_codigo"] = "CARCINOMA" + return frame + + +def test_the_scenario_is_the_surveillance_model_with_carcinoma_as_the_outcome(): + """Pins down: same dataflow, cohort, index and prediction index as the CIN2+ surveillance model, with carcinoma as + the only event, so the patient's two risks speak of the same visit. Fails if the scenarios drift apart.""" + assert SCENARIO.config["event_grades"] == ["CARCINOMA"] == SCENARIO.config["index"]["event_grades"] + assert SCENARIO.outcome == "cancer" and SCENARIO.cohort == SURVEILLANCE.cohort + assert [m.__name__ for m in SCENARIO.modules] == [m.__name__ for m in SURVEILLANCE.modules] + same = {k: v for k, v in SCENARIO.config.items() if k not in ("event_grades", "index")} + assert same == {k: v for k, v in SURVEILLANCE.config.items() if k not in ("event_grades", "index")} + assert SCENARIO.estimand["outcome"].startswith("Cáncer") + + +def test_the_dataflow_counts_only_carcinomas_as_events(cohort_frame): + """Pins down: a LIEAG biopsy is not a case for this scenario, and the registered model gives a cancer risk no + higher than the CIN2+ model's at the same visit. Fails if `event_grades` stops reaching the coding.""" + run = training.dataflow(*SCENARIO.modules, config=SCENARIO.config).execute( + ["interval_coded_members", "fitted_model"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}}) + coded = run["interval_coded_members"] + carcinomas = set(cohort_frame.loc[cohort_frame["valor_codigo"] == "CARCINOMA", "pac_id"]) + cases = set(coded.loc[(coded["c"] == 1) | np.isfinite(coded["r"]), "pac_id"]) + assert cases == carcinomas + + cin2 = training.dataflow(*SURVEILLANCE.modules, config=SURVEILLANCE.config).execute( + ["fitted_model"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}})["fitted_model"] + h = len(SCENARIO.config["horizons_years"]) + cancer, cin2plus = (m.predict_proba(cohort_frame)[:, 1:1 + h] for m in (run["fitted_model"], cin2)) + scored = ~np.isnan(cancer) & ~np.isnan(cin2plus) + assert scored.any() and (cancer[scored] <= cin2plus[scored] + 1e-6).all() diff --git a/tests/reports/test_templates.py b/tests/reports/test_templates.py index bb6912a..2011d05 100644 --- a/tests/reports/test_templates.py +++ b/tests/reports/test_templates.py @@ -13,7 +13,7 @@ def test_the_cacu_templates_are_listed_with_the_scenarios_they_serve(): found = {t["id"]: t for t in notebook_templates("cacu")} pim, survival = found["cacu/cin2_pim/reporte_subgrupos"], found["cacu/survival/reporte_subgrupos"] - assert pim["scenarios"] == ["cin2_pim", "cin2_pim_post_colposcopy", "cin2_pim_post_treatment"] + assert pim["scenarios"] == ["cancer_pim", "cin2_pim", "cin2_pim_post_colposcopy", "cin2_pim_post_treatment"] assert survival["scenarios"] == ["survival"] and survival["domain"] == "cacu" and survival["title"]