cin2_pim post-colposcopy and post-treatment scenarios, and their kit cohorts

Two TOML-only scenarios on cin2_pim's dataflow (KPNC's scenarios 4 and 5): CIN2+, KPNC's three post cytology groups,
the referral grade as history after colposcopy, and the strata that reproduce KPNC's tables 17 and 24 (one mixture per
referral grade; one mixture). The kit definitions of both cohorts mirror the dbt rules, so the WebApi cycle can build
them and KitBuild read them. A notebook describes the scenarios, their encoders and the shared DAG.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
This commit is contained in:
2026-11-20 12:09:40 -06:00
parent bde02109ab
commit 7d50786ac2
14 changed files with 2005 additions and 1 deletions
+1
View File
@@ -34,6 +34,7 @@ WebApi.
| `steps/model_fitting.py` | The classifier steps scenarios share: the temporal split, the classifier chosen by config, the fit and its metrics. |
| `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within one year (`horizons_years`, provisional) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. `model.toml` (names, `modules`: its `model.py` and `steps/model_fitting.py`, and `[config]`) and `model.py` (the dataflow to `labelled_members`, and `fitted_model`: a scikit-learn `Pipeline` that takes the long frame). Its routines' records (ML-01a: `sampling`, `missing_data`, `analytic_method`, `class_balance`, `output_confidence`) are nodes too, and the saver writes them; `train.py` only delegates to `dags/training.py`. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--read db|file] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]`, by default with the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. |
| `cacu/cin2_pim/` | CaCu's CIN2+ prevalence–incidence prototype: the cumulative risk at the index visit and at 1, 3 and 5 years. `PrevalenceIncidenceMixture`, a scikit-learn estimator (logistic prevalence, Weibull or I-spline incidence, `likelihood.py`), one mixture per HPV stratum, fitted to each member's code and interval; the clinical settings (windows, known-negative results, KPNC's cytology categories, the incidence family) in `model.toml`. No correction of verification bias, no clinical validation. Same commands as `cin2_logistic`. |
| `cacu/cin2_pim_post_colposcopy/`, `cacu/cin2_pim_post_treatment/` | `cin2_pim`'s dataflow on the post-colposcopy and post-treatment cohorts (KPNC's scenarios 4 and 5): only a `model.toml`, with KPNC's three post-colposcopy cytology groups and, after colposcopy, the referral grade (`history`). |
| `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios. Cada escenario lleva sus cuadernos en `<escenario>/notebooks/`, fuera del paquete instalado. |
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
| `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. |
+3 -1
View File
@@ -11,7 +11,9 @@ VPH+/NILM como desconocido).
- $\pi(x) = \operatorname{expit}(x^\top\theta)$: probabilidad de NIC2+ en la visita índice (prevalencia, logística).
- $S(t \mid z) = \exp\{-\Lambda_0(t)\, e^{z^\top\beta}\}$: supervivencia libre de NIC2+ incidente (riesgos
proporcionales), con $\Lambda_0$ Weibull, $(t/\lambda)^k$, o los I-splines de PIMixture, $\sum_j e^{\gamma_j} I_j(t)$
(`incidence` en `model.toml`). Una mezcla por estrato de VPH, con la citología índice en las categorías de KPNC.
(`incidence` en `model.toml`). Una mezcla por estrato (`strata`: VPH en el tamizaje,
grado de la referencia después de colposcopía, ninguno después de tratamiento), con la citología índice en las
categorías de KPNC.
- Riesgo acumulado: $CR(t) = \pi + (1-\pi)\,[1 - S(t)]$.
El tiempo se cuenta en años desde la visita índice $T_0$.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,43 @@
domain = "cacu"
scenario = "cin2_pim_post_colposcopy"
cohort = "cacu/cohorte_post_colposcopia"
outcome = "cin2"
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
# The same dataflow as `cin2_pim`; only the cohort and the config change.
modules = ["models.cacu.cin2_pim.model"]
description = """
Prototipo: riesgo acumulado de CIN2+ desde la primera citología después de una colposcopía sin CIN2+, en la visita y a \
1, 3 y 5 años (escenario 4 de ASCCP 2019; tabla 17 de KPNC). Mezcla prevalencia–incidencia con I-splines, una por grado \
de la referencia (bajo o alto), con el VPH y la citología (tres categorías de KPNC) de esa citología como covariables, \
como reproduce exactamente la tabla 17 (capítulo 25 de bayes-pim). CIN2+ porque la biopsia LIEAG no separa CIN2 de CIN3. Sin corrección del sesgo de verificación."""
[config]
horizons_years = [0.0, 1.0, 3.0, 5.0]
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
train_fraction = 0.7
prevalent_window_months = 6
index_sample_days = 30
known_negative = { bethesda = ["NORMAL", "ASC-US"], vph = ["NEGATIVO"] }
incidence = { family = "ispline", knots = 3, order = 4 }
# Chapter 25 of bayes-pim: table 17 is reproduced exactly with one baseline per referral grade, the six HPV × cytology
# curves proportional within it; one baseline per HPV result is not (residual 4e-3).
strata = ["referral_grade"]
incidence_features = ["cytology", "hpv_positive"]
# KPNC groups the post-colposcopy cytology in three: NILM, ASC-US/LSIL and high grade (ASC-H, AGC, HSIL+).
[config.cytology]
NILM = ["NORMAL"]
"ASC-US/LSIL" = ["ASC-US", "LIEBG"]
"High Grade" = ["ASC-H", "AGC", "LIEAG", "CIS", "ADENOCARCINOMA"]
# The referral before the colposcopy (Egemen et al. 2020, doi:10.1097/LGT.0000000000000529): low grade is ASC-US,
# LSIL or HPV-positive NILM; high grade is ASC-H, AGC or HSIL+. The results in `lookback_days` up to the first
# colposcopy, as the cohort's `no_referral_result` rule reads them; a member without one gets none.
[config.history]
feature = "referral_grade"
event = "colposcopia"
lookback_days = 365
levels = ["low", "high"]
low = ["ASC-US/LSIL"]
low_if_hpv_positive = ["NILM"]
high = ["High Grade"]
@@ -0,0 +1,33 @@
domain = "cacu"
scenario = "cin2_pim_post_treatment"
cohort = "cacu/cohorte_post_tratamiento"
outcome = "cin2"
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
# The same dataflow as `cin2_pim`; only the cohort and the config change.
modules = ["models.cacu.cin2_pim.model"]
description = """
Prototipo: riesgo acumulado de CIN2+ desde la primera citología después del tratamiento, en la visita y a 1, 3 y 5 años \
(escenario 5 de ASCCP 2019; tablas 24 y 5 de KPNC). Mezcla prevalencia–incidencia con I-splines, una sola línea \
base, con el VPH y la citología (tres categorías de KPNC) de esa citología como covariables, como reproduce exactamente \
la tabla 24 (capítulo 25 de bayes-pim). Sin estrato de la biopsia previa: \
la biopsia LIEAG no separa CIN2 de CIN3, y por lo mismo el desenlace es CIN2+. Sin corrección del sesgo de verificación."""
[config]
horizons_years = [0.0, 1.0, 3.0, 5.0]
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
train_fraction = 0.7
prevalent_window_months = 6
index_sample_days = 30
known_negative = { bethesda = ["NORMAL", "ASC-US"], vph = ["NEGATIVO"] }
incidence = { family = "ispline", knots = 3, order = 4 }
# Chapter 25 of bayes-pim: table 24 is reproduced exactly with one baseline for its six HPV × cytology curves (and also
# with one per HPV result); the coarser one is kept.
strata = []
incidence_features = ["cytology", "hpv_positive"]
history = {}
# KPNC groups the post-treatment cytology in three: NILM, ASC-US/LSIL and high grade.
[config.cytology]
NILM = ["NORMAL"]
"ASC-US/LSIL" = ["ASC-US", "LIEBG"]
"High Grade" = ["ASC-H", "AGC", "LIEAG", "CIS", "ADENOCARCINOMA"]
+90
View File
@@ -0,0 +1,90 @@
"""The post-colposcopy cohort's frame, from the timeline (`post_colposcopy.toml`).
The same rules as dbt's `cacu_post_colposcopy_*` models, over timeline rows instead of SQL over tables:
- the index is the first cytology more than `colposcopy_result_days` after the patient's first colposcopy, if it
falls in the recruitment window;
- then, in this order, the exclusions `prior_event`, `prior_treatment`, `no_referral_result`, `no_index_result`.
Each exclusion reads only the index and the timeline; a patient may be flagged by several, and attrition charges
each rule only for the members it removes from those it receives.
"""
from collections import defaultdict
from dataclasses import dataclass
from datetime import date
RESULT_TYPES = ("bethesda", "glandular", "vph")
@dataclass(frozen=True)
class Member:
pac_id: int
fecha_indice: date
indice_fuente_tabla: str
indice_fuente_id: str
variables: dict # name -> value
def _by_patient(filas):
patients = defaultdict(list)
for fila in filas:
patients[fila["pac_id"]].append(fila)
return patients
def _index(events, rules: dict, inicio: date, fin: date):
"""(index cytology, first colposcopy date), or None when the patient has no index in the window."""
colposcopies = [e["fecha"] for e in events if e["tipo"] == "colposcopia"]
if not colposcopies:
return None
colposcopy = min(colposcopies)
wait = int(rules["colposcopy_result_days"])
cytologies = sorted((e for e in events if e["tipo"] == "citologia" and (e["fecha"] - colposcopy).days > wait),
key=lambda e: (e["fecha"], e["fuente_id"]))
if not cytologies or not (inicio <= cytologies[0]["fecha"] < fin):
return None
return cytologies[0], colposcopy
def frame(filas, reglas: dict, inicio: date, fin: date, corte: date) -> tuple[list[Member], list[tuple[str, int]]]:
"""(members, attrition). `filas`: the CaCu timeline, already cut at the cut-off (`hasta=corte`)."""
grades = set(reglas["event_grades"])
lookback = int(reglas["referral_lookback_days"])
candidates = []
for pac_id, events in sorted(_by_patient(filas).items()):
events = [e for e in events if e["fecha"] <= corte]
found = _index(events, reglas, inicio, fin)
if found:
candidates.append((pac_id, events, *found))
def prior_event(events, index, colposcopy):
return any(e["tipo"] == "biopsia" and e["fecha"] < index["fecha"] and e["valor_codigo"] in grades for e in events)
def prior_treatment(events, index, colposcopy):
return any(e["tipo"] == "tratamiento" and e["fecha"] < index["fecha"] for e in events)
def no_referral_result(events, index, colposcopy):
return not any(e["tipo"] in RESULT_TYPES and e["valor_codigo"] is not None
and 0 <= (colposcopy - e["fecha"]).days <= lookback for e in events)
def no_index_result(events, index, colposcopy):
return not any(e["tipo"] in RESULT_TYPES and e["valor_codigo"] is not None
and (e["fuente_tabla"], e["fuente_id"]) == (index["fuente_tabla"], index["fuente_id"])
for e in events)
attrition = [("candidatas", len(candidates))]
for name, rule in (("prior_event", prior_event), ("prior_treatment", prior_treatment),
("no_referral_result", no_referral_result), ("no_index_result", no_index_result)):
candidates = [c for c in candidates if not rule(*c[1:])]
attrition.append((f"sin {name}", len(candidates)))
members = []
for pac_id, events, index, _ in candidates:
key = (index["fuente_tabla"], index["fuente_id"])
values = {t: next((e["valor_codigo"] for e in events if e["tipo"] == t and (e["fuente_tabla"], e["fuente_id"]) == key
and e["valor_codigo"] is not None), None) for t in RESULT_TYPES}
members.append(Member(pac_id, index["fecha"], *key,
{"pap_0": values["bethesda"], "glandular_0": values["glandular"], "hpv_0": values["vph"]}))
return members, attrition
+63
View File
@@ -0,0 +1,63 @@
# Cohorte posterior a colposcopia de CaCu: mujeres con su primera citología tras la primera colposcopia.
#
# Same index and exclusions, in the same order and with the same names, as the dbt models
# (Transformation/models/cacu/cohorts/post_colposcopy); parameters are the dbt vars `post_colposcopy_cohort`.
# Changing a rule changes the definition: bump `version`.
[group]
url = "cacu/cohorte_post_colposcopia"
version = "0.1.0"
status = "draft"
membership = "definitional"
title = "Mujeres tras colposcopia, por citología"
expression = "cacu.post_colposcopy:frame"
indice = "Primera citología más de colposcopy_result_days después de la primera colposcopia, si cae en la ventana de reclutamiento"
desenlace = "cin2_mas"
[[group.characteristic]]
code = "prior_event"
exclude = true
description = "Biopsia con el desenlace antes de la fecha índice"
[[group.characteristic]]
code = "prior_treatment"
exclude = true
description = "Tratada antes de la fecha índice: pertenece a la cohorte posterior al tratamiento"
[[group.characteristic]]
code = "no_referral_result"
exclude = true
description = "Sin resultado citológico ni de VPH en los referral_lookback_days hasta la colposcopia"
[[group.characteristic]]
code = "no_index_result"
exclude = true
description = "La citología índice no tiene resultado citológico (escamoso o glandular) ni de VPH"
[group.reglas]
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
colposcopy_result_days = 90
referral_lookback_days = 365
[group.reglas_estado]
event_grades = { estado = "vigente", fuente = "Desenlace CIN2+; LIEAG junta CIN2 y CIN3, así que CIN3+ no se puede leer" }
colposcopy_result_days = { estado = "sin_definir", fuente = "Valor provisional: 90 es nuestro, no de KPNC; por decidir con quien lleva el modelo" }
referral_lookback_days = { estado = "sin_definir", fuente = "Valor provisional: 365 cubre una derivación y su espera; por decidir con quien lleva el modelo" }
[[evidenceVariable]]
name = "pap_0"
role = "covariate"
tipo = "codigo"
title = "Squamous Bethesda category of the index cytology"
[[evidenceVariable]]
name = "glandular_0"
role = "covariate"
tipo = "codigo"
title = "Glandular category of the index cytology"
[[evidenceVariable]]
name = "hpv_0"
role = "covariate"
tipo = "codigo"
title = "HPV result of the same sample"
+88
View File
@@ -0,0 +1,88 @@
"""The post-treatment cohort's frame, from the timeline (`post_treatment.toml`).
The same rules as dbt's `cacu_post_treatment_*` models, over timeline rows instead of SQL over tables:
- the index is the first cytology more than `index_after_days` after the patient's first treatment, if it falls in
the recruitment window;
- then, in this order, the exclusions `no_pretreatment_biopsy`, `event_before_index`, `no_index_result`.
Each exclusion reads only the index and the timeline; a patient may be flagged by several, and attrition charges
each rule only for the members it removes from those it receives.
"""
from collections import defaultdict
from dataclasses import dataclass
from datetime import date
RESULT_TYPES = ("bethesda", "glandular", "vph")
@dataclass(frozen=True)
class Member:
pac_id: int
fecha_indice: date
indice_fuente_tabla: str
indice_fuente_id: str
variables: dict # name -> value
def _by_patient(filas):
patients = defaultdict(list)
for fila in filas:
patients[fila["pac_id"]].append(fila)
return patients
def _index(events, rules: dict, inicio: date, fin: date):
"""(index cytology, first treatment date), or None when the patient has no index in the window."""
treatments = [e["fecha"] for e in events if e["tipo"] == "tratamiento"]
if not treatments:
return None
treatment = min(treatments)
wait = int(rules["index_after_days"])
cytologies = sorted((e for e in events if e["tipo"] == "citologia" and (e["fecha"] - treatment).days > wait),
key=lambda e: (e["fecha"], e["fuente_id"]))
if not cytologies or not (inicio <= cytologies[0]["fecha"] < fin):
return None
return cytologies[0], treatment
def frame(filas, reglas: dict, inicio: date, fin: date, corte: date) -> tuple[list[Member], list[tuple[str, int]]]:
"""(members, attrition). `filas`: the CaCu timeline, already cut at the cut-off (`hasta=corte`)."""
grades = set(reglas["event_grades"])
lookback = int(reglas["pretreatment_lookback_days"])
candidates = []
for pac_id, events in sorted(_by_patient(filas).items()):
events = [e for e in events if e["fecha"] <= corte]
found = _index(events, reglas, inicio, fin)
if found:
candidates.append((pac_id, events, *found))
def no_pretreatment_biopsy(events, index, treatment):
return not any(e["tipo"] == "biopsia" and e["valor_codigo"] is not None
and 0 <= (treatment - e["fecha"]).days <= lookback for e in events)
def event_before_index(events, index, treatment):
return any(e["tipo"] == "biopsia" and treatment < e["fecha"] < index["fecha"] and e["valor_codigo"] in grades
for e in events)
def no_index_result(events, index, treatment):
return not any(e["tipo"] in RESULT_TYPES and e["valor_codigo"] is not None
and (e["fuente_tabla"], e["fuente_id"]) == (index["fuente_tabla"], index["fuente_id"])
for e in events)
attrition = [("candidatas", len(candidates))]
for name, rule in (("no_pretreatment_biopsy", no_pretreatment_biopsy), ("event_before_index", event_before_index),
("no_index_result", no_index_result)):
candidates = [c for c in candidates if not rule(*c[1:])]
attrition.append((f"sin {name}", len(candidates)))
members = []
for pac_id, events, index, _ in candidates:
key = (index["fuente_tabla"], index["fuente_id"])
values = {t: next((e["valor_codigo"] for e in events if e["tipo"] == t and (e["fuente_tabla"], e["fuente_id"]) == key
and e["valor_codigo"] is not None), None) for t in RESULT_TYPES}
members.append(Member(pac_id, index["fecha"], *key,
{"pap_0": values["bethesda"], "glandular_0": values["glandular"], "hpv_0": values["vph"]}))
return members, attrition
+58
View File
@@ -0,0 +1,58 @@
# Cohorte posterior a tratamiento de CaCu: mujeres con su primera citología tras el primer tratamiento.
#
# Same index and exclusions, in the same order and with the same names, as the dbt models
# (Transformation/models/cacu/cohorts/post_treatment); parameters are the dbt vars `post_treatment_cohort`.
# Changing a rule changes the definition: bump `version`.
[group]
url = "cacu/cohorte_post_tratamiento"
version = "0.1.0"
status = "draft"
membership = "definitional"
title = "Mujeres tras tratamiento, por citología"
expression = "cacu.post_treatment:frame"
indice = "Primera citología más de index_after_days después del primer tratamiento, si cae en la ventana de reclutamiento"
desenlace = "cin2_mas"
[[group.characteristic]]
code = "no_pretreatment_biopsy"
exclude = true
description = "Sin biopsia reportada en los pretreatment_lookback_days hasta el tratamiento"
[[group.characteristic]]
code = "event_before_index"
exclude = true
description = "Biopsia con el desenlace entre el tratamiento y la fecha índice"
[[group.characteristic]]
code = "no_index_result"
exclude = true
description = "La citología índice no tiene resultado citológico (escamoso o glandular) ni de VPH"
[group.reglas]
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
index_after_days = 90
pretreatment_lookback_days = 365
[group.reglas_estado]
event_grades = { estado = "vigente", fuente = "Desenlace CIN2+; LIEAG junta CIN2 y CIN3, así que CIN3+ no se puede leer" }
index_after_days = { estado = "sin_definir", fuente = "Valor provisional: 90 días tras el tratamiento; por decidir con quien lleva el modelo" }
pretreatment_lookback_days = { estado = "sin_definir", fuente = "Valor provisional: 365 días hasta el tratamiento; por decidir con quien lleva el modelo" }
[[evidenceVariable]]
name = "pap_0"
role = "covariate"
tipo = "codigo"
title = "Squamous Bethesda category of the index cytology"
[[evidenceVariable]]
name = "glandular_0"
role = "covariate"
tipo = "codigo"
title = "Glandular category of the index cytology"
[[evidenceVariable]]
name = "hpv_0"
role = "covariate"
tipo = "codigo"
title = "HPV result of the same sample"
+44
View File
@@ -231,3 +231,47 @@ def test_the_index_cytology_takes_kpncs_categories_not_a_binary():
found = model.index_results(frame, CONFIG["index_sample_days"], CONFIG["cytology"])
assert found["cytology"].tolist() == ["LSIL", "HSIL+", None, "AGC", "HSIL+", "HSIL+"]
POST_COLPOSCOPY = training.Scenario.load("cacu", "cin2_pim_post_colposcopy")
def _with_referral(rows, pac_id, index, bethesda, vph, colposcopy_days=-200, referral_days=-300):
"""A member's rows plus a referral result and a colposcopy before her index date."""
return rows + [*_visit(pac_id, index, referral_days, bethesda, vph), _row(pac_id, index, colposcopy_days, "colposcopia")]
def test_the_referral_grade_follows_kpncs_low_and_high_grade():
"""Pins down the history of the post-colposcopy TOML: HPV-positive NILM and LSIL referrals are low grade, ASC-H
high, an HPV-negative NILM refers no one and a result past the lookback doesn't count. Fails if the grade stops
reading the referral before the colposcopy, its HPV condition or the lookback."""
config = POST_COLPOSCOPY.config
rows = []
for pac_id, (bethesda, vph, referral_days) in enumerate([("NORMAL", "POSITIVO", -300), ("LIEBG", "NEGATIVO", -300),
("ASC-H", "NEGATIVO", -300), ("NORMAL", "NEGATIVO", -300),
("ASC-H", "POSITIVO", -700)], start=1):
rows = _with_referral(rows + _member(pac_id, INDEX, "NORMAL", "NEGATIVO"), pac_id, INDEX, bethesda, vph,
referral_days=referral_days)
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
found = model.index_results(frame, config["index_sample_days"], config["cytology"], config["history"])
assert found["referral_grade"].tolist() == ["low", "low", "high", None, None]
assert found["cytology"].tolist() == ["NILM"] * 5
def test_the_post_colposcopy_scenario_runs_on_the_shared_dataflow(cohort_frame):
"""Pins down that a scenario is only its TOML: the post-colposcopy one runs `cin2_pim`'s dataflow with its own
cytology groups and referral grade, and gives metrics at every horizon. Fails if the shared dataflow stops taking
the history from the config or a scenario needs code of its own."""
rows = cohort_frame.to_dict("records")
for pac_id, group in cohort_frame.groupby("pac_id"):
index = group["fecha_indice"].iloc[0]
rows = _with_referral(rows, pac_id, index, "ASC-H" if pac_id % 3 == 0 else "LIEBG", "POSITIVO")
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
found = training.dataflow(*POST_COLPOSCOPY.modules, config=POST_COLPOSCOPY.config).execute(
["metrics"], inputs={"cohort": frame})["metrics"]
assert {f"n_known_{h:g}y" for h in POST_COLPOSCOPY.config["horizons_years"]} <= set(found)
assert training.Scenario.load("cacu", "cin2_pim_post_treatment").cohort == "cacu/cohorte_post_tratamiento"
+176
View File
@@ -0,0 +1,176 @@
"""What this module covers: `models.cohorts.cacu.post_colposcopy.frame`: the index cytology, each exclusion in its
order, the attrition counts, and the definition's TOML.
Fixtures: none; each test builds its timeline rows with `_row`.
"""
from datetime import date, timedelta
from models.cohorts.cacu import post_colposcopy
from models.cohorts.definition import cohort_path, read_definition
RULES = {"event_grades": ["LIEAG", "CIS", "CARCINOMA"], "colposcopy_result_days": 90, "referral_lookback_days": 365}
START, END, CUTOFF = date(2025, 1, 1), date(2026, 1, 1), date(2026, 12, 31)
COLPOSCOPY = date(2025, 1, 1)
def _row(pac_id, tipo, fecha, valor=None, fuente_id="a", fuente_tabla="t"):
return {"pac_id": pac_id, "fecha": fecha, "tipo": tipo, "valor_codigo": valor, "fuente_tabla": fuente_tabla,
"fuente_id": f"{pac_id}{fuente_id}"}
def _after(days):
return COLPOSCOPY + timedelta(days=days)
def _patient(pac_id, *extra, referral=True, index_result="LIEBG"):
"""A patient with a colposcopy, a referral result 30 days before it, and an index cytology 200 days after."""
rows = [_row(pac_id, "colposcopia", COLPOSCOPY, fuente_id="c"),
_row(pac_id, "citologia", _after(200), fuente_id="i")]
if referral:
rows.append(_row(pac_id, "bethesda", _after(-30), "ASC-US", fuente_id="r"))
if index_result:
rows.append(_row(pac_id, "bethesda", _after(200), index_result, fuente_id="i"))
return rows + list(extra)
def _run(rows, rules=RULES):
return post_colposcopy.frame(rows, rules, START, END, CUTOFF)
def test_index_is_the_first_cytology_after_the_biopsy_window():
"""Pins down, as dbt's index unit test does: a cytology 30 days after the colposcopy is within the biopsy
window and doesn't count; the one at 200 days is the index, even with a later colposcopy. A patient with no
colposcopy, and one whose first cytology falls outside the recruitment window, have no index. Fails if the index
stops waiting for the biopsies, takes a later colposcopy, or ignores the window."""
rows = _patient(1, _row(1, "colposcopia", _after(59), fuente_id="c2"), _row(1, "citologia", _after(30), fuente_id="e"))
rows += [_row(2, "citologia", _after(200), fuente_id="d"), _row(2, "bethesda", _after(200), "LIEBG", fuente_id="d")]
rows += [_row(3, "colposcopia", date(2025, 11, 1), fuente_id="c"), _row(3, "citologia", date(2026, 6, 1), fuente_id="e"),
_row(3, "bethesda", date(2026, 6, 1), "LIEBG", fuente_id="e"), _row(3, "bethesda", date(2025, 10, 1), "LIEBG", fuente_id="r")]
members, attrition = _run(rows)
assert [(m.pac_id, m.fecha_indice, m.indice_fuente_id) for m in members] == [(1, _after(200), "1i")]
assert attrition[0] == ("candidatas", 1)
def test_index_needs_more_than_the_wait_days():
"""Pins down: a cytology exactly `colposcopy_result_days` after the colposcopy is too early, one day more is
the index. Fails if the comparison becomes `>=`."""
rows = [_row(1, "colposcopia", COLPOSCOPY, fuente_id="c"), _row(1, "bethesda", _after(-1), "LIEBG", fuente_id="r"),
_row(1, "citologia", _after(90), fuente_id="x"), _row(1, "citologia", _after(91), fuente_id="y"),
_row(1, "vph", _after(91), "POSITIVO", fuente_id="y")]
members, _ = _run(rows)
assert [m.indice_fuente_id for m in members] == ["1y"]
def test_index_ignores_cytologies_after_the_cutoff():
"""Pins down: a cytology after the cut-off is not an index. Fails if the cut-off stops applying."""
rows = _patient(1)
members, attrition = post_colposcopy.frame(rows, RULES, START, END, _after(100))
assert members == [] and attrition[0] == ("candidatas", 0)
def test_member_carries_the_index_results():
"""Pins down: the member's variables are the squamous, glandular and HPV results of the index cytology only,
and a missing one is None. Fails if results of other samples leak in or a variable is renamed."""
rows = _patient(1, _row(1, "glandular", _after(200), "AGC", fuente_id="i"),
_row(1, "vph", _after(250), "POSITIVO", fuente_id="z"))
members, _ = _run(rows)
assert members[0].variables == {"pap_0": "LIEBG", "glandular_0": "AGC", "hpv_0": None}
def test_prior_event_excludes_a_biopsy_with_the_outcome_before_the_index():
"""Pins down: a CIN2+ biopsy before the index date flags the patient; a negative one, or a CIN2+ on the index
date, doesn't. Fails if the event grades or the strict `<` change."""
rows = (_patient(1, _row(1, "biopsia", _after(10), "CIS")) + _patient(2, _row(2, "biopsia", _after(10), "NEGATIVO"))
+ _patient(3, _row(3, "biopsia", _after(200), "LIEAG")))
members, attrition = _run(rows)
assert [m.pac_id for m in members] == [2, 3]
assert attrition[:2] == [("candidatas", 3), ("sin prior_event", 2)]
def test_prior_treatment_excludes_a_treatment_before_the_index():
"""Pins down: a treatment before the index date flags the patient (she belongs to the post-treatment cohort); one
on the index date doesn't. Fails if the interval's end or the event type change."""
rows = (_patient(1, _row(1, "tratamiento", _after(100))) + _patient(2, _row(2, "tratamiento", _after(200))))
members, attrition = _run(rows)
assert [m.pac_id for m in members] == [2]
assert attrition[2] == ("sin prior_treatment", 1)
def test_no_referral_result_looks_back_from_the_colposcopy():
"""Pins down, as dbt's unit test does: a result 100 days before the colposcopy is the referral and the patient
stays; one 400 days before (past the lookback) or one after the colposcopy leaves her out; 365 days exactly
still counts. Fails if the lookback, its direction or the result types change."""
def case(pac_id, tipo, days, valor="LIEBG"):
return _patient(pac_id, _row(pac_id, tipo, _after(days), valor, fuente_id="q"), referral=False)
rows = (case(1, "vph", -100, "POSITIVO") + case(2, "bethesda", -400) + case(3, "bethesda", 14)
+ case(4, "glandular", -365, "AGC") + case(5, "vph", -366, "POSITIVO"))
members, attrition = _run(rows)
assert [m.pac_id for m in members] == [1, 4]
assert attrition[3] == ("sin no_referral_result", 2)
def test_no_referral_result_needs_a_value():
"""Pins down: a referral row without a code is not a result. Fails if null codes start to count."""
rows = _patient(1, _row(1, "bethesda", _after(-10), None, fuente_id="q"), referral=False)
members, _ = _run(rows)
assert members == []
def test_no_index_result_needs_a_result_of_the_index_cytology():
"""Pins down: an index cytology with only a glandular result (or only HPV) stays; one with none, or whose
results belong to another sample, is left out. Fails if the rule reads only the squamous result or ignores the
sample."""
rows = (_patient(1, _row(1, "glandular", _after(200), "AGC", fuente_id="i"), index_result=None)
+ _patient(2, _row(2, "vph", _after(200), "NEGATIVO", fuente_id="i"), index_result=None)
+ _patient(3, index_result=None)
+ _patient(4, _row(4, "bethesda", _after(200), None, fuente_id="i"), index_result=None)
+ _patient(5, _row(5, "vph", _after(250), "POSITIVO", fuente_id="z"), index_result=None))
members, attrition = _run(rows)
assert [m.pac_id for m in members] == [1, 2]
assert attrition[4] == ("sin no_index_result", 2)
def test_attrition_charges_each_rule_only_for_what_it_removes_from_the_rest():
"""Pins down: a patient flagged by several rules is charged to the first in order. Fails if each rule counted
against all candidates."""
rows = _patient(1, _row(1, "biopsia", _after(10), "CIS"), _row(1, "tratamiento", _after(20)), referral=False,
index_result=None)
rows += _patient(2)
members, attrition = _run(rows)
assert [m.pac_id for m in members] == [2]
assert attrition == [("candidatas", 2), ("sin prior_event", 1), ("sin prior_treatment", 1),
("sin no_referral_result", 1), ("sin no_index_result", 1)]
def test_definition_loads_and_resolves_the_frame():
"""Pins down: the TOML loads through `read_definition`, with the dbt rule parameters, and its `expression`
resolves to `post_colposcopy.frame`. Fails if a required key is dropped or the expression is renamed."""
definition = read_definition(cohort_path("cacu", "post_colposcopy"))
assert definition.url == "cacu/cohorte_post_colposcopia"
assert definition.function() is post_colposcopy.frame
assert definition.reglas["event_grades"] == ["LIEAG", "CIS", "CARCINOMA"]
assert (definition.reglas["colposcopy_result_days"], definition.reglas["referral_lookback_days"]) == (90, 365)
assert [v.nombre for v in definition.variables] == ["pap_0", "glandular_0", "hpv_0"]
+146
View File
@@ -0,0 +1,146 @@
"""What this module covers: `models.cohorts.cacu.post_treatment.frame`: the index cytology, each exclusion in its
order, the attrition counts, and the definition's TOML.
Fixtures: none; each test builds its timeline rows with `_row`.
"""
from datetime import date, timedelta
from models.cohorts.cacu import post_treatment
from models.cohorts.definition import cohort_path, read_definition
RULES = {"event_grades": ["LIEAG", "CIS", "CARCINOMA"], "index_after_days": 90, "pretreatment_lookback_days": 365}
START, END, CUTOFF = date(2025, 1, 1), date(2026, 1, 1), date(2026, 12, 31)
TREATMENT = date(2025, 1, 1)
def _row(pac_id, tipo, fecha, valor=None, fuente_id="a", fuente_tabla="t"):
return {"pac_id": pac_id, "fecha": fecha, "tipo": tipo, "valor_codigo": valor, "fuente_tabla": fuente_tabla,
"fuente_id": f"{pac_id}{fuente_id}"}
def _after(days):
return TREATMENT + timedelta(days=days)
def _patient(pac_id, *extra, biopsy=True, index_result="LIEBG"):
"""A patient with a treatment, a biopsy 30 days before it, and an index cytology 180 days after."""
rows = [_row(pac_id, "tratamiento", TREATMENT, fuente_id="x"), _row(pac_id, "citologia", _after(180), fuente_id="i")]
if biopsy:
rows.append(_row(pac_id, "biopsia", _after(-30), "LIEAG", fuente_id="b"))
if index_result:
rows.append(_row(pac_id, "bethesda", _after(180), index_result, fuente_id="i"))
return rows + list(extra)
def _run(rows, rules=RULES):
return post_treatment.frame(rows, rules, START, END, CUTOFF)
def test_index_is_the_first_cytology_past_the_days_after_treatment():
"""Pins down, as dbt's index unit test does: a cytology 60 days after the first treatment is too early; the one
at 180 days is the index, even with a later treatment. A patient never treated has no index. Fails if the index
stops waiting `index_after_days` or takes a later treatment."""
rows = _patient(1, _row(1, "tratamiento", _after(31), fuente_id="x2"), _row(1, "citologia", _after(60), fuente_id="e"))
rows += [_row(2, "citologia", _after(180), fuente_id="c"), _row(2, "bethesda", _after(180), "LIEBG", fuente_id="c")]
members, attrition = _run(rows)
assert [(m.pac_id, m.fecha_indice, m.indice_fuente_id) for m in members] == [(1, _after(180), "1i")]
assert attrition[0] == ("candidatas", 1)
def test_index_needs_more_than_the_wait_days_and_falls_in_the_window():
"""Pins down: a cytology exactly `index_after_days` after the treatment is too early, one day more is the
index; an index outside the recruitment window or after the cut-off gives no member. Fails if the comparison
becomes `>=` or the window/cut-off stop applying."""
base = [_row(1, "tratamiento", TREATMENT, fuente_id="x"), _row(1, "biopsia", _after(-5), "LIEAG", fuente_id="b"),
_row(1, "citologia", _after(90), fuente_id="x"), _row(1, "citologia", _after(91), fuente_id="y"),
_row(1, "vph", _after(91), "POSITIVO", fuente_id="y")]
late = [_row(2, "tratamiento", date(2025, 11, 1), fuente_id="x"), _row(2, "biopsia", date(2025, 10, 1), "LIEAG", fuente_id="b"),
_row(2, "citologia", date(2026, 6, 1), fuente_id="e"), _row(2, "vph", date(2026, 6, 1), "POSITIVO", fuente_id="e")]
members, _ = _run(base + late)
cut, _ = post_treatment.frame(base, RULES, START, END, _after(91 - 1))
assert [m.indice_fuente_id for m in members] == ["1y"]
assert cut == []
def test_member_carries_the_index_results():
"""Pins down: the member's variables are the squamous, glandular and HPV results of the index cytology only,
and a missing one is None. Fails if results of other samples leak in or a variable is renamed."""
rows = _patient(1, _row(1, "glandular", _after(180), "AGC", fuente_id="i"),
_row(1, "vph", _after(250), "POSITIVO", fuente_id="z"))
members, _ = _run(rows)
assert members[0].variables == {"pap_0": "LIEBG", "glandular_0": "AGC", "hpv_0": None}
def test_no_pretreatment_biopsy_looks_back_from_the_treatment():
"""Pins down: a biopsy 365 days before the treatment still counts, 366 days or after the treatment doesn't, and
a biopsy without a code isn't a report. Fails if the lookback, its direction or the null check change."""
def case(pac_id, days, valor="NEGATIVO"):
return _patient(pac_id, _row(pac_id, "biopsia", _after(days), valor, fuente_id="q"), biopsy=False)
rows = case(1, -365) + case(2, -366) + case(3, 10) + case(4, -20, None) + case(5, 0)
members, attrition = _run(rows)
assert [m.pac_id for m in members] == [1, 5]
assert attrition[1] == ("sin no_pretreatment_biopsy", 2)
def test_event_before_index_is_between_treatment_and_index():
"""Pins down, as dbt's unit test does: a CIN2+ biopsy between the treatment and the index is flagged; one before
the treatment, on the treatment date or on the index date isn't; a negative one between them isn't. Fails if
the interval's ends or the grades change."""
rows = (_patient(1, _row(1, "biopsia", _after(60), "LIEAG")) + _patient(2, _row(2, "biopsia", _after(-60), "LIEAG"))
+ _patient(3, _row(3, "biopsia", _after(180), "LIEAG")) + _patient(4, _row(4, "biopsia", _after(60), "NEGATIVO"))
+ _patient(5, _row(5, "biopsia", _after(0), "CIS")))
members, attrition = _run(rows)
assert [m.pac_id for m in members] == [2, 3, 4, 5]
assert attrition[2] == ("sin event_before_index", 4)
def test_no_index_result_needs_a_result_of_the_index_cytology():
"""Pins down: an index cytology with only a glandular result (or only HPV) stays; one with none, or whose
results belong to another sample, is left out. Fails if the rule reads only the squamous result or ignores the
sample."""
rows = (_patient(1, _row(1, "glandular", _after(180), "AGC", fuente_id="i"), index_result=None)
+ _patient(2, _row(2, "vph", _after(180), "NEGATIVO", fuente_id="i"), index_result=None)
+ _patient(3, index_result=None)
+ _patient(4, _row(4, "bethesda", _after(180), None, fuente_id="i"), index_result=None)
+ _patient(5, _row(5, "vph", _after(250), "POSITIVO", fuente_id="z"), index_result=None))
members, attrition = _run(rows)
assert [m.pac_id for m in members] == [1, 2]
assert attrition[3] == ("sin no_index_result", 2)
def test_attrition_charges_each_rule_only_for_what_it_removes_from_the_rest():
"""Pins down: a patient flagged by several rules is charged to the first in order. Fails if each rule counted
against all candidates."""
rows = _patient(1, _row(1, "biopsia", _after(60), "CIS"), biopsy=False, index_result=None) + _patient(2)
members, attrition = _run(rows)
assert [m.pac_id for m in members] == [2]
assert attrition == [("candidatas", 2), ("sin no_pretreatment_biopsy", 1), ("sin event_before_index", 1),
("sin no_index_result", 1)]
def test_definition_loads_and_resolves_the_frame():
"""Pins down: the TOML loads through `read_definition`, with the dbt rule parameters, and its `expression`
resolves to `post_treatment.frame`. Fails if a required key is dropped or the expression is renamed."""
definition = read_definition(cohort_path("cacu", "post_treatment"))
assert definition.url == "cacu/cohorte_post_tratamiento"
assert definition.function() is post_treatment.frame
assert definition.reglas["event_grades"] == ["LIEAG", "CIS", "CARCINOMA"]
assert (definition.reglas["index_after_days"], definition.reglas["pretreatment_lookback_days"]) == (90, 365)
assert [v.nombre for v in definition.variables] == ["pap_0", "glandular_0", "hpv_0"]