Post-colposcopy scenario reads the cohort of the first surveillance visit

cin2_pim_post_colposcopy now reads cacu/cohorte_post_colposcopia_visita_1 (dbt): Cheung et al. 2020 index the risk at
the first surveillance visit with a cotest, not at the first cytology. Its description states the provisional
assumption that a colposcopy without a biopsy order is below CIN2.

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 19:52:02 -06:00
parent 7d50786ac2
commit 06829a4498
12 changed files with 4 additions and 922 deletions
@@ -1,15 +1,16 @@
domain = "cacu"
scenario = "cin2_pim_post_colposcopy"
cohort = "cacu/cohorte_post_colposcopia"
cohort = "cacu/cohorte_post_colposcopia_visita_1"
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 \
Prototipo: riesgo acumulado de CIN2+ desde la primera visita de vigilancia (co-test) 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."""
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. PROVISIONAL: una colposcopía sin orden de biopsia (impresión normal) se toma \
sin CIN2+, lo que supone que la impresión colposcópica no omite ningún CIN2+."""
[config]
horizons_years = [0.0, 1.0, 3.0, 5.0]
-1
View File
@@ -1 +0,0 @@
"""CaCu's cohorts: the surveillance cohort."""
-90
View File
@@ -1,90 +0,0 @@
"""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
@@ -1,63 +0,0 @@
# 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
@@ -1,88 +0,0 @@
"""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
@@ -1,58 +0,0 @@
# 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"
-107
View File
@@ -1,107 +0,0 @@
"""El marco de la cohorte de vigilancia de CaCu, desde la línea de tiempo (`cohorte_vigilancia.toml`).
Las reglas 0.2.0 del kit de campo, sobre las filas de la línea de tiempo de dbt
(`cacu_linea_de_tiempo`) en lugar de SQL sobre tablas. Una fila del marco por miembro, con el desenlace como lo
pide el modelo de mezcla prevalencia–incidencia (Modelo-cacu):
c 1 = evento en la ventana basal; 0 = sin evento basal; -999 = estado basal desconocido
l, r el intervalo (l, r] en que aparece el evento, en años desde la índice.
Con c = 1 valen -999. r nulo = sin evento hasta el corte.
Quién entra:
- la índice es la primera citología de toda la historia, si cae en la ventana;
- se excluye a quien tuvo una biopsia con el desenlace antes de la índice;
- y luego a quien no tiene resultado citológico (escamoso o glandular) ni de VPH en la índice.
El desenlace solo se observa al verificar: una biopsia (positiva o negativa) o, con
`negativo_da_l`, un tamizaje completamente negativo posterior (`no_prevalente`).
Con `negativo_confirma_no_prevalente`, ese tamizaje vuelve c = 0 a quien era -999.
"""
from collections import defaultdict
from dataclasses import dataclass
from datetime import date
DIAS_POR_ANIO = 365.25
SIN_ESTADO = -999
@dataclass(frozen=True)
class Member:
pac_id: int
fecha_indice: date
indice_fuente_tabla: str
indice_fuente_id: str
variables: dict # nombre -> valor; un valor nulo no se guarda
def _by_patient(filas):
pacientes = defaultdict(list)
for fila in filas:
pacientes[fila["pac_id"]].append(fila)
return pacientes
def frame(filas, reglas: dict, inicio: date, fin: date, corte: date) -> tuple[list[Member], list[tuple[str, int]]]:
"""(miembros, atrición). `filas`: la línea de tiempo de CaCu, ya recortada al corte (`hasta=corte`)."""
grados = set(reglas["grados_evento"])
ventana = int(reglas["ventana_basal_dias"])
pap_negativo = set(reglas["no_prevalente"]["pap"])
vph_negativo = set(reglas["no_prevalente"]["vph"])
candidatas = evento_previo = sin_resultado = 0
miembros = []
for pac_id, eventos in sorted(_by_patient(filas).items()):
eventos = [e for e in eventos if e["fecha"] <= corte]
resultado = {(e["fuente_tabla"], e["fuente_id"]): e["valor_codigo"] for e in eventos if e["tipo"] == "bethesda"}
vph = {(e["fuente_tabla"], e["fuente_id"]): e["valor_codigo"] for e in eventos if e["tipo"] == "vph"}
glandular = {(e["fuente_tabla"], e["fuente_id"]) for e in eventos if e["tipo"] == "glandular" and e["valor_codigo"]}
tomas = sorted((e for e in eventos if e["tipo"] == "citologia"), key=lambda e: (e["fecha"], e["fuente_id"]))
if not tomas or not (inicio <= tomas[0]["fecha"] < fin):
continue
indice = tomas[0]
llave = (indice["fuente_tabla"], indice["fuente_id"])
fecha_indice, pap_0, hpv_0 = indice["fecha"], resultado.get(llave), vph.get(llave)
candidatas += 1
biopsias = [(e["fecha"], e["valor_codigo"] in grados) for e in eventos if e["tipo"] == "biopsia"]
if any(positiva and fecha < fecha_indice for fecha, positiva in biopsias):
evento_previo += 1
continue
if pap_0 is None and hpv_0 is None and llave not in glandular:
sin_resultado += 1
continue
verificaciones = [((fecha - fecha_indice).days, positiva, "biopsia")
for fecha, positiva in biopsias if fecha >= fecha_indice]
if reglas["negativo_da_l"]:
for toma in tomas[1:]:
clave = (toma["fuente_tabla"], toma["fuente_id"])
if toma["fecha"] > fecha_indice and resultado.get(clave) in pap_negativo and vph.get(clave) in vph_negativo:
verificaciones.append(((toma["fecha"] - fecha_indice).days, False, "tamizaje"))
positivas = [d for d, positiva, _ in verificaciones if positiva]
primera_positiva = min(positivas) if positivas else None
negativas = [d for d, positiva, _ in verificaciones
if not positiva and (primera_positiva is None or d < primera_positiva)]
ultima_negativa = max(negativas) if negativas else None
if primera_positiva is not None and primera_positiva <= ventana:
c = 1
elif any(not positiva and tipo == "biopsia" and d <= ventana for d, positiva, tipo in verificaciones):
c = 0
elif pap_0 in pap_negativo and hpv_0 in vph_negativo:
c = 0
elif reglas["negativo_confirma_no_prevalente"] and ultima_negativa is not None:
c = 0
else:
c = SIN_ESTADO
if c == 1:
l = r = SIN_ESTADO
else:
l = (ultima_negativa or 0) / DIAS_POR_ANIO if c == 0 else 0
r = None if primera_positiva is None else primera_positiva / DIAS_POR_ANIO
miembros.append(Member(pac_id, fecha_indice, *llave,
{"c": c, "l": l, "r": r, "pap_0": pap_0, "hpv_0": hpv_0}))
atricion = [("candidatas", candidatas), ("sin evento_previo", candidatas - evento_previo),
("sin sin_resultado", len(miembros))]
return miembros, atricion
-78
View File
@@ -1,78 +0,0 @@
# Cohorte de vigilancia de CaCu: quién entra al modelo de riesgo de CIN2+ y con qué marco.
#
# Definición 0.2.0 del kit de campo (indicadores_kit_0/campo/cohortes/cacu/
# cohorte_vigilancia_reglas.toml): mismas reglas y mismo formato de [group.reglas],
# el que lee Modelo-cacu (`reglas_de_toml`). Lo que cambia es de dónde lee: la línea de
# tiempo del kit (`cdm/linea_de_tiempo.py`), no SQL sobre tablas.
#
# Cambiar una regla es cambiar la definición: se sube `version`.
[group]
url = "cacu/cohorte_vigilancia"
version = "0.2.0"
status = "draft"
membership = "definitional"
title = "Mujeres en vigilancia por citología"
expression = "cacu.surveillance:frame"
indice = "Primera citología de la historia de la paciente, si cae en la ventana de reclutamiento"
desenlace = "cin2_mas"
[[group.characteristic]]
code = "evento_previo"
exclude = true
description = "Biopsia con el desenlace antes de la fecha índice: no está en riesgo de un primer evento"
[[group.characteristic]]
code = "sin_resultado"
exclude = true
description = "La citología índice no tiene resultado citológico (escamoso o glandular) ni de VPH: no hay predictores"
[group.reglas]
grados_evento = ["LIEAG", "CIS", "CARCINOMA"]
ventana_basal_dias = 90
negativo_da_l = true
negativo_confirma_no_prevalente = true
colposcopia_negativa = []
[group.reglas.no_prevalente]
pap = ["NORMAL"]
vph = ["NEGATIVO"]
description = "Tamizaje completamente negativo: confirma que no es prevalente"
[group.reglas_estado]
grados_evento = { estado = "vigente", fuente = "Modelo-cacu: desenlace CIN2+; CIN3+ no se puede con este staging (I-K31)" }
no_prevalente = { estado = "vigente", fuente = "Usuario, 2026-10-08 (traspaso_modelos.md M11)" }
negativo_da_l = { estado = "vigente", fuente = "Usuario, 2026-10-08" }
negativo_confirma_no_prevalente = { estado = "vigente", fuente = "Usuario, 2026-10-09 (traspaso_modelos.md M13)" }
ventana_basal_dias = { estado = "sin_definir", fuente = "90 es el valor con que se probó la 0.0.1 de campo; por decidir con quien lleva el modelo" }
colposcopia_negativa = { estado = "sin_definir", fuente = "La colposcopia no tiene fuente en staging (I-K32): vacía, no se lee" }
[[evidenceVariable]]
name = "c"
role = "outcome"
tipo = "numero"
title = "Estado basal: 1 prevalente, 0 no prevalente, -999 desconocido"
[[evidenceVariable]]
name = "l"
role = "outcome"
tipo = "numero"
title = "Último momento sin enfermedad, en años desde la índice (-999 si c = 1)"
[[evidenceVariable]]
name = "r"
role = "outcome"
tipo = "numero"
title = "Primer momento con enfermedad, en años desde la índice (sin fila = sin evento al corte)"
[[evidenceVariable]]
name = "pap_0"
role = "covariate"
tipo = "codigo"
title = "Categoría citológica de la citología índice"
[[evidenceVariable]]
name = "hpv_0"
role = "covariate"
tipo = "codigo"
title = "Resultado de VPH de la misma muestra"
-82
View File
@@ -1,82 +0,0 @@
"""La definición de una cohorte, de su TOML: FHIR `Group` definicional más sus `EvidenceVariable`.
Igual que un Measure: la definición es un archivo (`<proyecto>/<nombre>.toml`),
las reglas clínicas son datos (`[group.reglas]`) y la función que arma el marco se
nombra con `expression` (`modulo:funcion`, relativo a `models.cohorts`).
"""
import hashlib
import json
import tomllib
from dataclasses import dataclass
from importlib import import_module
from pathlib import Path
ROOT = Path(__file__).resolve().parent # `<proyecto>/<nombre>.toml`, next to its rule module
@dataclass(frozen=True)
class Variable:
nombre: str
rol: str # outcome o covariate
tipo: str # numero o codigo
titulo: str
@dataclass(frozen=True)
class Definition:
url: str
version: str
titulo: str
expression: str
desenlace: str
reglas: dict
variables: tuple[Variable, ...]
definicion_sha: str # sha256 del TOML
@property
def reglas_sha(self) -> str:
return json_sha(self.reglas)
def function(self):
"""La función que arma el marco: `funcion(filas_de_linea, reglas, inicio, fin, corte)`."""
return function_of(self.expression)
def json_sha(objeto) -> str:
"""sha256 del JSON canónico: claves ordenadas, sin espacios."""
texto = json.dumps(objeto, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
return hashlib.sha256(texto.encode("utf-8")).hexdigest()
def cohort_path(proyecto: str, nombre: str, *, propuesta: bool = False) -> Path:
"""A cohort's TOML. `propuesta`: from `<proyecto>/proposals/`, which the cycle doesn't build."""
return ROOT / proyecto / ("proposals" if propuesta else "") / f"{nombre}.toml"
def read_definition(ruta: Path) -> Definition:
texto = ruta.read_text(encoding="utf-8")
doc = tomllib.loads(texto)
g = doc["group"]
reglas = dict(g["reglas"])
if "no_prevalente" in reglas: # regla de CaCu: su `description` es texto, no regla
reglas["no_prevalente"] = {k: v for k, v in reglas["no_prevalente"].items() if k != "description"}
variables = tuple(Variable(v["name"], v["role"], v["tipo"], v["title"]) for v in doc["evidenceVariable"])
nombres = [v.nombre for v in variables]
if len(set(nombres)) != len(nombres):
raise ValueError(f"{g['url']}: variables repetidas.")
return Definition(
url=g["url"], version=g["version"], titulo=g["title"], expression=g["expression"],
desenlace=g["desenlace"], reglas=reglas, variables=variables,
definicion_sha=hashlib.sha256(texto.encode("utf-8")).hexdigest(),
)
def function_of(expresion: str):
"""The function of `module:function`, relative to `models.cohorts`. Fails if the module doesn't define it."""
modulo, nombre = expresion.split(":")
function = getattr(import_module(f"models.cohorts.{modulo}"), nombre, None)
if not callable(function):
raise ValueError(f"{modulo} debe definir la función {nombre}.")
return function
-176
View File
@@ -1,176 +0,0 @@
"""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
@@ -1,146 +0,0 @@
"""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"]
-30
View File
@@ -1,30 +0,0 @@
"""What this module covers: `models.cohorts.cacu.surveillance.frame`'s rule for an index cytology without results.
Fixtures: none; each test builds its timeline rows with `_event`.
"""
from datetime import date
from models.cohorts.cacu import surveillance
RULES = {"grados_evento": ["LIEAG"], "ventana_basal_dias": 180, "no_prevalente": {"pap": ["NORMAL"], "vph": ["NEGATIVO"]},
"negativo_da_l": False, "negativo_confirma_no_prevalente": False}
INDEX = date(2025, 1, 1)
def _event(pac_id, tipo, valor=None, fuente_id="a"):
return {"pac_id": pac_id, "fecha": INDEX, "tipo": tipo, "valor_codigo": valor, "fuente_tabla": "citologiacervical",
"fuente_id": f"{pac_id}{fuente_id}"}
def test_a_glandular_result_alone_is_an_index_result():
"""Pins down, as dbt's `cacu_surveillance_excl_no_index_result` does: a member whose index cytology has only a
glandular result (AGC) stays, and one with no result of any kind is left out. Fails if the rule goes back to
reading only the squamous Bethesda and HPV."""
rows = [_event(1, "citologia"), _event(1, "glandular", "AGC"),
_event(2, "citologia"), _event(2, "glandular", None)]
members, attrition = surveillance.frame(rows, RULES, date(2024, 1, 1), date(2026, 1, 1), date(2026, 12, 31))
assert [m.pac_id for m in members] == [1]
assert attrition[-1] == ("sin sin_resultado", 1)