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:
@@ -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 +0,0 @@
|
||||
"""CaCu's cohorts: the surveillance cohort."""
|
||||
@@ -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
|
||||
@@ -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"
|
||||
@@ -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
|
||||
@@ -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"
|
||||
@@ -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
|
||||
@@ -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"
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user