Compare commits

...

129 Commits

Author SHA1 Message Date
edgar 206a6c662b No perder la primera visita poscolposcopía por lo que se le hizo después
ci / python (pull_request) Failing after 57m40s
ci / web (pull_request) Failing after 2m24s
2026-12-04 20:40:39 -06:00
edgar 48a5719a06 Usar solo la tabla maestra NCI, con sus intervalos, y aplicar la historia desconocida
ci / python (pull_request) Failing after 59m44s
ci / web (pull_request) Failing after 3m12s
2026-12-04 19:19:17 -06:00
edgar 2f2fcddf7f Generar referencias siempre graduadas, seguimiento menos grave y sin tamizaje desde los 65 2026-12-04 19:06:39 -06:00
edgar 06dc675d7d Publicar CIN2+ y cáncer en la tabla maestra NCI 2026-12-04 18:35:27 -06:00
edgar 75ca7d183f Actualizar la web 2026-12-04 17:49:35 -06:00
edgar 7acc3ceb33 Generar la maestra NCI de las tablas oficiales y usar la historia desconocida 2026-12-04 17:21:44 -06:00
edgar 772075f1fd Decir que la paciente ya fue tratada 2026-12-04 16:47:47 -06:00
edgar 0c434436a3 Actualizar la web 2026-12-04 16:03:08 -06:00
edgar bd221b952b Generar historias sintéticas cortas, desde 2021 2026-12-04 16:03:08 -06:00
edgar c26606c1d0 Retirar de las series la tabla maestra NCI, de procedencia no verificada 2026-12-04 16:03:07 -06:00
edgar 38acca1685 Publicar las referencias de los indicadores CaCu 2026-12-04 16:03:06 -06:00
edgar 4cfa2deefa Contar como caso solo el carcinoma: el carcinoma in situ es NIC3 2026-12-04 16:03:06 -06:00
edgar e067fe17cc Retirar los libros NCI ocultos, las herramientas provisionales y la base Gibbs 2026-12-04 14:17:09 -06:00
edgar 3f02377dac Leer de tablas de oro los libros NCI visibles 2026-12-04 13:12:34 -06:00
edgar a828777e1f Ocultar sin borrar genotipo, postratamiento y segunda visita poscolposcopía, y documentar las referencias NCI 2026-12-04 12:47:12 -06:00
edgar 40cbd6eff7 Leer la maestra NCI de tablas de oro y corregir la derivación por AGC 2026-12-04 12:02:12 -06:00
edgar f043ca14fa Actualizar la web y la API: biopsia CIN 2 y CIN 3, y estilo 2026-12-04 09:12:15 -06:00
edgar 7fc1d90621 Documentar dónde se deciden los requisitos NCI 2026-12-04 09:12:15 -06:00
edgar 2615f931fb Decidir en oro los requisitos NCI y dividir la lectura de riesgos en módulos 2026-12-04 09:12:15 -06:00
edgar 429fd070af Limpiar los avisos de estilo fuera de la parte NCI 2026-12-04 09:12:15 -06:00
edgar 2660f9a312 Actualizar la web: detección anterior y tiempos de CaMa 2026-12-04 05:49:57 -06:00
edgar 0a52c56aec Actualizar la web: rondas por última detección y tiempos escalonados 2026-12-04 05:38:08 -06:00
edgar 757e155247 Añadir la última detección a los datos de demostración de CaCu 2026-12-04 05:04:18 -06:00
edgar 38f6f246b8 Actualizar la web: tipos histológicos en español 2026-12-04 04:42:25 -06:00
edgar 35576087a3 Añadir tipo histológico y tratamientos a los datos de demostración de CaMa 2026-12-04 01:58:18 -06:00
edgar 6abb124a68 Actualizar la web: ronda subsecuente y tratamiento de CaMa 2026-12-04 01:23:41 -06:00
edgar 96b517d826 Medir en CaMa el tiempo de diagnóstico tras biopsia a tratamiento (provisional) 2026-12-04 01:23:41 -06:00
edgar b8367dfc8b Calcular los requisitos del libro 17 sin subconsultas repetidas 2026-12-04 01:23:41 -06:00
edgar 8930d6c5d7 Actualizar la web: ronda subsecuente y citologías anormales 2026-12-04 00:50:27 -06:00
edgar cd6faf412d Proponer el tiempo de diagnóstico a tratamiento en CaMa 2026-12-04 00:50:27 -06:00
edgar f86e4d2f21 Probar el tiempo de diagnóstico tras biopsia a tratamiento y la paridad de CaMa 2026-12-04 00:50:27 -06:00
edgar 1bc85d33c9 Leer de oro los requisitos del libro 17 y quitar sus condiciones en Python 2026-12-03 23:54:38 -06:00
edgar 65bfa44b2e CaMa: medidas de tipo histológico y pantalla de indicadores 2026-12-03 23:47:37 -06:00
edgar 29e903565f Contar en oro lo previo a cada muestra y los requisitos del libro 17 2026-12-03 23:47:37 -06:00
edgar e701b35008 Añadir la foto de lo que responde cada libro NCI 2026-12-03 23:47:37 -06:00
edgar 3a05e23bc9 Contar como 0 días el tratamiento el mismo día del diagnóstico tras biopsia 2026-12-03 23:47:36 -06:00
edgar 5c602372b7 Actualizar la prueba de paridad de CaCu 2026-12-03 22:22:20 -06:00
edgar 622582b7a2 Contar el grupo menor de 25 desde los 15 y declarar las diferencias de paridad 2026-12-03 22:21:59 -06:00
edgar 1292cc3041 Medir el tiempo a tratamiento desde el diagnóstico tras biopsia 2026-12-03 22:21:59 -06:00
edgar b3b4e0ec08 Contar AGC y carcinoma invasor como alto grado en las tablas NCI 2026-12-03 22:21:59 -06:00
edgar 6045cdb2f2 Volver a nombrar como tiempos las medidas de oportunidad 2026-12-03 20:09:50 -06:00
edgar d033c55708 Leer de oro los hechos de la referencia NCI 2026-12-03 20:09:50 -06:00
edgar 7ef330817d Agregar fecha de corte, grupo menor de 25 y antecedentes de detección 2026-12-03 19:33:13 -06:00
edgar a007a71e08 Decidir en oro la detección, el hallazgo glandular y el diagnóstico precolposcópico 2026-12-03 19:27:21 -06:00
edgar cbdbc9c8e2 Unificar el enlace con la biopsia, la citología válida y la edad 2026-12-03 17:12:03 -06:00
edgar eb75fdf8d4 Calificar en oro la referencia de postcolposcopía con su VPH 2026-12-03 17:12:03 -06:00
edgar 1b624f2cdd Tomar la histerectomía solo del examen citológico 2026-12-03 17:12:03 -06:00
Angel Capetillo Zavala 9414b15a9c Update WebApp chart labels 2026-12-03 15:18:28 -06:00
Angel Capetillo Zavala 5188615d0e Point WebApp at the CaMa card removal 2026-12-03 11:01:08 -06:00
Angel Capetillo Zavala a9b311f27a Vincular WebApp con las exportaciones de CaMa 2026-12-03 10:25:50 -06:00
edgar 0af67fee5a Clasificar cada tamizaje según lo ocurrido antes de su citología 2026-12-03 09:53:12 -06:00
edgar ade1200ebb Compartir el selector de curvas de la ficha 2026-12-03 07:31:13 -06:00
edgar 7a5bb1c08d Agregar curvas de supervivencia seleccionables en la ficha 2026-12-03 07:30:02 -06:00
edgar 60c2a58115 Mostrar todos los ajustes de supervivencia por combinación 2026-12-03 07:28:49 -06:00
edgar ebcc145a71 Revertir la evaluación bayesiana opcional con PyMC 2026-12-03 07:21:25 -06:00
edgar b744b7dd57 Añadir evaluación bayesiana sintética opcional 2026-12-03 01:00:13 -06:00
edgar 791dffd659 Documentar límites del Gibbs longitudinal 2026-12-03 00:58:06 -06:00
edgar 1c64ef2544 Compatibilizar consultas con gold anterior 2026-12-03 00:57:50 -06:00
edgar 4768a8839b Actualizar prueba bayesiana opcional 2026-12-03 00:55:50 -06:00
edgar 6e9cec7ca7 Documentar avance nocturno y base bayesiana 2026-12-03 00:47:38 -06:00
edgar bad58d55ea Añadir evaluación logística de desarrollo 2026-12-03 00:44:51 -06:00
edgar 7791c7201d Evitar fechas y genotipos incompletos engañosos 2026-12-03 00:37:59 -06:00
edgar 660b28793a Aclarar vínculos de biopsia y referencia NCI 2026-12-03 00:36:05 -06:00
edgar 824fbeebf5 Exigir citología posterior para seguimiento postcolposcopia 2026-12-03 00:33:23 -06:00
edgar ef2a154900 Actualizar curvas de la ficha sin barra de herramientas 2026-12-03 00:24:51 -06:00
edgar 39dc271b74 Asignar tablas NCI con datos verificables 2026-12-03 00:19:49 -06:00
edgar c8e93c5f2d Documentar datos faltantes para tablas NCI 2026-12-03 00:19:49 -06:00
edgar 574d6db9f6 Leer tablas NCI de visitas y genotipos 2026-12-03 00:19:49 -06:00
edgar ed49f846f8 Aclarar el supuesto de la referencia NCI en la ficha 2026-12-03 00:18:30 -06:00
edgar 20a1a340e5 Actualizar barras de confirmación y etiqueta NCI en la web 2026-12-03 00:06:33 -06:00
edgar 4b4d5f3e86 Instalar dependencias antes de copiar el código para reutilizar su capa 2026-12-03 00:06:33 -06:00
edgar 1335228386 Documentar codificadores binarios CaCu 2026-12-02 23:59:02 -06:00
edgar 26c4000c67 Incorporar codificadores CaCu y probarlos sobre gold 2026-12-02 23:59:02 -06:00
edgar 644c15fac6 Leer fechas de disponibilidad y formatos de citología CaCu 2026-12-02 23:59:02 -06:00
edgar bc2494ceec Agregar tabla de supervivencia en la ficha 2026-12-02 23:44:29 -06:00
edgar 87b2d0ab91 Ajustar tasa de confirmación y etiquetas de riesgo en la web 2026-12-02 23:43:19 -06:00
edgar 22544308c3 Mostrar curva de combinación, escalas y métodos en la ficha CaCu 2026-12-02 23:20:52 -06:00
edgar 84caf2704a Publicar variables usadas en las estimaciones 2026-12-02 23:14:28 -06:00
edgar 25f2079c04 Actualizar diagnóstico de varianzas PIM 2026-12-02 23:04:37 -06:00
edgar 6dc5a0d383 Declarar la medida publicada por cada predicción 2026-12-02 23:00:18 -06:00
edgar 74c6138d49 Actualizar ficha de curvas de probabilidad 2026-12-02 22:54:24 -06:00
edgar e670a48f52 Tomar el día de la evidencia FHIR en hora de Monterrey 2026-12-02 22:02:08 -06:00
edgar 16edc9f034 Agregar series NCI posteriores a colposcopia y tratamiento 2026-12-02 21:59:04 -06:00
edgar 34d3f4cb72 Declarar disponibilidad de intervalos de supervivencia CaCu 2026-12-02 21:59:04 -06:00
edgar a9529153a0 Registrar etapas de descarte de cohortes 2026-12-02 21:59:04 -06:00
edgar 5fe1f5e975 Documentar elegibilidad incierta y probar esquema anterior 2026-12-02 21:59:04 -06:00
edgar 0138de8ab6 Unificar el día de evidencia FHIR 2026-12-02 21:59:04 -06:00
edgar 39b923db09 No usar resultados FHIR anulados y dejar pendientes los preliminares 2026-12-02 21:57:33 -06:00
edgar 047446a1aa Reconstruir gold tras un despliegue con un job de Dagster 2026-12-02 21:57:33 -06:00
edgar 42aa6df6dd Usar días en indicadores de oportunidad 2026-12-02 21:54:57 -06:00
edgar 2883757071 Nombrar en días los indicadores CaCu 2026-12-02 21:50:05 -06:00
edgar 0697e84559 Fijar WebApp con la exclusión por histerectomía conservada 2026-12-02 20:26:15 -06:00
edgar f98dac86e3 Cargar datos sintéticos de CaCu con Synthea por la API 2026-12-02 20:26:15 -06:00
edgar 3ebf34fdff Renombrar tasas de confirmación histopatológica 2026-12-02 20:24:48 -06:00
edgar ebb3fea787 Comprobar tiempos de diagnóstico en gold 2026-12-02 20:21:44 -06:00
edgar 9666596ab0 Separar primer diagnóstico y diagnóstico tras biopsia 2026-12-02 20:01:30 -06:00
edgar 0d7b85f1f7 Fijar WebApp con las correcciones de la ficha CaCu 2026-12-02 19:44:51 -06:00
Angel Capetillo Zavala ba8816fcfa Fijar WebApp con la integración del lote 2B de CaCu 2026-12-02 19:26:51 -06:00
edgar af8fe28850 Fijar WebApp con la elegibilidad solo para pacientes no elegibles 2026-12-02 19:04:01 -06:00
Angel Capetillo Zavala d1e74792a4 Fijar WebApp con elegibilidad CaCu del lote 2A 2026-12-02 18:47:40 -06:00
edgar 257e12b63c Aplicar la vigencia de riesgos CaCu y publicar las series de riesgo con tablas NCI 2026-12-02 18:24:39 -06:00
Angel Capetillo Zavala 230e73f314 Pin the WebApp with the grouped NCI comparison and the risk-only scales 2026-12-02 17:48:56 -06:00
edgar 6b6f1c757d Reportar la deserción de cohortes CaCu en MLflow 2026-12-02 17:03:56 -06:00
edgar 2304cae6b7 Exponer criterios de elegibilidad en FHIR 2026-12-02 16:46:32 -06:00
edgar 83b393a1f0 Retirar el plan de trabajo del repositorio 2026-12-02 16:09:40 -06:00
edgar 08c430af35 Reportar todos los motivos de exclusión CaCu por visita 2026-12-02 16:09:40 -06:00
edgar d533d358c4 Documentar el plan de desarrollo CaCu 2026-12-02 15:38:11 -06:00
edgar ba81ab811f Preparar la evidencia fuente y la elegibilidad CaCu por visita
01a: fechas clínicas, disponibilidad en origen y referencia por campo; evidencia FHIR independiente.
01b (parcial): proyección de elegibilidad por instancia y lector con comprobación del esquema gold.

Pendiente: las exclusiones propias de cada escenario conservan solo el motivo prioritario; fechas FHIR parciales o sin zona, estados de resultado y actualización desde instalaciones anteriores. Ver PLAN_CONTEXTO_CACU.md.
2026-12-02 15:38:10 -06:00
Angel Capetillo Zavala dd54f9a5ab Pin CaCu metadata and distribution fixes 2026-12-02 14:10:49 -06:00
edgar ed3c09222a Agregar prototipo para consultar variables de riesgo CaCu 2026-12-02 10:15:15 -06:00
edgar 18845f4719 Incorporar las curvas de supervivencia de CaCu 2026-12-02 09:35:36 -06:00
edgar d68952bc6e Excluir por histerectomía y publicar el motivo 2026-12-02 09:35:32 -06:00
edgar 4f308b4125 Agregar cohortes CaCu de segunda visita 2026-12-02 09:35:19 -06:00
edgar 43651cf43d Agregar VPH 16 y 18 por separado a la capa gold 2026-12-02 09:34:58 -06:00
edgar e6ff145a60 Expose cervical exam fields in the CaCu model timeline 2026-12-01 20:13:07 -06:00
angel 033c38649a Merge pull request 'Merge/cacu rounds cama integration' (#28) from merge/cacu-rounds-cama-integration into feature/cacu-screening-rounds
Reviewed-on: #28
2026-12-01 19:20:17 -06:00
Angel Capetillo Zavala 5ffa927f41 Merge the CaMa integration into the CaCu rounds, pinning the merged WebApi and WebApp 2026-12-01 19:10:49 -06:00
Angel Capetillo Zavala 50eb097134 CaCu: pin the WebApp and WebApi of the NCI reference comparison 2026-12-01 18:32:31 -06:00
Angel Capetillo Zavala 5a11bb1555 CaCu: exact resolution of the NCI reference risk, its comparison with the models and its FHIR result 2026-12-01 18:24:39 -06:00
Angel Capetillo Zavala e9ccad7f69 CaCu: the NCI CIN3+ risk tables as a versioned reference resource with their builder 2026-12-01 18:24:38 -06:00
Angel Capetillo Zavala 027ba274a7 CaCu: pin the record, stage and grouped-bar WebApp 2026-12-01 17:16:22 -06:00
Angel Capetillo Zavala eb92e77be7 CaCu: the state and sources of each stage of a cytology's route 2026-12-01 17:15:41 -06:00
Angel Capetillo Zavala 1eea97254a CaCu: HPV genotype reports by age, follow-up status and screening round 2026-12-01 17:15:40 -06:00
Angel Capetillo Zavala c224163a3d Resolve submodule URLs relative to integrator remote 2026-12-01 14:23:00 -06:00
Angel Capetillo Zavala 98467c5bc7 CaCu: pin screening rounds WebApp 2026-12-01 14:23:00 -06:00
Angel Capetillo Zavala b77c22168c Resolve submodule URLs relative to integrator remote 2026-12-01 12:29:33 -06:00
Angel Capetillo Zavala d3a02178d1 CaMa: pin integration branches for review 2026-12-01 12:28:18 -06:00
Angel Capetillo Zavala 72cd19219a CaMa: add provisional mammogram to biopsy duration 2026-12-01 12:27:28 -06:00
Angel Capetillo Zavala de58f0db59 CaMa: preserve synthetic mammogram biopsy link 2026-12-01 12:27:17 -06:00
140 changed files with 12085 additions and 607 deletions
+3 -3
View File
@@ -1,12 +1,12 @@
[submodule "WebApi"]
path = WebApi
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApi.git
url = ../WebApi.git
branch = rebuild
[submodule "WebApp"]
path = WebApp
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApp.git
url = ../WebApp.git
branch = rebuild
[submodule "models"]
path = models
url = ssh://git@10.0.10.41:2222/ISSSTELEON/models.git
url = ../models.git
branch = rebuild
+71 -20
View File
@@ -2,9 +2,11 @@
import them. Codes are the platform's (core.schema)."""
# Biopsy grades that count as CIN2+ (the outcome) and as invasive cancer.
CIN2_PLUS = ["HSIL", "CIS", "carcinoma"]
CIN2_PLUS = ["CIN2", "HSIL", "CIN3", "CIS", "carcinoma"] # HSIL: reported without telling 2 from 3
CANCER = ["carcinoma"]
CASE = ["CIS", "carcinoma"] # a biopsy this grade makes her a case: she has cancer
CASE = ["carcinoma"] # a biopsy this grade makes her a case. Carcinoma in situ is CIN3, not cancer
# CIN3 or severe dysplasia and worse. HSIL is left out: it does not tell moderate from severe.
CIN3_PLUS = ["CIN3", "CIS", "carcinoma"]
# The follow-up list: patients with a cytology sampled within the window before the cut-off.
FOLLOW_UP_WINDOWS = [1, 3, 6, 12] # months
@@ -17,13 +19,13 @@ KPNC = {
"LSIL": ["LSIL"],
"ASC-H": ["ASC-H"],
"AGC": ["AGC"],
"HSIL+": ["HSIL", "CIS", "adenocarcinoma"],
"HSIL+": ["HSIL", "CIS", "carcinoma", "adenocarcinoma"],
}
# The three categories used after colposcopy and after treatment.
KPNC_3 = {
"NILM": ["NILM"],
"ASC-US/LSIL": ["ASC-US", "LSIL"],
"High Grade": ["ASC-H", "AGC", "HSIL", "CIS", "adenocarcinoma"],
"High Grade": ["ASC-H", "AGC", "HSIL", "CIS", "carcinoma", "adenocarcinoma"],
}
# Results that show a patient free of CIN2+ at a visit: a negative co-test (both within
@@ -33,6 +35,17 @@ INDEX_SAMPLE_DAYS = 30 # results this many days after the index sample still de
PREVALENT_WINDOW_DAYS = 6 * 365.25 / 12 # an outcome this soon was there at the index
DAYS_PER_YEAR = 365.25
HPV_GENOTYPE_FIELDS = ("hpv_16", "hpv_18")
SECOND_VISIT_FIELDS = (
"bethesda",
"glandular",
"hpv",
*HPV_GENOTYPE_FIELDS,
"gynecologic_condition",
"presenting_symptom",
"cervix_appearance",
)
# Recruitment windows (start inclusive, end exclusive).
RECRUITMENT = ("2018-01-01", "2027-01-01")
POST_TREATMENT_RECRUITMENT = ("2024-01-01", "2027-01-01")
@@ -49,9 +62,26 @@ DIAGNOSIS_SPECIALTIES = ["colposcopy", "oncology_surgery"]
COLPOSCOPY_SPECIALTIES = ["colposcopy"]
SAMPLE_TO_DIAGNOSIS_DAYS = 120 # a diagnosis note this soon after a sample assesses it
DIAGNOSIS_ICD10 = [
"Z014", "Z124", "B977", "R876", "N87", "N870", "N871", "N872", "N879",
"D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539",
] # fmt: skip
"Z014",
"Z124",
"B977",
"R876",
"N87",
"N870",
"N871",
"N872",
"N879",
"D06",
"D060",
"D061",
"D067",
"D069",
"C53",
"C530",
"C531",
"C538",
"C539",
]
HISTORY_ICD10 = ["D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539"]
TREATMENT_ICD10 = ["D06", "D060", "D061", "D067", "D069"]
COLPOSCOPY_ICD10 = ["R876", "N87", "N870", "N871", "N872", "N879", "B977"]
@@ -63,25 +93,46 @@ SURVEILLANCE_SPECIALTIES = ["family_medicine", "colposcopy"]
# Measures (core.measures): the horizons of the screening route, in days; an interval
# that hasn't ended after its horizon counts as not ended.
HORIZONS = {
"sample_to_report": 60, "sample_to_treatment": 180, "diagnosis_to_treatment": 60,
"sample_to_colposcopy": 60, "sample_to_biopsy": 60, "result_to_colposcopy": 60,
"colposcopy_to_biopsy": 60, "biopsy_to_diagnosis": 60,
} # fmt: skip
ABNORMAL = ["ASC-US", "ASC-H", "LSIL", "HSIL", "CIS"] # IND1
HIGH_GRADE = ["ASC-H", "HSIL", "CIS"] # cytology that should be confirmed by biopsy
DETECTION = ["HSIL", "CIS", "carcinoma"] # biopsy grades counted as detected (EU13)
BIOPSY_SEVERITY = ["normal", "LSIL", "HSIL", "CIS", "carcinoma"] # least to most severe
"sample_to_report": 60,
"sample_to_treatment": 180,
"diagnosis_to_treatment": 60,
"sample_to_colposcopy": 60,
"sample_to_biopsy": 60,
"result_to_colposcopy": 60,
"colposcopy_to_biopsy": 60,
"biopsy_to_diagnosis": 60,
}
ABNORMAL = ["ASC-US", "ASC-H", "LSIL", "HSIL", "CIS", "carcinoma"] # IND1
HIGH_GRADE = ["ASC-H", "HSIL", "CIS", "carcinoma"] # cytology that should be confirmed by biopsy
DETECTION = ["CIN2", "HSIL", "CIN3", "CIS", "carcinoma"] # biopsy grades counted as detected (EU13)
BIOPSY_SEVERITY = [
"normal",
"LSIL",
"CIN2",
"HSIL",
"CIN3",
"CIS",
"carcinoma",
] # least to most severe
# The PPVs of a procedure: groups of its cytology (each holds the more severe squamous ones)
# and of its histology; the first histology group is the score's.
PROCEDURE_CYTOLOGY = {
"ascus_plus": ["ASC-US", "LSIL", "ASC-H", "HSIL", "CIS"],
"lsil_plus": ["LSIL", "ASC-H", "HSIL", "CIS"],
"hsil_plus": ["HSIL", "CIS"],
"ascus_plus": ["ASC-US", "LSIL", "ASC-H", "HSIL", "CIS", "carcinoma"],
"lsil_plus": ["LSIL", "ASC-H", "HSIL", "CIS", "carcinoma"],
"hsil_plus": ["HSIL", "CIS", "carcinoma"],
}
PROCEDURE_HISTOLOGY = {
"cin1_plus": ["LSIL", *CIN2_PLUS], "cin2_plus": CIN2_PLUS, "carcinoma": CANCER,
} # fmt: skip
"cin1_plus": ["LSIL", *CIN2_PLUS],
"cin2_plus": CIN2_PLUS,
"carcinoma": CANCER,
}
AGE_GROUPS = [(25, 34), (35, 44), (45, 54), (55, 64)] # plus "<25" and "65+"
NCI_AGE_RANGE = (25, 65) # the ages the NCI tables and books are for
HIDDEN_SCENARIOS = ("post_treatment", "post_colposcopy_second_visit")
# a table category made of several results, by the tables' own definition
NCI_CYTOLOGY_GROUPS = {"High Grade": ["ASC-H", "AGC", "HSIL+"], "ASC-US/LSIL": ["ASC-US", "LSIL"]}
NCI_HISTORY_DAYS = 5 * 366 # "approximately 5 years": a negative test counts this long
RISK_BAND_MODEL = "cacu.cin2_pim" # whose risk at the index visit is banded (surveillance)
RISK_BANDS = [("low", 0.04), ("intermediate", 0.25), ("high", None)] # below each cut
+48
View File
@@ -0,0 +1,48 @@
"""Which of a patient's model risks still apply at a cut-off day (pure). A risk estimated
before something that has since happened is not shown; the models still learn from it."""
from collections.abc import Iterable
from datetime import date
from core import cacu
from core.cacu.measures import as_day
SURVIVAL = "cacu.survival" # the only model that applies once she has cancer
POST_TREATMENT = "cacu.cin2_pim_post_treatment"
def withheld(history: Iterable[dict], cutoff: date) -> tuple[date, date | None, str | None]:
"""From her biopsies and treatments (`date`, `type`, `value_code`) up to the cut-off:
the day from which a post-treatment estimate applies (`date.max`: none does), her last
treatment, and why other estimates are withheld (None: nothing is withheld)."""
found = [(as_day(h["date"]), h["type"], h.get("value_code")) for h in history]
found = [f for f in found if f[0] <= cutoff]
cancer = [day for day, kind, value in found if kind == "biopsy" and value in cacu.CASE]
if cancer:
return date.max, None, f"Diagnóstico de cáncer el {min(cancer)}."
lesion = max(((day, value) for day, kind, value in found
if kind == "biopsy" and value in cacu.CIN2_PLUS), default=None) # fmt: skip
treated = max((day for day, kind, _ in found if kind == "treatment"), default=None)
if lesion and (treated is None or treated < lesion[0]):
return (
date.max,
None,
f"Diagnóstico {lesion[1]} el {lesion[0]}: no se encuentra tratamiento posterior.",
)
if treated:
return (
treated,
treated,
f"Tratamiento el {treated}: paciente ya tratada.",
)
return date.min, None, None
def current(risks: Iterable[dict], history: Iterable[dict], cutoff: date) -> list[dict]:
"""The rows of `gold.cacu_risk` that still apply to one patient at the cut-off."""
since, treated, reason = withheld(history, cutoff)
if reason is None:
return list(risks)
return [r for r in risks if r["model"] == SURVIVAL
or (treated is not None and r["model"] == POST_TREATMENT
and as_day(r["index_date"]) >= since)] # fmt: skip
+383 -108
View File
@@ -12,6 +12,7 @@ from core.measures import (
Proportion,
RiskBand,
age_group,
age_years,
as_day,
desc,
)
@@ -26,16 +27,30 @@ def follow_up_status(row: dict, at: date, through: bool = False) -> str:
day = as_day(row.get(first))
return day is not None and (day <= at if through else day < at)
for first, status in (("first_case", "case"), ("first_treatment", "post_treatment"),
("first_colposcopy", "post_colposcopy")): # fmt: skip
for first, status in (
("first_case", "case"),
("first_treatment", "post_treatment"),
("first_postcolposcopy_cytology", "post_colposcopy"),
):
if by(first):
return status
return "pre_colposcopy"
def screening_status(row: dict) -> str:
"""What kind of screening a row is, by what came before its cytology (without one, before
the row's own day): a cytology taken after a colposcopy is a post-colposcopy screening."""
day = as_day(row.get("sample_date") or row["date"])
status = follow_up_status(row, day)
colposcopy = as_day(row.get("first_colposcopy"))
if status == "pre_colposcopy" and colposcopy is not None and colposcopy < day:
return "post_colposcopy"
return status
def valid(row: dict) -> bool:
"""A cytology with a result, reported, of satisfactory (or unknown) adequacy."""
return row["result_date"] is not None and row.get("adequacy") != "unsatisfactory"
"""Whether the sample counts, as gold decides it (macro cacu_valid_cytology)."""
return bool(row["valid"])
def latest(row: dict) -> tuple:
@@ -46,12 +61,17 @@ def latest(row: dict) -> tuple:
def latest_most_severe_biopsy(row: dict) -> tuple:
"""Her latest valid sample, then its most severe reported biopsy, the latest first."""
reported = row.get("biopsy_report_date") is not None
return (*latest(row), reported, row.get("severity") or 0,
desc(as_day(row.get("biopsy_report_date"))), desc(row.get("biopsy_id"))) # fmt: skip
return (
*latest(row),
reported,
row.get("severity") or 0,
desc(as_day(row.get("biopsy_report_date"))),
desc(row.get("biopsy_id")),
)
def result(row: dict) -> str:
return row["result"] if valid(row) else NO_DATA
return (row["result"] or NO_DATA) if valid(row) else NO_DATA
def histology(row: dict) -> str:
@@ -88,14 +108,15 @@ def groups_by_hpv(row: dict, p=None) -> list[str]:
def round_of(row: dict, p=None) -> str:
"""Subsequent: screened before, as her form says, or past colposcopy or treatment at the
sample. Initial: the first screening of her life."""
if row["sample_date"] is None:
return NO_DATA
if follow_up_status(row, as_day(row["sample_date"])) in ("post_colposcopy", "post_treatment"):
return "subsequent"
history = row["screening_history"]
return NO_DATA if history is None else "initial" if history == "never" else "subsequent"
"""Initial or subsequent screening, as gold decides it (macro cacu_detection)."""
return row["detection"] or NO_DATA
def subsequent_history(row: dict, p=None) -> str | list[str]:
"""The form's history within the subsequent round, including missing or conflicting values."""
if round_of(row) != "subsequent":
return []
return row.get("screening_history") or NO_DATA
def hpv_genotype(row: dict) -> str:
@@ -119,115 +140,369 @@ def biopsy_answer(row: dict) -> str:
return "high_grade" if row["histology"] in cacu.CIN2_PLUS else "below_high_grade"
EU_GUIDELINES = (
"https://cci4eu.aws-lcb.iarc.who.int/wp-content/uploads/2025/01/"
"EU_guidelines_CervicalCancer_Screening.pdf-1.pdf"
)
def _citation(text: str, url: str) -> dict:
return {"type": "citation", "citation": text, "url": url}
def european_kpi(number: int) -> dict:
return _citation(
"European guidelines for quality assurance in cervical cancer screening. Second "
f"edition, capítulo 7, KPI {number}. Referencia metodológica; la definición local "
"puede diferir.",
EU_GUIDELINES,
)
RISK_REFERENCES = (
_citation(
"Perkins et al. 2019 ASCCP Risk-Based Management Consensus Guidelines (2020).",
"https://pmc.ncbi.nlm.nih.gov/articles/PMC7147428/",
),
_citation(
"Cheung et al. Methods for Risk Estimation, Recommended Management, and Validation (2020).",
"https://pubmed.ncbi.nlm.nih.gov/32243306/",
),
_citation(
"Hyun, Cheung et al. Flexible risk prediction models for left or interval-censored data "
"from electronic health records (2017).",
"https://pmc.ncbi.nlm.nih.gov/articles/PMC6586434/",
),
)
def ppv(id: str, title: str, procedure: str, counted) -> Measure:
"""Of the patients with the procedure in the period (her first), those whose histology is
LIEBG or more; those already cases are left out."""
levels = tuple((name, lambda r, grades=grades: r["histology"] in grades)
for name, grades in cacu.PROCEDURE_HISTOLOGY.items()) # fmt: skip
levels = tuple(
(name, lambda r, grades=grades: r["histology"] in grades)
for name, grades in cacu.PROCEDURE_HISTOLOGY.items()
)
return Measure(
id, title, "procedures",
Proportion(levels[0][1], denominator=lambda r: counted(r) and not case_before(r),
order=earliest, levels=levels, date="date",
strata=(("cytology", groups_by_cytology), ("hpv", groups_by_hpv),
("round", round_of))),
id,
title,
"procedures",
Proportion(
levels[0][1],
denominator=lambda r: counted(r) and not case_before(r),
order=earliest,
levels=levels,
date="date",
strata=(("cytology", groups_by_cytology), ("hpv", groups_by_hpv), ("round", round_of)),
),
params={"type": procedure},
facts={"report_known_at": ("histology", "report_date"),
"cytology_known_at": ("result", "hpv", "hpv_16", "hpv_18")},
references=(european_kpi(11),),
facts={
"report_known_at": ("histology", "report_date"),
"cytology_known_at": ("result", "hpv", "hpv_16", "hpv_18"),
},
dated={"report_date": ("histology",)},
) # fmt: skip
)
H = cacu.HORIZONS
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no cervical cancer note before
AGE = ("age_group", lambda row, p: age_group(row.get("birth_date"), p.start, cacu.AGE_GROUPS))
STATUS = ("follow_up_status", lambda row, p: follow_up_status(row, p.start))
def results_age_group(row: dict, p) -> str | list[str]:
"""Age at period start; omit children under 15 only from this stratifier."""
birth = as_day(row.get("birth_date"))
years = age_years(birth, p.start)
if years is None:
return NO_DATA
return [] if years < 15 else age_group(birth, p.start, cacu.AGE_GROUPS)
RESULTS_AGE = ("age_group", results_age_group)
STATUS = ("follow_up_status", lambda row, p: screening_status(row))
RESULT = ("result", lambda row, p: row["result"])
MEASURES = {m.id: m for m in [
Measure("IND1", "Pacientes con citología anormal", "samples",
Proportion(lambda r: r["result"] in cacu.ABNORMAL), "decrease", group="principal"),
Measure("CACU_EU13", "Tasa de detección histopatológica", "sample_biopsies",
Proportion(lambda r: r.get("histology") in cacu.DETECTION
and r.get("biopsy_report_date") is not None,
strata=(AGE, STATUS)), group="principal"),
Measure("CACU_EU7", "Pacientes evaluadas por resultado de citología", "samples",
Composition(latest, result, strata=(AGE, STATUS, ("round", round_of)))),
Measure("CACU_VPH", "Pacientes evaluadas por resultado de VPH", "samples",
Composition(lambda r: (as_day(r["sample_date"]), r["sample_id"]),
lambda r: SIGN[r["hpv"]],
where=lambda r: r["hpv"] is not None,
strata=(AGE, STATUS, ("round", round_of),
*((g, lambda r, p, g=g: SIGN.get(r[g], []))
for g in ("hpv_16", "hpv_18")))),
facts={"report_known_at": ("hpv", "hpv_16", "hpv_18")}),
Measure("CACU_VPH_GENOTIPO", "Resultados de VPH por genotipo", "samples",
Composition(lambda r: (), hpv_genotype, unit="sample_id",
where=lambda r: r["report_date"] is not None and any(
r[c] is not None for c in ("hpv", "hpv_16", "hpv_18"))),
MEASURES = {
m.id: m
for m in [
Measure(
"IND1",
"Pacientes con citología anormal",
"samples",
Proportion(lambda r: r["result"] in cacu.ABNORMAL),
"decrease",
group="principal",
),
Measure(
"CACU_EU13",
"Tasa de detección histopatológica",
"sample_biopsies",
Proportion(
lambda r: (
r.get("histology") in cacu.DETECTION and r.get("biopsy_report_date") is not None
),
strata=(AGE, STATUS),
),
group="principal",
references=(european_kpi(13),),
),
Measure(
"CACU_EU7",
"Pacientes evaluadas por resultado de citología",
"samples",
Composition(
latest,
result,
strata=(
RESULTS_AGE,
STATUS,
("round", round_of),
("subsequent_history", subsequent_history),
),
),
references=(european_kpi(7),),
),
Measure(
"CACU_VPH",
"Pacientes evaluadas por resultado de VPH",
"samples",
Composition(
lambda r: (as_day(r["sample_date"]), r["sample_id"]),
lambda r: SIGN[r["hpv"]],
where=lambda r: r["hpv"] is not None,
strata=(
AGE,
STATUS,
("round", round_of),
*((g, lambda r, p, g=g: SIGN.get(r[g], [])) for g in ("hpv_16", "hpv_18")),
),
),
facts={"report_known_at": ("hpv", "hpv_16", "hpv_18")},
),
Measure(
"CACU_VPH_GENOTIPO",
"Resultados de VPH por genotipo",
"samples",
Composition(
lambda r: (),
hpv_genotype,
unit="sample_id",
where=lambda r: (
r["report_date"] is not None
and any(r[c] is not None for c in ("hpv", "hpv_16", "hpv_18"))
),
strata=(
RESULTS_AGE,
STATUS,
("round", round_of),
("subsequent_history", subsequent_history),
),
),
facts={"report_known_at": ("hpv", "hpv_16", "hpv_18", "report_date")},
description="Reportes de VPH, por fecha de toma."),
Measure("CACU_BIOPSIA_RESULTADOS", "Resultados de biopsia cervical", "procedures",
Composition(lambda r: (), lambda r: r["histology"] or NO_DATA,
unit="procedure_id", date="report_date",
where=lambda r: r["report_date"] is not None),
params={"type": "biopsy"}, known="report_known_at",
description="Reportes de biopsia, por fecha de reporte."),
Measure("CACU_BIOPSIA_SOLICITUD_CONFIRMACION",
"Confirmación por solicitudes de biopsia", "procedures",
description="Reportes de VPH, por fecha de toma. Cuenta reportes, no pacientes; "
"la edad es la de la paciente al inicio del periodo; el estatus y la ronda son "
"los de la muestra del reporte.",
),
Measure(
"CACU_BIOPSIA_RESULTADOS",
"Resultados de biopsia cervical",
"procedures",
Composition(
lambda r: (),
lambda r: r["histology"] or NO_DATA,
unit="procedure_id",
date="report_date",
where=lambda r: r["report_date"] is not None,
),
params={"type": "biopsy"},
known="report_known_at",
description="Reportes de biopsia, por fecha de reporte.",
),
Measure(
"CACU_BIOPSIA_SOLICITUD_CONFIRMACION",
"Confirmación por solicitudes de biopsia",
"procedures",
Composition(lambda r: (), biopsy_answer, unit="procedure_id", date="date"),
params={"type": "biopsy"},
facts={"report_known_at": ("histology", "report_date")},
dated={"report_date": ("histology",)},
description="Solicitudes de biopsia registradas, por fecha de solicitud."),
ppv("CACU_VPP_COLPOSCOPIA", "Valor predictivo positivo de la colposcopía", "colposcopy",
lambda r: True),
ppv("CACU_VPP_BIOPSIA", "Valor predictivo positivo de la biopsia", "biopsy",
lambda r: r["histology"] is not None and r["report_date"] is not None),
Measure("CACU_TIEMPO_DIAGNOSTICO_CIE10", "Tiempo de tamizaje a diagnóstico por CIE-10",
description="Solicitudes de biopsia registradas, por fecha de solicitud.",
),
ppv(
"CACU_VPP_COLPOSCOPIA",
"Tasa de confirmación histopatológica de referencia a colposcopía",
"colposcopy",
lambda r: True,
),
ppv(
"CACU_VPP_BIOPSIA",
"Tasa de confirmación histopatológica de referencia a biopsia",
"biopsy",
lambda r: r["histology"] is not None and r["report_date"] is not None,
),
Measure(
"CACU_TIEMPO_DIAGNOSTICO_CIE10",
"Tiempo de tamizaje a primer diagnóstico por CIE-10",
"samples",
Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=NO_HISTORY,
strata=(("diagnosis_code",
lambda r, p: r["diagnosis_code"] or NO_DATA),)), "decrease"),
Measure("CACU_CONFIRMACION_CITOLOGIA", "Confirmación histopatológica", "sample_biopsies",
Composition(latest_most_severe_biopsy, histology,
admit=lambda r: valid(r) and r["result"] in cacu.HIGH_GRADE,
strata=(RESULT,))),
Measure("CACU_EU_TIEMPO_REPORTE", "Tiempo de toma a resultado de citología", "samples",
Duration("days_sample_result", "result_date", "sample_date", H["sample_to_report"],
ended="report_date"), "decrease"),
Measure("CACU_DIAS_TOMA_DIAGNOSTICO", "Tiempo de tamizaje a diagnóstico", "samples",
Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_TOMA_TRATAMIENTO", "Tiempo de tamizaje a tratamiento", "samples",
Duration("days_sample_treatment", "treatment_date", "sample_date",
H["sample_to_treatment"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_DIAGNOSTICO_TRATAMIENTO", "Tiempo de diagnóstico a tratamiento", "samples",
Duration("days_diagnosis_treatment", "diagnosis_treatment_date", "diagnosis_date",
H["diagnosis_to_treatment"],
units=lambda r: r["history"] == 0 and r["diagnosis_date"] is not None),
"decrease"),
Measure("CACU_DIAS_TOMA_COLPOSCOPIA", "Tiempo de toma de muestra a colposcopía", "samples",
Duration("days_sample_colposcopy", "colposcopy_date", "sample_date",
H["sample_to_colposcopy"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_TOMA_BIOPSIA", "Tiempo de toma de muestra a resultado de biopsia", "samples",
Duration("days_sample_biopsy", "biopsy_date", "sample_date",
H["sample_to_biopsy"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_RESULTADO_COLPOSCOPIA", "Tiempo de resultado a colposcopía", "samples",
Duration("days_result_colposcopy", "result_colposcopy_date", "result_date",
H["result_to_colposcopy"],
units=lambda r: r["history"] == 0 and r["result_date"] is not None),
"decrease"),
Measure("CACU_DIAS_COLPOSCOPIA_BIOPSIA", "Tiempo de colposcopía a biopsia", "samples",
Duration("days_colposcopy_biopsy", "biopsy_date", "result_colposcopy_date",
H["colposcopy_to_biopsy"],
units=lambda r: r["history"] == 0
and r["result_colposcopy_date"] is not None), "decrease"),
Measure("CACU_DIAS_BIOPSIA_DIAGNOSTICO", "Tiempo de biopsia a diagnóstico", "samples",
Duration("days_biopsy_diagnosis", "biopsy_diagnosis_date", "biopsy_date",
H["biopsy_to_diagnosis"],
units=lambda r: r["history"] == 0 and r["biopsy_date"] is not None),
"decrease"),
Measure("CACU_RIESGO_BANDA", "Banda de riesgo de CIN2+ en vigilancia", "risk",
Duration(
"days_sample_diagnosis",
"diagnosis_date",
"sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS,
units=NO_HISTORY,
strata=(("diagnosis_code", lambda r, p: r["diagnosis_code"] or NO_DATA),),
),
"decrease",
),
Measure(
"CACU_CONFIRMACION_CITOLOGIA",
"Confirmación histopatológica",
"sample_biopsies",
Composition(
latest_most_severe_biopsy,
histology,
admit=lambda r: valid(r) and r["result"] in cacu.HIGH_GRADE,
strata=(RESULT,),
),
),
Measure(
"CACU_EU_TIEMPO_REPORTE",
"Tiempo de toma a resultado de citología",
"samples",
Duration(
"days_sample_result",
"result_date",
"sample_date",
H["sample_to_report"],
ended="report_date",
),
"decrease",
),
Measure(
"CACU_DIAS_TOMA_DIAGNOSTICO",
"Tiempo de tamizaje a diagnóstico precolposcópico",
"samples",
Duration(
"days_sample_precolposcopy_diagnosis",
"precolposcopy_diagnosis_date",
"sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS,
units=NO_HISTORY,
),
"decrease",
),
Measure(
"CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA",
"Tiempo de tamizaje a diagnóstico tras biopsia",
"samples",
Duration(
"days_sample_biopsy_diagnosis",
"biopsy_diagnosis_date",
"sample_date",
H["sample_to_biopsy"] + H["biopsy_to_diagnosis"],
units=lambda r: r["history"] == 0 and r.get("biopsy_date") is not None,
),
"decrease",
),
Measure(
"CACU_DIAS_TOMA_TRATAMIENTO",
"Tiempo de tamizaje a tratamiento",
"samples",
Duration(
"days_sample_treatment",
"treatment_date",
"sample_date",
H["sample_to_treatment"],
units=NO_HISTORY,
),
"decrease",
),
Measure(
"CACU_DIAS_DIAGNOSTICO_TRATAMIENTO",
"Tiempo de diagnóstico tras biopsia a tratamiento",
"samples",
Duration(
"days_diagnosis_treatment",
"diagnosis_treatment_date",
"biopsy_diagnosis_date",
H["diagnosis_to_treatment"],
units=lambda r: r["history"] == 0 and r["biopsy_diagnosis_date"] is not None,
),
"decrease",
),
Measure(
"CACU_DIAS_TOMA_COLPOSCOPIA",
"Tiempo de toma de muestra a colposcopía",
"samples",
Duration(
"days_sample_colposcopy",
"colposcopy_date",
"sample_date",
H["sample_to_colposcopy"],
units=NO_HISTORY,
),
"decrease",
),
Measure(
"CACU_DIAS_TOMA_BIOPSIA",
"Tiempo de toma de muestra a resultado de biopsia",
"samples",
Duration(
"days_sample_biopsy",
"biopsy_date",
"sample_date",
H["sample_to_biopsy"],
units=NO_HISTORY,
),
"decrease",
),
Measure(
"CACU_DIAS_RESULTADO_COLPOSCOPIA",
"Tiempo de resultado a colposcopía",
"samples",
Duration(
"days_result_colposcopy",
"result_colposcopy_date",
"result_date",
H["result_to_colposcopy"],
units=lambda r: r["history"] == 0 and r["result_date"] is not None,
),
"decrease",
),
Measure(
"CACU_DIAS_COLPOSCOPIA_BIOPSIA",
"Tiempo de colposcopía a biopsia",
"samples",
Duration(
"days_colposcopy_biopsy",
"biopsy_date",
"result_colposcopy_date",
H["colposcopy_to_biopsy"],
units=lambda r: r["history"] == 0 and r["result_colposcopy_date"] is not None,
),
"decrease",
),
Measure(
"CACU_DIAS_BIOPSIA_DIAGNOSTICO",
"Tiempo de biopsia a diagnóstico",
"samples",
Duration(
"days_biopsy_diagnosis",
"biopsy_diagnosis_date",
"biopsy_date",
H["biopsy_to_diagnosis"],
units=lambda r: r["history"] == 0 and r["biopsy_date"] is not None,
),
"decrease",
),
Measure(
"CACU_RIESGO_BANDA",
"Banda de riesgo de CIN2+ en vigilancia",
"risk",
RiskBand(tuple(cacu.RISK_BANDS)),
periods=("semester",), params={"model": cacu.RISK_BAND_MODEL}),
]} # fmt: skip
periods=("semester",),
params={"model": cacu.RISK_BAND_MODEL},
references=RISK_REFERENCES,
),
]
}
+75
View File
@@ -0,0 +1,75 @@
"""The NCI/ASCCP CIN3+ reference risks of a cytology, looked up exactly and traced (experimental).
`resolve` finds the scenario one cytology belongs to by the information the platform holds by a
cut-off, then the one row of the reference tables (gold's NCI master table) that names it. It
never approximates: a result with no row, an unverified equivalence, a history the platform cannot
demonstrate or a scenario not implemented ends in a state that says why, and a value the tables
leave blank is "not published", not zero. `compare` sets an institutional model beside a reference
risk only when the two measure the same thing.
This is research, not a recommendation: the tables' management column is not read and nothing here
is validated clinically."""
from .colposcopy import (
_colposcopy_results,
)
from .compare import (
MODELS,
REASONS,
compare,
)
from .outcome import (
STATES,
_found,
_horizons,
_outcome,
)
from .reading import (
_day,
_flag,
_used,
_valid,
master,
master_rows,
unmet,
)
from .resolve import (
_screening,
resolve,
)
from .vocabulary import (
AGE_RANGE,
BIOPSY,
CYTOLOGY,
GROUPS,
UNVERIFIED,
high_grade,
hpv_category,
)
__all__ = [
"master",
"master_rows",
"AGE_RANGE",
"BIOPSY",
"CYTOLOGY",
"GROUPS",
"MODELS",
"REASONS",
"STATES",
"UNVERIFIED",
"_colposcopy_results",
"_day",
"_flag",
"_found",
"_horizons",
"_outcome",
"_screening",
"_used",
"_valid",
"compare",
"high_grade",
"hpv_category",
"resolve",
"unmet",
]
@@ -0,0 +1,73 @@
"""The table of results after colposcopy."""
from datetime import date
from . import reading
from .outcome import _found
from .reading import _day, _used, _valid, master_rows
from .vocabulary import BIOPSY, UNVERIFIED
def _colposcopy_results(
facts: dict, index: dict, category: str, named: list[dict], out, cutoff
) -> dict:
"""After colposcopy: the referral screening result and the biopsy that names it. Its
horizons are one and five years, not immediate."""
if len(named) > 1:
return out("ambiguous", ["several_biopsies_name_the_cytology"])
biopsy = named[0]
when = _day(index["sample_date"])
if index.get("hpv") is None and category in ("ASC-US", "LSIL", "NILM"):
return out("missing_data", ["missing_hpv"])
referral = None
if category in ("ASC-H", "AGC", "HSIL+"):
referral = category
elif index.get("hpv") and category in ("ASC-US", "LSIL"):
referral = f"HPV-positive {category}"
elif index.get("hpv") and category == "NILM":
earlier = [
c
for c in facts.get("cytologies", [])
if _day(c["sample_date"]) < when
and _valid(c)
and (_day(c.get("report_date")) or date.max) <= when
]
earlier.sort(key=lambda c: _day(c["sample_date"]))
if earlier and earlier[-1].get("hpv") and earlier[-1]["result"] == "NILM":
referral = "HPV-positive NILM x2"
histology = biopsy.get("histology")
if referral is None and histology != "carcinoma":
return out("no_published_row", ["not_a_referral_result_in_the_tables"])
if histology in ("HSIL", "CIS"):
reason = "hsil_cin2_cin3" if histology == "HSIL" else "cis_ais"
return out("unverifiable_correspondence", [reason], assumptions=[UNVERIFIED[reason]])
label = BIOPSY.get(histology)
if label is None:
return out("missing_data", ["biopsy_without_histology"])
# the tables give the histologies they cannot price (cancer here) one row for any referral
referral = None if label == "Cancer" else referral
scenario = {
"table": "colposcopy_results",
"label": "Resultado de colposcopía",
"key": {"referral": referral, "biopsy": label},
}
if not reading.master(facts):
return out("missing_data", ["reference_tables_not_in_gold"])
rows, _ = master_rows(facts, "colposcopy_results", None, referral=referral, biopsy=label)
result = _found(
rows,
"exact",
scenario,
out,
used=[
_used("referral cotest", index),
{
"label": "biopsy",
"request_date": _day(biopsy["request_date"]),
"report_date": _day(biopsy.get("report_date")),
"histology": histology,
},
],
)
result["evaluation_date"] = _day(biopsy.get("report_date"))
return result
+91
View File
@@ -0,0 +1,91 @@
"""An institutional model beside a reference risk."""
from .reading import _day
# -- comparison with the institutional models --------------------------------------------------
# What each institutional CaCu model estimates, as its code and spec say (models/cacu/specs.py).
# `population_verified` stays false: no model has been shown to share the tables' population.
MODELS = {
"cacu.cin2_pim": {"outcome": "CIN2+", "index": "last screening cytology"},
"cacu.cancer_pim": {"outcome": "cancer", "index": "last screening cytology"},
"cacu.cin2_logistic": {"outcome": "CIN2+ within one year", "index": "index sample"},
"cacu.cin2_pim_post_colposcopy": {"outcome": "CIN2+", "index": "first colposcopy"},
"cacu.cin2_pim_post_treatment": {"outcome": "CIN2+", "index": "treatment"},
"cacu.cin3_pim": {"outcome": "CIN3+", "index": "last screening cytology"},
"cacu.cin3_pim_post_colposcopy": {"outcome": "CIN3+", "index": "first colposcopy"},
"cacu.survival": {
"outcome": "not stated as a histology outcome",
"index": "first biopsy carcinoma",
},
}
REASONS = {
"no_institutional_model": "no institutional model has scored her",
"outcome_differs": "the model's outcome is not the table's (CIN3+)",
"unknown_model": "the model's outcome is not registered for comparison",
"horizon_not_published_by_model": "the model publishes no prediction at this horizon",
"index_date_differs": "the model's index date is not the evaluated cytology's",
"population_not_verified": (
"the model's population and scenario are not verified to match the table's"
),
"no_reference": "the tables give no risk at this horizon",
}
def compare(resolution: dict, assessments: list[dict], registry: dict | None = None) -> list[dict]:
"""Per reference horizon and institutional model, the difference in percentage points
(institutional minus reference) when the two are the same estimate, else why not.
`assessments`: model (code), title, index_date, predictions (years, p, low, high)."""
registry = MODELS if registry is None else registry
found = []
for h in resolution["horizons"]:
base = {"years": h["years"], "reference": h["risk"]}
if not assessments:
found.append(
{
**base,
"model": None,
"institutional": None,
"status": "not_comparable",
"difference_pp": None,
"reasons": ["no_institutional_model"],
}
)
for a in assessments:
kind = registry.get(a["model"])
asked = next((p for p in a["predictions"] if p["years"] == h["years"]), None)
why = []
if h["risk"] is None:
why.append("no_reference")
if kind is None:
why.append("unknown_model")
elif kind["outcome"] != "CIN3+":
why.append("outcome_differs")
if asked is None:
why.append("horizon_not_published_by_model")
if _day(a.get("index_date")) != resolution.get(
"evaluation_date", resolution["index"]["sample_date"]
):
why.append("index_date_differs")
if not (kind or {}).get("population_verified"):
why.append("population_not_verified")
row = {
**base,
"model": a["model"],
"title": a.get("title"),
"institutional": None if asked is None else asked["p"],
"interval": None
if asked is None or asked.get("low") is None
else [asked["low"], asked["high"]],
"outcome": (kind or {}).get("outcome"),
}
if why:
found.append(
{**row, "status": "not_comparable", "difference_pp": None, "reasons": why}
)
else:
diff = round((asked["p"] - h["risk"]) * 100, 2)
found.append({**row, "status": "comparable", "difference_pp": diff, "reasons": []})
return found
@@ -0,0 +1,99 @@
"""The first visit after colposcopy and the second screening visit after an abnormal one. What
each asks of a sample is decided in gold (macros cacu_nci_*)."""
from datetime import date
from . import reading
from .outcome import _found
from .reading import _day, _used, _valid, master_rows
from .vocabulary import high_grade
# What gold finds unmet, in the order the first one is named.
SECOND_VISIT_REQUIREMENTS = (
"prior_procedure_requires_other_scenario",
"missing_or_ambiguous_previous_visit",
"previous_result_not_available_by_index",
"contradictory_previous_hpv",
"missing_previous_hpv",
)
POST_COLPO_REQUIREMENTS = (
"missing_or_ineligible_age",
"age_outside_25_65",
"missing_or_ambiguous_index_sample",
"hysterectomy_declared",
"missing_hpv",
"contradictory_hpv",
"treatment_before_index",
"prior_biopsy_pending_at_index",
"no_prior_biopsy_report",
"multiple_prior_biopsy_reports",
"intermediate_visit_not_supported",
"biopsy_not_demonstrably_below_cin2",
"referral_link_not_recorded",
"linked_referral_not_available",
"multiple_linked_referral_samples",
"colposcopy_not_documented",
"invalid_biopsy_chronology",
)
def _first(facts: dict, scenario: str, day: date, order: tuple[str, ...]) -> str | None:
unmet = reading.unmet(facts, scenario, day)
if unmet is None:
return "requirements_not_in_gold"
return next((c for c in order if c in unmet), None)
def _post_colposcopy(facts: dict, index: dict, category: str, when: date, hpv: str, out):
"""The post-colposcopy table, first visit: the referral's grade and the current results."""
if why := _first(facts, "nci_post_colposcopy", when, POST_COLPO_REQUIREMENTS):
return out("scenario_not_implemented", [why])
biopsy = next(
b
for b in facts.get("biopsies", [])
if _day(b.get("report_date")) is not None and _day(b["report_date"]) < when
)
referral = next(
c
for c in facts["cytologies"]
if _day(c["sample_date"]) == _day(biopsy["cytology_sample_date"])
and (_day(c.get("report_date")) or date.max) <= _day(biopsy["request_date"])
and _valid(c)
)
if high_grade(referral["result"]):
grade = "High Grade"
elif referral["result"] in ("ASC-US", "LSIL") and referral.get("hpv"):
grade = "Low Grade"
else:
return out("no_published_row", ["referral_or_cytology_category_not_verified"])
key = {"pre_colposcopy": grade, "post_colposcopy_history": None, "hpv": hpv}
rows, via = master_rows(facts, "post_colposcopy", category, **key)
scenario = {
"table": "post_colposcopy",
"label": "Poscolposcopía, primera visita",
"key": {"pre_colposcopy": grade, "hpv": hpv, "cytology": category},
}
used = [_used("referral cytology", referral), _used("current cotest", index)]
return _found(rows, via, scenario, out, used=used)
def _second_visit(facts: dict, index: dict, category: str, when: date, hpv: str, out):
"""The surveillance table: one earlier visit, abnormal, and the current results."""
if _first(facts, "nci_second_visit", when, SECOND_VISIT_REQUIREMENTS):
return out("scenario_not_implemented", ["history_is_a_surveillance_scenario"])
prior = next(c for c in facts["cytologies"] if _day(c["sample_date"]) < when)
if prior["hpv"] and prior["result"] == "NILM":
history = "HPV-positive/NILM"
elif not prior["hpv"] and prior["result"] in ("ASC-US", "LSIL"):
history = f"HPV-negative/{prior['result']}"
else:
return out("scenario_not_implemented", ["previous_history_category_not_verified"])
key = {"history": history, "previous_two": None, "hpv": hpv}
rows, via = master_rows(facts, "surveillance", category, **key)
scenario = {
"table": "surveillance",
"label": "Vigilancia, segunda visita",
"key": {"history": history, "hpv": hpv, "cytology": category},
}
used = [_used("earlier cotest", prior), _used("current cotest", index)]
return _found(rows, via, scenario, out, used=used)
+63
View File
@@ -0,0 +1,63 @@
"""The states a resolution ends in, and its answer."""
# Every state a resolution ends in, and what it means.
STATES = {
"resolved": "one published row names the scenario",
"not_published": "the row exists and the tables leave its risk blank",
"missing_data": "a datum the scenario needs is not in the platform by the cut-off",
"history_not_demonstrable": "the tables need a past history the platform cannot demonstrate",
"not_applicable": "the patient is outside the tables' applicability",
"contradictory": "the results contradict each other",
"ambiguous": "more than one record or row could be the one",
"scenario_not_implemented": "the scenario belongs to a table this version does not resolve",
"unverifiable_correspondence": "the platform's record and the table's category are not "
"verifiably the same thing",
"no_published_row": "the tables publish no row for this combination",
}
def _outcome(status: str, reasons: list[str], **more) -> dict:
return {
"status": status,
"reasons": reasons,
"scenario": None,
"row": None,
"horizons": [],
"used": [],
"assumptions": [],
**more,
}
def _horizons(row: dict) -> list[dict]:
return [
{
"years": int(years),
"risk": risk,
"published": risk is not None,
"percent": row["risks_percent"][years],
}
for years, risk in row["risks"].items()
]
def _found(rows: list[dict], via: str | None, scenario: dict, out, used: list[dict]) -> dict:
if not rows:
return out("no_published_row", ["no_row_for_the_combination"], scenario=scenario, used=used)
if len(rows) > 1:
return out("ambiguous", ["several_rows"], scenario=scenario, used=used)
row = rows[0]
reference = {name: row[name] for name in ("book", "sha256", "sheet", "row")}
horizons = _horizons(row)
status = "resolved" if row["published"] else "not_published"
return out(
status,
[] if row["published"] else ["risk_blank_in_the_tables"],
scenario=scenario,
row=reference,
horizons=horizons,
complementary=row.get("complementary") or {},
intervals=row.get("intervals") or {},
matched_via=via,
used=used,
)
+81
View File
@@ -0,0 +1,81 @@
"""Reading a patient's facts: days, validity, what gold says is unmet."""
from datetime import date
def _day(value) -> date | None:
return None if value is None else date.fromisoformat(str(value)[:10])
def unmet(facts: dict, scenario: str, day: date) -> set | None:
"""What gold says the sample does not meet of a scenario (macro cacu_nci_requirements; empty:
it meets it all); None when gold has not evaluated it, never taken as meeting them."""
found = {
r["criterion"]
for r in facts.get("requirements", [])
if r.get("scenario", "nci_post_colposcopy") == scenario and _day(r["sample_date"]) == day
}
return found - {None} if found else None
def _valid(cytology: dict) -> bool:
return bool(cytology["valid"]) # decided in gold: macro cacu_valid_cytology
def _flag(value) -> bool | None:
"""A result stored as 0 or 1 as the boolean it is; unknown stays unknown."""
return None if value is None else bool(value)
def _used(label: str, c: dict) -> dict:
return {
"label": label,
"sample_date": _day(c["sample_date"]),
"report_date": _day(c.get("report_date")),
"result": c.get("result"),
"hpv": _flag(c.get("hpv")),
"hpv_16": _flag(c.get("hpv_16")),
"hpv_18": _flag(c.get("hpv_18")),
}
def master(facts: dict) -> list[dict] | None:
"""gold.nci_risk_lookup with each row's estimates, as the API reads it."""
return facts.get("master")
def master_rows(facts: dict, scenario: str, asked: str | None, **key) -> tuple[list[dict], str]:
"""The master table's rows for a combination, as gold.nci_risk_lookup holds them (`facts`'
`master`: that view with each row's estimates), and how they matched: the category itself
(`exact`) or the table's own group holding it (`table_group`)."""
found: dict = {}
for r in master(facts) or []:
if (r["scenario"], r["asked_cytology"]) != (scenario, asked):
continue
if any(r[name] != value for name, value in key.items()):
continue
row = found.setdefault(
r["row_id"],
{
"sheet": r["sheet"],
"row": r["source_row"],
"book": r["book"],
"sha256": r["source_sha256"],
"published": bool(r["published"]),
"matched_via": r["matched_via"],
"risks": {}, # CIN3+, the outcome the guidelines act on
"risks_percent": {},
"complementary": {}, # outcome -> horizon -> risk (CIN2+, cancer)
"intervals": {}, # outcome -> horizon -> (lower, upper), 95%
},
)
years = str(r["horizon_years"])
limits = (r.get("lower"), r.get("upper"))
row["intervals"].setdefault(r.get("outcome", "CIN3+"), {})[years] = limits
if r.get("outcome", "CIN3+") == "CIN3+":
row["risks"][years] = r["risk"]
row["risks_percent"][years] = r["risk_percent"]
else:
row["complementary"].setdefault(r["outcome"], {})[years] = r["risk"]
rows = list(found.values())
return rows, rows[0]["matched_via"] if rows else None
+128
View File
@@ -0,0 +1,128 @@
"""Which scenario of the tables her cytology belongs to, and the screening table."""
from datetime import date
from core.measures import age_years
from . import reading
from .colposcopy import _colposcopy_results
from .later_visits import _post_colposcopy, _second_visit
from .outcome import _found, _outcome
from .reading import _day, _used, _valid, master_rows
from .vocabulary import AGE_RANGE, CYTOLOGY, hpv_category
def resolve(facts: dict, cutoff: date, sample: date | None = None) -> dict:
"""The reference risk of her cytology of `sample` (else her latest) by `cutoff`, using only what
was reported by then. `facts`: birth_date; cytologies (sample_date, report_date, result,
adequacy, hpv, hpv_16, hpv_18, gynecologic_condition); biopsies (request_date, report_date,
histology, cytology_sample_date, the sample its own record names); events (type, date) of the
platform's timeline."""
known = [
c
for c in facts.get("cytologies", [])
if _day(c["sample_date"]) <= cutoff
and (_day(c.get("report_date")) or date.max) <= cutoff
and _valid(c)
]
known.sort(key=lambda c: _day(c["sample_date"]))
if sample is not None:
found = [c for c in known if _day(c["sample_date"]) == sample]
if not found:
return _outcome("missing_data", ["sample_not_reported_by_cutoff"], cutoff=cutoff)
index = found[-1]
elif known:
index = known[-1]
else:
return _outcome("missing_data", ["no_cytology_reported_by_cutoff"], cutoff=cutoff)
when = _day(index["sample_date"])
base = {
"cutoff": cutoff,
"index": {
"sample_date": when,
"report_date": _day(index.get("report_date")),
"result": index["result"],
},
}
def out(status, reasons, **more):
return _outcome(status, reasons, **base, **more)
age = age_years(facts.get("birth_date"), when)
base["age"] = age
if age is None:
return out("missing_data", ["no_birth_date"])
if not AGE_RANGE[0] <= age <= AGE_RANGE[1]:
return out("not_applicable", ["age_outside_25_65"])
category = CYTOLOGY.get(index["result"])
if category is None:
return out("no_published_row", ["cytology_not_in_tables"])
biopsies = [
b for b in facts.get("biopsies", []) if (_day(b.get("report_date")) or date.max) <= cutoff
]
named = [b for b in biopsies if _day(b.get("cytology_sample_date")) == when]
after = [
e
for e in facts.get("events", [])
if when < _day(e["date"]) <= cutoff and e["type"] in ("colposcopy", "treatment")
]
# a first visit after colposcopy is read as of that visit, whatever was done to her later
if reading.unmet(facts, "nci_post_colposcopy", when) == set():
hpv, why = hpv_category(index)
if why:
return out("missing_data" if why == "missing_hpv" else "contradictory", [why])
return _post_colposcopy(facts, index, category, when, hpv, out)
if named:
return _colposcopy_results(facts, index, category, named, out, cutoff)
if after or any(when < _day(b["request_date"]) <= cutoff for b in facts.get("biopsies", [])):
return out("unverifiable_correspondence", ["procedure_after_without_named_referral"])
return _screening(facts, index, category, when, out)
def _screening(facts: dict, index: dict, category: str, when: date, out) -> dict:
"""The screening table: her past history (cotest-negative, or unknown when no earlier HPV test
is registered), the current HPV and cytology."""
missing = reading.unmet(facts, "nci_master", when) # her past by the sample, decided in gold
if missing is None:
return out("missing_data", ["requirements_not_in_gold"])
if "colposcopy_or_treatment_before" in missing:
hpv, why = hpv_category(index)
if why:
return out("missing_data" if why == "missing_hpv" else "contradictory", [why])
return _post_colposcopy(facts, index, category, when, hpv, out)
for reason in ("registered_cin2_plus_before", "hysterectomy_declared"):
if reason in missing:
return out("not_applicable", [reason])
hpv, why = hpv_category(index)
if why:
return out("missing_data" if why == "missing_hpv" else "contradictory", [why])
if "earlier_test_older_than_5_years" in missing:
return out("history_not_demonstrable", ["earlier_test_older_than_5_years"])
if "history_is_a_surveillance_scenario" in missing:
return _second_visit(facts, index, category, when, hpv, out)
if not reading.master(facts):
return out("missing_data", ["reference_tables_not_in_gold"])
# the guidelines estimate with an unknown history too (its own rows)
history = "NO HISTORY" if "no_earlier_test_registered" in missing else "Cotest-negative"
used = [_used("current cotest", index)]
if history == "Cotest-negative":
last = max(
(
c
for c in facts.get("cytologies", []) # the test the history rests on, cited
if _day(c["sample_date"]) < when
and (_day(c.get("report_date")) or date.max) <= when
and _valid(c)
and c.get("hpv") is not None
),
key=lambda c: _day(c["sample_date"]),
)
used.insert(0, _used("earlier cotest", last))
rows, via = master_rows(facts, "screening", category, history=history, hpv=hpv)
scenario = {
"table": "screening",
"label": "Tamizaje",
"key": {"history": history, "hpv": hpv, "cytology": category},
}
return _found(rows, via, scenario, out, used=used)
@@ -0,0 +1,52 @@
"""The reference tables and the platform's results in their words."""
from core import cacu
AGE_RANGE = cacu.NCI_AGE_RANGE
# The platform's cytology (gold's `finding`) as the tables' vocabulary.
CYTOLOGY = {
"NILM": "NILM",
"ASC-US": "ASC-US",
"LSIL": "LSIL",
"ASC-H": "ASC-H",
"HSIL": "HSIL+",
"CIS": "HSIL+",
"carcinoma": "HSIL+",
"AGC": "AGC",
}
# A table category made of several results, by the tables' own definition (the high-grade results
# are ASC-H, AGC and HSIL+; ASC-US/LSIL is the pair). Never a fallback for another category.
GROUPS = {name: set(results) for name, results in cacu.NCI_CYTOLOGY_GROUPS.items()}
def high_grade(result: str | None) -> bool:
"""Whether the tables count the platform's cytology as ASC-H, AGC or HSIL+."""
return CYTOLOGY.get(result) in GROUPS["High Grade"]
# A biopsy's histology as the colposcopy table names it.
BIOPSY = {"normal": "<CIN1", "LSIL": "CIN1", "CIN2": "CIN2", "CIN3": "CIN3", "carcinoma": "Cancer"}
# Correspondences the platform cannot confirm, with why; an analyst who verifies one turns it off.
UNVERIFIED = {
"hsil_cin2_cin3": "the platform's HSIL biopsy does not separate CIN2 from CIN3",
"cis_ais": "the platform's carcinoma in situ is not told from adenocarcinoma in situ",
}
def hpv_category(cytology: dict) -> tuple[str | None, str | None]:
"""(the tables' current-HPV category, a reason it cannot be one). HPV 16 and 18 are not
read apart: a genotyped sample is HPV-positive."""
hpv = cytology.get("hpv")
if hpv is None:
return None, "missing_hpv"
if hpv:
return "HPV-positive", None
if cytology.get("hpv_16") or cytology.get("hpv_18"):
return None, "contradictory_hpv"
return "HPV-negative", None
+9
View File
@@ -0,0 +1,9 @@
"""The risk series a patient's record can choose to draw, each with its source, version,
outcome and published intervals (experimental).
Series are shown side by side and never subtracted here. A source that cannot be matched to her
by what the platform holds gives a series with its reasons and no number."""
from .record import OUTCOMES, institutional, nci_master, series
__all__ = ["OUTCOMES", "institutional", "nci_master", "series"]
+130
View File
@@ -0,0 +1,130 @@
"""The series of one patient's record: the models' and the NCI master table's."""
from collections.abc import Iterable
from datetime import date
from core.cacu import visibility
OUTCOMES = ("CIN2+", "CIN3+", "cancer")
NO_GENOTYPE = "Tiene genotipo de VPH; no se usó: la referencia es la de VPH positivo."
UNKNOWN_HISTORY = "Sin prueba de VPH anterior registrada: se usa la fila de historia desconocida."
def _series(identifier: str, source: str, outcome: str, label: str, points=(), **more) -> dict:
return {
"id": identifier,
"source": source,
"outcome": outcome,
"label": label,
"points": list(points),
"status": "resolved" if points else "unresolved",
"reasons": [],
"assumptions": [],
"version": None,
"method": None,
**more,
}
def _point(years, probability, interval: dict | None = None) -> dict:
interval = interval or {}
return {
"years": years,
"probability": probability,
"low": interval.get("lower"),
"high": interval.get("upper"),
"level": interval.get("level"),
}
def nci_master(resolution: dict) -> list[dict]:
"""The master table's row the record resolves, one series per outcome the table has, with
its 95% limits, versioned by the table's file."""
scenario = resolution.get("scenario") or {}
key = scenario.get("key", {})
label = " · ".join(
[scenario.get("label", "Tabla maestra"), *(str(v) for v in key.values() if v is not None)]
)
row = resolution.get("row")
risks = {
"CIN3+": {str(h["years"]): h["risk"] for h in resolution["horizons"] if h["published"]},
**(resolution.get("complementary") or {}),
}
assumptions = []
if any(u.get("hpv_16") or u.get("hpv_18") for u in resolution.get("used", [])):
assumptions.append(NO_GENOTYPE)
if key.get("history") == "NO HISTORY":
assumptions.append(UNKNOWN_HISTORY)
def point(outcome, years, risk):
low, high = (resolution.get("intervals") or {}).get(outcome, {}).get(years, (None, None))
interval = {"lower": low, "upper": high, "level": None if low is None else 0.95}
return _point(int(years), risk, interval)
result = []
for outcome in OUTCOMES:
points = [
point(outcome, years, risk)
for years, risk in sorted(risks.get(outcome, {}).items(), key=lambda i: int(i[0]))
if risk is not None and risks["CIN3+"]
]
if not points and outcome != "CIN3+":
continue
result.append(
_series(
f"nci-master-{outcome}",
"NCI",
outcome,
label,
points,
reasons=resolution["reasons"],
assumptions=assumptions,
version=f"sha256:{row['sha256']}" if row else None,
)
)
return result
def institutional(risks: Iterable[dict], cutoff: date, title) -> list[dict]:
"""One series per model, from its latest index date by the cut-off. `risks` are already the
ones that still apply (core.cacu.currency); survival is not a risk of disease."""
latest: dict[str, list[dict]] = {}
for r in risks:
index = str(r["index_date"])[:10]
if r["model"] == "cacu.survival" or index > cutoff.isoformat():
continue
held = latest.get(r["model"], [])
if not held or index > str(held[0]["index_date"])[:10]:
latest[r["model"]] = [r]
elif index == str(held[0]["index_date"])[:10]:
held.append(r)
return [
_series(
model,
"Institucional",
"cancer" if "cancer" in model else "CIN2+",
title(model),
[
_point(
int(r["horizon_years"]),
r["probability"],
{
"lower": r["ci_low"],
"upper": r["ci_high"],
"level": None if r["ci_low"] is None else 0.95,
},
)
for r in sorted(rows, key=lambda r: r["horizon_years"])
],
version=f"v{rows[0]['version']}",
)
for model, rows in sorted(latest.items())
]
def series(resolution: dict, risks: Iterable[dict], cutoff: date, title) -> list[dict]:
"""The models' series (but the hidden ones') and the NCI's."""
return [
*institutional((r for r in risks if visibility.model(r["model"])), cutoff, title),
*nci_master(resolution),
]
+56
View File
@@ -0,0 +1,56 @@
"""What gold can demonstrate about the stages after a cytology (colposcopy, biopsy, diagnosis):
each stage's state and where its day comes from. The route's days are in `gold.cacu_samples`;
the sources and the biopsy's record are read beside them (`persistance.fhir`).
States (the stage's day is published whatever its state; a stage with no day has none):
- `recorded`: a biopsy whose own record names the cytology it came from;
- `inferred`: dated by association: colposcopy and diagnosis are always so (silver has no
record of them: notes and biopsy orders date them), a biopsy only when its record does not
name the cytology;
- `pending`: a biopsy requested, with no report by the cut-off;
- `ambiguous`: a biopsy reported before it was requested (an impossible order).
Nothing is inferred beyond that: no request for a colposcopy or a diagnosis is known, so those
stages are never `pending`, and no rule dates a colposcopy or a diagnosis twice, so they are
never `ambiguous`.
Sources: `clinical-note` and `biopsy-order` for a colposcopy (a colposcopy-clinic note, or a
biopsy ordered at the visit), `clinical-note` for a diagnosis, `biopsy-record` (the record names
the cytology) or `date-association` (dates do) for a biopsy."""
STATES = ("recorded", "inferred", "pending", "ambiguous")
SOURCES = ("clinical-note", "biopsy-order", "biopsy-record", "date-association")
def stage_facts(row: dict) -> dict[str, tuple[str, list[str]]]:
"""Stage name -> (state, sources) for one sample, from its route row: the days
(`colposcopy`, `biopsy`, `diagnosis`, as known by the cut-off), the biopsy's first request
and `link`, `reported` (its first report by the cut-off), `backwards` (a reported biopsy\
older than
its request) and the sources that
date the colposcopy and the diagnosis (`colposcopy_note`, `colposcopy_biopsy`,
`diagnosis_note`)."""
out: dict[str, tuple[str, list[str]]] = {}
if row.get("colposcopy"):
found = [
s
for s, flag in (
("clinical-note", row.get("colposcopy_note")),
("biopsy-order", row.get("colposcopy_biopsy")),
)
if flag
]
out["colposcopy"] = ("inferred", found)
if row.get("diagnosis"):
out["diagnosis"] = ("inferred", ["clinical-note"] if row.get("diagnosis_note") else [])
if row.get("requested"):
source = {"recorded": "biopsy-record", "inferred": "date-association"}.get(
row.get("link") or ""
)
sources = [source] if source else []
if row.get("backwards"):
out["biopsy"] = ("ambiguous", sources)
elif not row.get("reported"):
out["biopsy"] = ("pending", sources)
elif row.get("biopsy"): # reported but out of the route's horizon: no day, no state
out["biopsy"] = ("recorded" if row.get("link") == "recorded" else "inferred", sources)
return out
+25
View File
@@ -0,0 +1,25 @@
"""What the platform shows of CaCu for now, decided in one place. The NCI books of genotype,
post-treatment and post-colposcopy second visit were deleted (docs/nci-referencias.md); the
hidden models (core.models.HIDDEN) are kept."""
from core import cacu, models
def scenario(code: str) -> bool:
"""A clinical scenario; a patient of a hidden one is answered as excluded."""
return code not in cacu.HIDDEN_SCENARIOS
def model(name: str) -> bool:
"""A model, as `<domain>.<name>`."""
return name not in models.HIDDEN
def nci_row(table: str, key: dict) -> bool:
"""A row of the NCI master table: genotype rows are kept as data and not read."""
return not (
not scenario(table)
or str(key.get("hpv") or "").startswith("HPV16")
# a history after colposcopy is a second visit or later
or (table == "post_colposcopy" and key.get("post_colposcopy_history"))
)
+7 -1
View File
@@ -34,7 +34,13 @@ DIAGNOSIS_ICD10 = [
# Measures (core.measures): the horizons, in days; an interval that hasn't ended after its
# horizon counts as not ended. A diagnosis this soon after the mammogram resolves it.
HORIZONS = {"sample_to_report": 60, "to_diagnosis": 180}
# Provisional: both 60-day horizons require clinical validation.
HORIZONS = {
"sample_to_report": 60,
"to_diagnosis": 180,
"biopsy_to_diagnosis": 60,
"diagnosis_to_treatment": 60,
}
AGE_GROUPS = [(40, 49), (50, 59), (60, 69)] # plus "<40" and "70+"
# The follow-up list: patients whose latest mammogram, taken within the window before the
+274 -55
View File
@@ -18,8 +18,16 @@ from core.measures import (
)
H = cama.HORIZONS
REPORT = {"report_known_at": ("report_date", "birads", "birads_rank", "days_sample_report",
"report_diagnosis_date", "days_report_diagnosis")} # fmt: skip
REPORT = {
"report_known_at": (
"report_date",
"birads",
"birads_rank",
"days_sample_report",
"report_diagnosis_date",
"days_report_diagnosis",
)
}
DIAGNOSIS = {"diagnosis_known_at": ("diagnosis_date", "days_sample_diagnosis")}
BIOPSY = {"biopsy_known_at": ("biopsy_report_date", "histology", "histology_rank")}
@@ -37,8 +45,13 @@ def most_severe(row: dict) -> tuple:
def then_its_most_severe_biopsy(row: dict) -> tuple:
"""Her most severe mammogram, then its most severe reported biopsy, the latest first."""
counted = row["biopsy_report_date"] is not None
return (*most_severe(row), counted, desc(row["histology_rank"]),
desc(as_day(row["biopsy_report_date"])), desc(row["biopsy_id"])) # fmt: skip
return (
*most_severe(row),
counted,
desc(row["histology_rank"]),
desc(as_day(row["biopsy_report_date"])),
desc(row["biopsy_id"]),
)
def birads(row: dict) -> str:
@@ -52,6 +65,18 @@ def biopsy_histology(row: dict) -> str:
return row["histology"] or NO_DATA
def biopsy_type(row: dict) -> str:
"""The selected biopsy's reported ICD-O-3 type, distinct from its classification."""
if row["biopsy_report_date"] is None:
return NO_BIOPSY
return row.get("histologic_type") or NO_DATA
def should_be_biopsied(row: dict) -> bool:
"""A reported mammogram whose BI-RADS asks for a biopsy (the confirmation's denominator)."""
return reported(row) and row["birads"] in cama.SUSPICIOUS
def four_to_six(row: dict) -> bool:
return reported(row) and row["birads"] in cama.BIRADS_4_TO_6
@@ -59,56 +84,250 @@ def four_to_six(row: dict) -> bool:
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no breast cancer note before
BIRADS = ("birads", lambda row, p: row["birads"])
MEASURES = {m.id: m for m in [
Measure("CAMA_BIRADS", "Distribución de BI-RADS", "mammograms",
Composition(most_severe, birads, date="exam_date"), facts=REPORT),
Measure("CAMA_BIRADS456_PACIENTE",
"Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6", "mammograms",
Composition(most_severe, birads, admit=four_to_six, date="exam_date"), facts=REPORT),
Measure("CAMA_BIRADS456_MASTOGRAFIA",
"Porcentaje individual de mastografías con resultado BI-RADS 4, 5 y 6", "mammograms",
Composition(most_severe, birads, where=four_to_six, unit="mammogram_id",
date="exam_date"), facts=REPORT),
Measure("CAMA_BIRADS_CANCER_INVASOR", "BI-RADS de la mastografía previa a un cáncer invasor",
MEASURES = {
m.id: m
for m in [
Measure(
"CAMA_BIRADS",
"Distribución de BI-RADS",
"mammograms",
Composition(most_severe, birads, date="exam_date"),
facts=REPORT,
),
Measure(
"CAMA_BIRADS456_PACIENTE",
"Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6",
"mammograms",
Composition(most_severe, birads, admit=four_to_six, date="exam_date"),
facts=REPORT,
),
Measure(
"CAMA_BIRADS456_MASTOGRAFIA",
"Porcentaje individual de mastografías con resultado BI-RADS 4, 5 y 6",
"mammograms",
Composition(
most_severe, birads, where=four_to_six, unit="mammogram_id", date="exam_date"
),
facts=REPORT,
),
Measure(
"CAMA_BIRADS_CANCER_INVASOR",
"BI-RADS de la mastografía previa a un cáncer invasor",
"biopsies",
Composition(lambda r: (r["birads"] is not None, as_day(r["report_date"]),
r["biopsy_id"]),
lambda r: r["birads"] or NO_DATA,
where=lambda r: r["histology"] in cama.INVASIVE, date="report_date"),
known="report_known_at"),
Measure("CAMA_BIOPSIAS", "Distribución de resultados de biopsia", "biopsies",
Composition(lambda r: (r["histology"] is not None, as_day(r["report_date"])),
lambda r: r["histology"] or NO_DATA, unit="biopsy_id",
date="report_date"),
known="report_known_at"),
Measure("CAMA_HISTOPATOLOGIA_BIRADS", "Resultado histopatológico por categoría BI-RADS",
"mammogram_biopsies",
Composition(then_its_most_severe_biopsy, biopsy_histology, admit=four_to_six,
strata=(BIRADS,), date="exam_date"),
facts=REPORT | BIOPSY),
Measure("CAMA_CONFIRMACION_BIRADS45", "Tasa de confirmación histopatológica",
"mammogram_biopsies",
Proportion(lambda r: r["biopsy_report_date"] is not None,
denominator=lambda r: r["report_date"] is not None
and r["birads"] in cama.SUSPICIOUS,
unit="mammogram_id", date="exam_date"),
"increase", group="principal", facts=REPORT | BIOPSY),
Measure("CAMA_TASA_DETECCION_HISTOPATOLOGICA", "Tasa de detección histopatológica",
Composition(
lambda r: (r["birads"] is not None, as_day(r["report_date"]), r["biopsy_id"]),
lambda r: r["birads"] or NO_DATA,
where=lambda r: r["histology"] in cama.INVASIVE,
date="report_date",
),
known="report_known_at",
),
Measure(
"CAMA_BIOPSIAS",
"Distribución de resultados de biopsia",
"biopsies",
Proportion(lambda r: r["histology"] in cama.CANCER,
denominator=lambda r: r["histology"] in cama.BIOPSY_SEVERITY,
unit="biopsy_id", date="report_date"),
group="principal", known="report_known_at"),
Measure("CAMA_EU38A", "Días de la toma de la mastografía a su resultado", "mammograms",
Duration("days_sample_report", "report_date", "exam_date", H["sample_to_report"],
unit="mammogram_id", date="exam_date"), "decrease", facts=REPORT),
Measure("CAMA_DIAS_TOMA_DIAGNOSTICO", "Tiempo de tamizaje a diagnóstico", "mammograms",
Duration("days_sample_diagnosis", "diagnosis_date", "exam_date", H["to_diagnosis"],
units=NO_HISTORY, unit="mammogram_id", date="exam_date"),
"decrease", facts=DIAGNOSIS),
Measure("CAMA_DIAS_RESULTADO_DIAGNOSTICO", "Tiempo de resultado a diagnóstico", "mammograms",
Duration("days_report_diagnosis", "report_diagnosis_date", "report_date",
H["to_diagnosis"], units=NO_HISTORY, unit="mammogram_id",
date="report_date"),
"decrease", known="report_known_at"),
]} # fmt: skip
Composition(
lambda r: (r["histology"] is not None, as_day(r["report_date"])),
lambda r: r["histology"] or NO_DATA,
unit="biopsy_id",
date="report_date",
),
known="report_known_at",
),
Measure(
"CAMA_TIPO_HISTOLOGICO",
"Tipo histológico de biopsias",
"biopsy_types",
Composition(
lambda r: (),
lambda r: r["histologic_type"] or NO_DATA,
unit="biopsy_id",
date="report_date",
),
known="report_known_at",
description="Biopsias por fecha de reporte y tipo histológico CIE-O-3. "
"Sin dato incluye biopsias sin tipo o con vínculo ambiguo.",
),
Measure(
"CAMA_HISTOPATOLOGIA_BIRADS",
"Resultado histopatológico por categoría BI-RADS",
"mammogram_biopsies",
Composition(
then_its_most_severe_biopsy,
biopsy_histology,
admit=four_to_six,
strata=(BIRADS,),
date="exam_date",
),
facts=REPORT | BIOPSY,
),
Measure(
"CAMA_TIPO_HISTOLOGICO_BIRADS",
"Tipo histológico por categoría BI-RADS",
"mammogram_biopsy_types",
Composition(
then_its_most_severe_biopsy,
biopsy_type,
admit=four_to_six,
strata=(BIRADS,),
date="exam_date",
),
facts=REPORT
| {
"biopsy_known_at": (
"biopsy_report_date",
"histology",
"histology_rank",
"histologic_type",
)
},
description="Tipo histológico CIE-O-3 de la biopsia vinculada; sin tipo o con "
"vínculo ambiguo se registra como sin dato.",
),
Measure(
"CAMA_CONFIRMACION_BIRADS45",
"Tasa de confirmación histopatológica",
"mammogram_biopsies",
Proportion(
lambda r: r["biopsy_report_date"] is not None,
denominator=lambda r: (
r["report_date"] is not None and r["birads"] in cama.SUSPICIOUS
),
unit="mammogram_id",
date="exam_date",
),
"increase",
group="principal",
facts=REPORT | BIOPSY,
),
Measure(
"CAMA_TASA_DETECCION_HISTOPATOLOGICA",
"Tasa de detección histopatológica",
"biopsies",
Proportion(
lambda r: r["histology"] in cama.CANCER,
denominator=lambda r: r["histology"] in cama.BIOPSY_SEVERITY,
unit="biopsy_id",
date="report_date",
),
group="principal",
known="report_known_at",
),
Measure(
"CAMA_EU38A",
"Días de la toma de la mastografía a su resultado",
"mammograms",
Duration(
"days_sample_report",
"report_date",
"exam_date",
H["sample_to_report"],
unit="mammogram_id",
date="exam_date",
),
"decrease",
facts=REPORT,
),
Measure(
"CAMA_DIAS_TOMA_DIAGNOSTICO",
"Tiempo de tamizaje a diagnóstico",
"mammograms",
Duration(
"days_sample_diagnosis",
"diagnosis_date",
"exam_date",
H["to_diagnosis"],
units=NO_HISTORY,
unit="mammogram_id",
date="exam_date",
),
"decrease",
facts=DIAGNOSIS,
),
Measure(
"CAMA_DIAS_RESULTADO_DIAGNOSTICO",
"Tiempo de resultado a diagnóstico",
"mammograms",
Duration(
"days_report_diagnosis",
"report_diagnosis_date",
"report_date",
H["to_diagnosis"],
units=NO_HISTORY,
unit="mammogram_id",
date="report_date",
),
"decrease",
known="report_known_at",
),
Measure(
"CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO",
"Tiempo de diagnóstico tras biopsia a tratamiento",
"diagnosis_treatment",
Duration(
"days_diagnosis_treatment",
"diagnosis_treatment_date",
"biopsy_diagnosis_date",
H["diagnosis_to_treatment"],
units=lambda r: NO_HISTORY(r) and r["biopsy_diagnosis_date"] is not None,
unit="mammogram_id",
date="exam_date",
),
"decrease",
facts={
"biopsy_date_known_at": (
"biopsy_diagnosis_date",
"diagnosis_treatment_date",
"days_diagnosis_treatment",
),
"biopsy_diagnosis_known_at": (
"biopsy_diagnosis_date",
"diagnosis_treatment_date",
"days_diagnosis_treatment",
),
"diagnosis_treatment_known_at": (
"diagnosis_treatment_date",
"days_diagnosis_treatment",
),
},
dated={
"biopsy_date": (
"biopsy_diagnosis_date",
"diagnosis_treatment_date",
"days_diagnosis_treatment",
),
"biopsy_diagnosis_date": ("diagnosis_treatment_date", "days_diagnosis_treatment"),
},
description="PROVISIONAL: horizontes de 60 días pendientes de validación clínica; "
"diagnóstico posterior a biopsia vinculada y primer tratamiento, incluido el mismo "
"día.",
),
# Pending the analysts' validation (LOTE-3-CAMA-REBUILD.md): the biopsy is the one whose
# request names the mammogram, the first reported if several; the horizon is the
# diagnosis's, as no other is set.
Measure(
"CAMA_DIAS_RESULTADO_BIOPSIA",
"Tiempo de resultado de mastografía a resultado de biopsia",
"mammogram_first_biopsy",
Duration(
"days_report_biopsy",
"biopsy_report_date",
"report_date",
H["to_diagnosis"],
units=should_be_biopsied,
unit="mammogram_id",
date="report_date",
),
"decrease",
facts=REPORT | {"biopsy_known_at": ("biopsy_report_date", "days_report_biopsy")},
description=(
"PROVISIONAL, pendiente de validación metodológica de los analistas. Días del "
"reporte de la mastografía (BI-RADS 4, 4A, 4B, 4C o 5) al reporte de la primera "
"biopsia reportada cuya solicitud nombra esa mastografía; sin vínculo explícito "
"no hay medición. Horizonte de 180 días reutilizado del tramo a diagnóstico "
"(no hay uno propio). Por decidir: fuente real del vínculo, cohorte, selección "
"con varias biopsias, horizonte, historia de cáncer y fechas inconsistentes."
),
),
]
}
+3 -1
View File
@@ -61,6 +61,7 @@ class Study(BaseModel):
key: list[str] # fields that, with the person, identify one study instance
events: dict[EventClass, Event]
fields: dict[str, FieldDef]
ingest_only: bool = False
@model_validator(mode="after")
def _consistent(self):
@@ -99,7 +100,8 @@ def files() -> dict[str, list[str]]:
def of_domain(domain: str) -> list[str]:
"""The studies a domain serves: its own and the common ones."""
return [*files().get(domain, []), *files().get("common", [])]
return [name for name in [*files().get(domain, []), *files().get("common", [])]
if not studies()[name].ingest_only] # fmt: skip
@cache
+24
View File
@@ -1,4 +1,16 @@
# Cervical cancer screening.
cacu_eligibility_evidence:
title: Evidencia clínica para elegibilidad CaCu
ingest_only: true
key: [evidence_id]
events:
encounter: {date: evidence_date}
fields:
evidence_id: {type: text, event: encounter, title: Referencia en origen, required: true}
evidence_date: {type: date, event: encounter, title: Fecha clínica}
evidence_type: {type: text, event: encounter, title: Tipo de evidencia, required: true}
evidence_code: {type: text, event: encounter, title: Código clínico, required: true}
cervical_cytology:
title: Citología cervical
key: [sample_date]
@@ -69,6 +81,16 @@ cervical_cytology:
LSIL: Lesión intraepitelial escamosa de bajo grado
HSIL: Lesión intraepitelial escamosa de alto grado
CIS: Carcinoma in situ
carcinoma: Carcinoma epidermoide invasor
# Bethesda's glandular cells, beside the squamous result (the form's box 15).
glandular:
type: code
event: report
title: Células glandulares
system: bethesda-glandular
codes:
AGC: Células glandulares atípicas
adenocarcinoma: Adenocarcinoma
hpv: {type: boolean, event: report, title: VPH de alto riesgo}
hpv_16: {type: boolean, event: report, title: VPH 16}
hpv_18: {type: boolean, event: report, title: VPH 18}
@@ -120,6 +142,8 @@ cervical_biopsy:
codes:
normal: Sin lesión
LSIL: Lesión intraepitelial escamosa de bajo grado (CIN 1)
CIN2: Neoplasia intraepitelial cervical grado 2 (CIN 2)
HSIL: Lesión intraepitelial escamosa de alto grado (CIN 2-3)
CIN3: Neoplasia intraepitelial cervical grado 3 (CIN 3)
CIS: Carcinoma in situ
carcinoma: Carcinoma invasor
+3
View File
@@ -3,6 +3,9 @@
bethesda:
url: https://isssteleon.org/fhir/CodeSystem/bethesda
title: Sistema Bethesda (citología cervical)
bethesda-glandular:
url: https://isssteleon.org/fhir/CodeSystem/bethesda-glandular
title: Sistema Bethesda, células glandulares
who-cervical-histology:
url: https://isssteleon.org/fhir/CodeSystem/who-cervical-histology
title: Clasificación OMS de lesiones cervicales (histología)
+341 -5
View File
@@ -16,6 +16,7 @@ from fhir.resources.R4B.diagnosticreport import DiagnosticReport
from fhir.resources.R4B.encounter import Encounter
from fhir.resources.R4B.measure import Measure
from fhir.resources.R4B.observation import Observation
from fhir.resources.R4B.parameters import Parameters
from fhir.resources.R4B.patient import Patient
from fhir.resources.R4B.procedure import Procedure
from fhir.resources.R4B.resource import Resource
@@ -24,6 +25,7 @@ from fhir.resources.R4B.searchparameter import SearchParameter
from fhir.resources.R4B.structuredefinition import StructureDefinition
from core import catalog, models
from core.cacu import visibility
FHIR_VERSION = "4.3.0"
BASE = "https://isssteleon.org/fhir"
@@ -36,6 +38,30 @@ _IDS = uuid.uuid5(uuid.NAMESPACE_URL, BASE)
# Local code systems: code -> display (Spanish, as the screens show them).
CODE_SYSTEMS: dict[str, tuple[str, dict[str, str]]] = {
"cacu-eligibility-scenario": ("Escenarios de elegibilidad CaCu", {
"surveillance": "Vigilancia", "pre_colposcopy": "Precolposcopia",
"post_colposcopy": "Postcolposcopia",
"post_colposcopy_second_visit": "Segunda visita postcolposcopia",
"post_treatment": "Postratamiento", "survival": "Supervivencia",
}),
"cacu-exclusion-criterion": ("Criterios de exclusión CaCu", {
"hysterectomy": "Histerectomía previa al índice",
"under_18": "Edad menor de 18 años al índice",
"prior_outcome": "Resultado CIN2+ previo al índice",
"no_index_result": "Sin resultado de citología o VPH en la visita índice",
"unreported_biopsy": "Biopsia solicitada sin resultado",
"outcome_by_index": "Resultado CIN2+ hasta la visita índice",
"cancer_history": "Antecedente de cáncer cervicouterino",
"prior_treatment": "Tratamiento previo a la visita índice",
"no_referral": "Sin citologia de referencia previa a la colposcopia",
"referral_not_graded": "Citologia de referencia de bajo grado sin VPH positivo",
"no_cotest": "Sin cotest de citología y VPH en la visita índice",
"no_pretreatment_biopsy": "Sin biopsia previa al tratamiento en el periodo requerido",
"outcome_before_index": "Resultado CIN2+ entre tratamiento e índice",
"no_birth_date": "Fecha de nacimiento desconocida",
"died_by_index": "Defunción en o antes de la visita índice",
"not_evaluated": "Escenario que la plataforma no evalúa por ahora",
}),
"cacu-procedure": ("Procedimientos de CaCu", {
"colposcopy": "Colposcopia", "treatment": "Tratamiento",
}),
@@ -69,6 +95,7 @@ CODE_SYSTEMS: dict[str, tuple[str, dict[str, str]]] = {
"birads": "BI-RADS de la mastografía", "diagnosis_code": "Diagnóstico CIE-10",
"cytology": "Citología previa", "hpv": "VPH de la citología previa",
"level": "Histología confirmada", "round": "Tamizaje inicial o subsecuente",
"subsequent_history": "Antecedente declarado de detección subsecuente",
"hpv_16": "VPH 16", "hpv_18": "VPH 18",
}),
"risk-model": ("Modelos de riesgo", {}), # open: a model's name is its code
@@ -97,16 +124,32 @@ CODE_SYSTEMS["catalog-field"] = ("Campos de los estudios", {
# Where a duration is scored: the whole, and each stratum with a score of its own.
DURATIONS = ["MeasureReport.group.measureScore",
"MeasureReport.group.stratifier.stratum.measureScore"] # fmt: skip
# Extensions an element may carry more than once (one per period type, one per source).
REPEATED = {
"period-type",
"stage-colposcopy-source",
"stage-biopsy-source",
"stage-diagnosis-source",
}
# Our extensions: name -> (value type, the elements they extend).
EXTENSIONS: dict[str, tuple[str, list[str]]] = {
"ic-bajo": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
"ic-alto": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
"ic-estado": ("code", ["RiskAssessment.prediction"]),
"ic-metodo": ("code", ["RiskAssessment.prediction"]),
"ic-nivel": ("decimal", ["RiskAssessment.prediction"]),
"prediction-measure": ("code", ["RiskAssessment"]),
"model-inputs": ("string", ["RiskAssessment"]),
"q1": ("decimal", DURATIONS),
"q3": ("decimal", DURATIONS),
"corte-conocimiento": ("dateTime", ["MeasureReport"]),
"period-type": ("code", ["Measure"]),
"follow-up-status": ("Coding", ["Patient"]),
"follow-up-priority": ("Coding", ["Patient"]),
"first-hysterectomy-recorded": ("date", ["Patient"]),
# why some of her model risks are not shown at the cut-off (core.cacu.currency)
"risk-withheld": ("string", ["Patient"]),
"report-date": ("date", ["DiagnosticReport"]),
"days-to-diagnosis": ("integer", ["DiagnosticReport"]),
# what followed a cytology: colposcopy and diagnosis are inferred; `biopsy-link` says
@@ -116,6 +159,14 @@ EXTENSIONS: dict[str, tuple[str, list[str]]] = {
"biopsy-date": ("date", ["DiagnosticReport"]),
"biopsy-link": ("code", ["DiagnosticReport"]),
"diagnosis-date": ("date", ["DiagnosticReport"]),
# the state of each stage and where its day comes from (core.cacu.stages): recorded, inferred,
# pending or ambiguous; sources are repeated, one per source
"stage-colposcopy-state": ("code", ["DiagnosticReport"]),
"stage-colposcopy-source": ("code", ["DiagnosticReport"]),
"stage-biopsy-state": ("code", ["DiagnosticReport"]),
"stage-biopsy-source": ("code", ["DiagnosticReport"]),
"stage-diagnosis-state": ("code", ["DiagnosticReport"]),
"stage-diagnosis-source": ("code", ["DiagnosticReport"]),
# a clinical scenario of the model's report the person falls in (its curves)
"escenario-clinico": ("string", ["RiskAssessment"]),
# a child on TEA's list: her age group, case, EEG and scores
@@ -174,6 +225,12 @@ _REPORT_FACTS = {"days": "days-to-diagnosis", "colposcopy": "colposcopy-date",
def report_facts(row: dict) -> list[dict]:
found = []
if "requested" in row or "colposcopy_note" in row: # CaCu: what the route's stages are
from core.cacu.stages import stage_facts
for stage, (state, sources) in stage_facts(row).items():
found.append(ext(f"stage-{stage}-state", "code", state))
found += [ext(f"stage-{stage}-source", "code", s) for s in sources]
for column, name in _REPORT_FACTS.items():
if (value := row.get(column)) is not None:
kind = EXTENSIONS[name][0]
@@ -205,6 +262,12 @@ def patient(row: dict, status_system: str | None = None) -> Patient:
priority = coding("follow-up-priority", row["priority"])
found["extension"].append(ext("follow-up-priority", "Coding", priority))
found.setdefault("extension", []).extend(_tea_listed(row))
if row.get("first_hysterectomy"):
found["extension"].append(
ext("first-hysterectomy-recorded", "date", _day(row["first_hysterectomy"]))
)
if row.get("risk_withheld"):
found["extension"].append(ext("risk-withheld", "string", row["risk_withheld"]))
if not found["extension"]:
del found["extension"]
if row.get("names"):
@@ -387,6 +450,13 @@ def risk_assessment(row: dict, horizons: Iterable[dict]) -> RiskAssessment:
bounds = (("ic-bajo", "ci_low"), ("ic-alto", "ci_high"))
interval = [ext(name, "decimal", h[key]) for name, key in bounds
if h.get(key) is not None] # fmt: skip
if row["model"] == "cacu.survival":
available = h.get("ci_low") is not None and h.get("ci_high") is not None
interval.append(ext("ic-estado", "code", "available" if available else "unavailable"))
if available:
interval.append(ext("ic-metodo", "code", h.get("ci_method") or "unknown"))
if h.get("ci_level") is not None:
interval.append(ext("ic-nivel", "decimal", h["ci_level"]))
predictions.append({
"probabilityDecimal": h["probability"],
"whenRange": {"high": {"value": h["horizon_years"], "unit": "a", "system": UCUM,
@@ -405,9 +475,13 @@ def risk_assessment(row: dict, horizons: Iterable[dict]) -> RiskAssessment:
"subject": subject(row["person_id"]),
"occurrenceDateTime": _day(row["index_date"]),
"prediction": predictions,
**({"extension": [ext("escenario-clinico", "string", name) for name in scenarios]}
if (scenarios := [n for n in (row.get("scenarios") or "").split(SCENARIO_SEPARATOR)
if n]) else {}),
"extension": [ext("prediction-measure", "code",
"mortality" if model.endswith('.survival') else
"other" if model.endswith('.recurrence') else "risk"),
*([ext("model-inputs", "string", row["input_values"])]
if row.get("input_values") else []),
*[ext("escenario-clinico", "string", n)
for n in (row.get("scenarios") or "").split(SCENARIO_SEPARATOR) if n]],
}) # fmt: skip
@@ -467,6 +541,8 @@ def measure(m, domain: str) -> Measure:
"extension": [ext("period-type", "code", p) for p in m.periods],
"group": [group],
} # fmt: skip
if m.references:
found["relatedArtifact"] = list(m.references)
if m.description:
found["description"] = m.description
if m.improvement:
@@ -501,8 +577,7 @@ def extensions() -> list[StructureDefinition]:
"baseDefinition": "http://hl7.org/fhir/StructureDefinition/Extension",
"derivation": "constraint",
"differential": {"element": [
{"id": "Extension", "path": "Extension", "max": "*" if name == "period-type"
else "1"},
{"id": "Extension", "path": "Extension", "max": "*" if name in REPEATED else "1"},
{"id": "Extension.extension", "path": "Extension.extension", "max": "0"},
{"id": "Extension.url", "path": "Extension.url", "fixedUri": url},
{"id": "Extension.value[x]", "path": "Extension.value[x]", "min": 1,
@@ -542,3 +617,264 @@ def conformance() -> list[Resource]:
"""Everything our resources declare: what the validator loads, and what the
CapabilityStatement points to."""
return [*code_systems(), *extensions(), *search_parameters()]
# --- the NCI reference comparison (experimental) ------------------------------------------------
def _part(name: str, kind: str, value=None, parts: list | None = None) -> dict:
"""A Parameters part: a named value of the given kind (code, string, date, integer, decimal,
boolean) or named parts; nothing when it has neither (FHIR allows no empty part)."""
found: dict = {"name": name}
if parts is not None:
kept = [p for p in parts if p]
if not kept:
return {}
found["part"] = kept
elif value is not None:
found[f"value{kind[0].upper()}{kind[1:]}"] = (
value.isoformat() if isinstance(value, date) and kind == "date" else value
)
else:
return {}
return found
def reference_risk(resolution: dict, comparison: list[dict]) -> Parameters:
"""One patient's NCI reference resolution as a Parameters (the result of the $reference-risk
operation): the state and its reasons, the scenario and the row it came from, what was\
used, each
horizon's reference risk and, per institutional model, the comparison. Nothing here is stored: a
state with no risk has no reference part, and a blank risk is not zero."""
p = _part
index = resolution.get("index") or {}
scenario = resolution.get("scenario")
row = resolution.get("row")
parts = [
p("status", "code", resolution["status"]),
*[p("reason", "code", r) for r in resolution["reasons"]],
p("experimental", "boolean", True),
p("cutoff", "date", resolution["cutoff"]),
]
if index:
parts.append(
p(
"index",
"string",
None,
[
p("sample-date", "date", index.get("sample_date")),
p("report-date", "date", index.get("report_date")),
p("result", "code", index.get("result")),
p("age", "integer", resolution.get("age")),
],
)
)
if resolution.get("evaluation_date"):
parts.append(p("evaluation-date", "date", resolution["evaluation_date"]))
if scenario:
parts.append(
p(
"scenario",
"string",
None,
[
p("table", "code", scenario["table"]),
p("label", "string", scenario["label"]),
*[
p("key", "string", None, [p("name", "code", k), p("value", "string", v)])
for k, v in scenario["key"].items()
if v is not None
],
],
)
)
if row:
parts.append(
p(
"source",
"string",
None,
[
p("file", "string", row["book"]),
p("sha256", "string", row["sha256"]),
p("outcome", "code", "CIN3+"),
],
)
)
parts.append(
p(
"row",
"string",
None,
[
p("sheet", "string", row["sheet"]),
p("number", "integer", row["row"]),
p("matched-via", "code", resolution.get("matched_via")),
],
)
)
for u in resolution.get("used", []):
parts.append(
p(
"used",
"string",
None,
[
p(
k.replace("_", "-"),
"date" if k.endswith("date") else "string",
v if k.endswith("date") else None if v is None else str(v),
)
for k, v in u.items()
if v is not None
],
)
)
parts += [p("assumption", "string", a) for a in resolution.get("assumptions", [])]
for h in resolution.get("horizons", []):
mine = [c for c in comparison if c["years"] == h["years"]]
parts.append(
p(
"horizon",
"string",
None,
[
p("years", "integer", h["years"]),
p("published", "boolean", h["published"]),
p("reference", "decimal", h["risk"]),
*[
p(
"comparison",
"string",
None,
[
p("model", "code", c.get("model")),
p("title", "string", c.get("title")),
p("outcome", "string", c.get("outcome")),
p("institutional", "decimal", c.get("institutional")),
p(
"institutional-low",
"decimal",
(c.get("interval") or [None, None])[0],
),
p(
"institutional-high",
"decimal",
(c.get("interval") or [None, None])[1],
),
p("status", "code", c["status"]),
p("difference-pp", "decimal", c.get("difference_pp")),
*[p("reason", "code", r) for r in c["reasons"]],
],
)
for c in mine
],
],
)
)
return Parameters.model_validate(
{"resourceType": "Parameters", "parameter": [x for x in parts if x]}
)
def risk_series(series: list[dict], patient_id: str, cutoff: date) -> Parameters:
"""The risk series of one patient (core.cacu.risk_series): probabilities as stored or
published, not rounded; a series without a number says why."""
p = _part
parts = [p("patient", "Reference", {"reference": f"Patient/{patient_id}"}),
p("cutoff", "date", cutoff), p("experimental", "boolean", True)] # fmt: skip
for s in series:
parts.append(
p(
"series",
"string",
None,
[
p("id", "string", s["id"]),
p("source", "string", s["source"]),
p("version", "string", s["version"]),
p("outcome", "string", s["outcome"]),
p("label", "string", s["label"]),
p("status", "code", s["status"]),
*[p("reason", "code", r) for r in s["reasons"]],
*[p("assumption", "string", a) for a in s["assumptions"]],
*[
p(
"point",
"string",
None,
[
p("years", "integer", point["years"]),
p("probability", "decimal", point["probability"]),
p("low", "decimal", point["low"]),
p("high", "decimal", point["high"]),
p("level", "decimal", point["level"]),
],
)
for point in s["points"]
],
],
)
)
return Parameters.model_validate(
{"resourceType": "Parameters", "parameter": [x for x in parts if x]}
)
def cacu_eligibility(rows: Iterable[dict], patient_id: str, cutoff: date) -> Parameters:
"""Eligibility of one patient's indexed CaCu candidates, with each detected reason."""
candidates: dict[tuple, dict] = {}
for row in rows:
key = (row["scenario"], row["index_date"], row.get("index_sample_id"))
candidate = candidates.setdefault(
key,
{
"scenario": row["scenario"],
"index_date": row["index_date"],
"sample_id": row.get("index_sample_id"),
"eligible": bool(row["eligible"]),
"criteria": [],
},
)
if row.get("criterion") is not None:
candidate["criteria"].append(row["criterion"])
if not visibility.scenario(row["scenario"]):
candidate["eligible"] = False
candidate["criteria"].append("not_evaluated")
p = _part
def coding(system_name: str, code: str) -> dict:
title, codes = CODE_SYSTEMS[system_name]
return {"system": f"{CODES}{system_name}", "code": code, "display": codes.get(code, title)}
parts = [
p("status", "code", "evaluated" if candidates else "no_candidate"),
p("patient", "Reference", {"reference": f"Patient/{patient_id}"}),
p("cutoff", "date", cutoff),
]
for key in sorted(candidates, key=lambda item: tuple(str(value) for value in item)):
candidate = candidates[key]
parts.append(
p(
"candidate",
"string",
None,
[
p(
"scenario",
"Coding",
coding("cacu-eligibility-scenario", candidate["scenario"]),
),
p("index-date", "date", candidate["index_date"]),
p("index-sample-id", "string", candidate["sample_id"]),
p("eligible", "boolean", candidate["eligible"]),
*[
p("criterion", "Coding", coding("cacu-exclusion-criterion", reason))
for reason in sorted(set(candidate["criteria"]))
],
],
)
)
return Parameters.model_validate({"resourceType": "Parameters", "parameter": parts})
+172 -6
View File
@@ -11,18 +11,23 @@ target holds the row saying why.
"""
import hashlib
import json
from collections.abc import Iterable
from datetime import date, datetime
from typing import Any
from zoneinfo import ZoneInfo
from fhir.resources.R4B.conceptmap import ConceptMap
from core import catalog, concept_map
from core.fhir import CODES
from core.pipeline import RECORD
from core.pipeline import FIELD_EVIDENCE, RECORD
from core.schema import IDENTIFIER_SYSTEMS
STUDY = CODES + "study"
FIELD = CODES + "catalog-field"
EVIDENCE = "cacu_eligibility_evidence"
FINAL_RESULTS = {"final", "amended", "corrected"}
def record(sender: str, reference: str) -> str:
@@ -48,6 +53,29 @@ def _entries(bundle: dict) -> dict[str, dict]:
return found
def combined(bundles: Iterable[dict]) -> dict:
"""Latest resources for one sender, with Bundle-local references made canonical."""
def reference(item: dict, named: dict) -> dict:
target = named.get(item.get("reference"))
if target is None:
return item
return {**item, "reference": f"{target['resourceType']}/{target['id']}"}
latest = {}
for bundle in bundles:
named = _entries(bundle)
for ref, resource in resources(bundle).items():
resource = resource.copy()
for field in ("subject", "encounter"):
if resource.get(field):
resource[field] = reference(resource[field], named)
if resource["resourceType"] == "DiagnosticReport" and resource.get("result"):
resource["result"] = [reference(item, named) for item in resource["result"]]
latest[ref] = resource
return {"entry": [{"resource": resource} for resource in latest.values()]}
def _translated(maps: Iterable[ConceptMap], coding: dict, system: str) -> str | None:
"""A coding as a code of `system`: as it is when already there, else through the maps."""
if coding.get("system") == system:
@@ -97,6 +125,105 @@ def _value(observation: dict, f: catalog.FieldDef, maps) -> Any:
return None
# The day of a record is the one in Monterrey, whatever zone the sender wrote it in.
LOCAL = ZoneInfo("America/Monterrey")
def _source_time(value: str | None) -> str | None:
"""Keep a complete date or write a zoned timestamp in Monterrey time.
Partial dates and timestamps without a zone cannot establish a safe day cut-off.
They remain unknown rather than being completed or assigned a local timezone.
"""
if not value:
return None
try:
if len(value) == 10:
return date.fromisoformat(value).isoformat()
stamp = datetime.fromisoformat(value)
if stamp.tzinfo is not None:
return stamp.astimezone(LOCAL).isoformat(timespec="microseconds")
except ValueError:
pass
return None
def _clinical_day(value: str | None) -> str | None:
"""Use the same Monterrey day for clinical and availability timestamps."""
normalized = _source_time(value)
return normalized[:10] if normalized else None
def _evidence(ref: str, clinical: str | None, available: str | None) -> dict:
return {
"source_ref": ref,
"source_clinical_date": _clinical_day(clinical),
"source_available_at": _source_time(available),
}
def _report_observations(sent: dict, named: dict) -> set[str]:
return {
o["id"]
for r in sent.values()
if r["resourceType"] == "DiagnosticReport"
for item in r.get("result", [])
if (o := named.get(item.get("reference", ""))) is not None
and o["resourceType"] == "Observation"
}
def _standalone_evidence(sent: dict, named: dict, sender: str, maps) -> list[dict]:
linked = _report_observations(sent, named)
exams = catalog.studies()["cervical_cytology"].fields["gynecologic_condition"]
icd10 = catalog.systems()["icd-10"].url
out = []
for ref, r in sent.items():
kind = r["resourceType"]
if kind == "Condition":
verification = _codings(r.get("verificationStatus"))
if verification and not any(c.get("code") == "confirmed" for c in verification):
continue
codes = (_translated(maps, c, icd10) for c in _codings(r.get("code")))
value = next((code for code in codes if code), None)
clinical = r.get("onsetDateTime") or (r.get("onsetPeriod") or {}).get("end")
available = r.get("recordedDate")
event = "condition"
elif kind == "Observation":
if r["id"] in linked or r.get("encounter") or r.get("status") not in FINAL_RESULTS:
continue
if not any(
_translated(maps, c, FIELD) == "cervical_cytology.gynecologic_condition"
for c in _codings(r.get("code"))
):
continue
value = _value(r, exams, maps)
if value not in exams.codes:
continue
clinical = (
r.get("effectiveDateTime")
or r.get("effectiveInstant")
or (r.get("effectivePeriod") or {}).get("end")
)
available = r.get("issued")
event = "gynecologic_condition"
else:
continue
if value:
evidence = _evidence(f"{sender}|{ref}", clinical, available)
out.append(
{
RECORD: record(sender, ref),
"evidence_id": evidence["source_ref"],
"evidence_date": evidence["source_clinical_date"],
"evidence_type": event,
"evidence_code": value,
FIELD_EVIDENCE: json.dumps({"evidence_code": evidence}),
}
)
return out
def rows(bundle: dict, entity: str, sender: str, maps: Iterable[ConceptMap] = ()) -> list[dict]:
"""The Bundle's rows of one entity: `identity` (each Patient, and each report's
subject), `death` (Patients who died), or a study of the catalog (each report or
@@ -111,18 +238,25 @@ def rows(bundle: dict, entity: str, sender: str, maps: Iterable[ConceptMap] = ()
if entity == "identity":
out = [{**identity(r), RECORD: record(sender, ref)}
for ref, r in sent.items() if r["resourceType"] == "Patient"] # fmt: skip
linked = _report_observations(sent, named)
for ref, r in sent.items():
if r["resourceType"] in ("DiagnosticReport", "Encounter") and (p := subject(r)):
kind = r["resourceType"]
standalone = kind == "Observation" and r["id"] not in linked and not r.get("encounter")
if (standalone or kind in ("DiagnosticReport", "Encounter", "Condition")) and (
p := subject(r)
):
out.append({**identity(p), RECORD: record(sender, ref)})
return out
if entity == "death":
return [{"death_date": r["deceasedDateTime"][:10], RECORD: record(sender, ref)}
for ref, r in sent.items()
if r["resourceType"] == "Patient" and r.get("deceasedDateTime")] # fmt: skip
if entity == EVIDENCE:
return _standalone_evidence(sent, named, sender, maps)
spec = catalog.studies()[entity]
kind = "DiagnosticReport" if "report" in spec.events else "Encounter"
root = next(e for e in spec.events.values() if e.parent is None)
root_name, root = next((n, e) for n, e in spec.events.items() if e.parent is None)
out = []
for ref, r in sent.items():
if r["resourceType"] != kind:
@@ -130,28 +264,60 @@ def rows(bundle: dict, entity: str, sender: str, maps: Iterable[ConceptMap] = ()
code = r.get("code") if kind == "DiagnosticReport" else (r.get("type") or [None])[0]
if not any(_translated(maps, c, STUDY) == entity for c in _codings(code)):
continue
if r.get("status") == "entered-in-error": # annulled: nothing of it is used
continue
row: dict[str, Any] = {RECORD: record(sender, ref)}
start = r.get("effectiveDateTime") if kind == "DiagnosticReport" else (
(r.get("period") or {}).get("start")) # fmt: skip
if kind == "DiagnosticReport":
start = r.get("effectiveDateTime") or (r.get("effectivePeriod") or {}).get("start")
else:
start = (r.get("period") or {}).get("start")
if start:
row[root.date] = start[:10]
release = None
# A preliminary report is a sample still waiting for its result.
pending = r.get("status") == "preliminary"
if kind == "DiagnosticReport":
reported = next((x.get("valueDate") for x in r.get("extension", [])
if x.get("url", "").endswith("/report-date")), None) # fmt: skip
reported = reported or (r.get("issued") or "")[:10] or None
if reported:
if r.get("status") in FINAL_RESULTS | {"appended"}:
release = r.get("issued") or reported
if reported and not pending:
row[spec.events["report"].date] = reported
results = [named.get(x.get("reference", "")) for x in r.get("result", [])]
else:
mine = {ref, *(k for k, v in named.items() if v is r)}
results = [o for o in sent.values() if o["resourceType"] == "Observation"
and (o.get("encounter") or {}).get("reference") in mine] # fmt: skip
evidence = {}
for o in filter(None, results):
if o.get("resourceType") != "Observation" or o.get("status") == "entered-in-error":
continue
if o.get("subject") and subject(o) is not subject(r):
continue
for coding in _codings(o.get("code")):
name = _translated(maps, coding, FIELD) or ""
study, _, field = name.partition(".")
if study == entity and field in spec.fields:
# of a preliminary report or value, only what the sample itself says
unfinished = pending or o.get("status") == "preliminary"
if unfinished and spec.fields[field].event != root_name:
break
row[field] = _value(o, spec.fields[field], maps)
clinical = (
o.get("effectiveDateTime")
or o.get("effectiveInstant")
or (o.get("effectivePeriod") or {}).get("end")
or start
)
available = (
o.get("issued") or release if o.get("status") in FINAL_RESULTS else None
)
evidence[field] = _evidence(
f"{sender}|Observation/{o['id']}", clinical, available
)
break
if evidence:
row[FIELD_EVIDENCE] = json.dumps(evidence)
out.append(row)
return out
+13 -3
View File
@@ -86,12 +86,21 @@ def _moment(value) -> datetime | None:
return found if found.tzinfo else found.replace(tzinfo=UTC)
def age_years(birth, on: date) -> int | None:
"""Completed years on a date (dbt's macro `age_years`)."""
born = as_day(birth)
return (
None
if born is None
else on.year - born.year - ((on.month, on.day) < (born.month, born.day))
)
def age_group(birth, at: date, groups: list[tuple[int, int]]) -> str:
"""`low-high` of the group her age at `at` falls in, or below/above them all."""
birth = as_day(birth)
if birth is None:
age = age_years(birth, at)
if age is None:
return NO_DATA
age = at.year - birth.year - ((at.month, at.day) < (birth.month, birth.day))
for low, high in groups:
if low <= age <= high:
return f"{low}-{high}"
@@ -437,6 +446,7 @@ class Measure:
# The same by the event cutoff: a date column -> the columns it dates.
dated: dict[str, tuple[str, ...]] = field(default_factory=dict)
description: str | None = None
references: tuple[dict, ...] = () # FHIR RelatedArtifact bibliographic sources
def evaluate(
+11
View File
@@ -7,6 +7,8 @@ TITLES: dict[str, str] = {
"cacu.cancer_pim": "Riesgo de cáncer en vigilancia",
"cacu.cin2_pim_post_colposcopy": "Riesgo de LIEAG+ tras colposcopía",
"cacu.cin2_pim_post_treatment": "Riesgo de LIEAG+ tras tratamiento",
"cacu.cin3_pim": "Riesgo de CIN 3+ en vigilancia",
"cacu.cin3_pim_post_colposcopy": "Riesgo de CIN 3+ tras colposcopía",
"cacu.survival": "Supervivencia",
"cama.survival": "Supervivencia",
"cama.recurrence": "Recurrencia",
@@ -20,6 +22,15 @@ TITLES: dict[str, str] = {
"tea.eeg-ados2": "Relación del EEG con el ADOS-2",
}
# Trained and scored to test and develop, compared in Gobernanza: never a patient's risk.
DEVELOPMENT = frozenset({"cacu.cin2_logistic", "cacu.cin2_firth_development"})
# Kept but neither trained or scored by default nor shown: out of scope for now, or (CIN3+)
# waiting for data that tell severe dysplasia from moderate.
HIDDEN = frozenset(
{"cacu.cin2_pim_post_treatment", "cacu.cin3_pim", "cacu.cin3_pim_post_colposcopy"}
)
def title(model: str) -> str:
"""`model` (`<domain>.<name>`) as the pages name it."""
+1
View File
@@ -358,6 +358,7 @@ class Pipeline(BaseModel):
RECORD = "_record" # the source row every row comes from (hash of that row)
HELD = "_held" # why a row may not reach silver (list of reasons) or None
QUOTES = "_quotes" # what text each LLM value was read from
FIELD_EVIDENCE = "_field_evidence" # source dates and reference for individual values
def matches(node: Route, row: dict[str, Any]) -> bool:
+56
View File
@@ -0,0 +1,56 @@
"""Versioned, source-preserving representation of published risk table rows.
This module represents source data; it does not infer patient variables or compare models.
"""
FORMAT_VERSION = "1.0.0"
def source_estimate(
*,
outcome: str,
horizon_years: int,
value: float | None,
unit: str,
file: str,
sheet: str,
row: int,
lower: float | None = None,
upper: float | None = None,
confidence_level: float | None = None,
confidence_method: str | None = None,
) -> dict:
"""Represent one explicit workbook estimate; callers must identify its source unit."""
if outcome not in {"CIN2+", "CIN3+", "cancer"}:
raise ValueError("unsupported outcome")
if unit not in {"fraction", "percent"}:
raise ValueError("unit must be fraction or percent")
scale = 100 if unit == "percent" else 1
def probability(number):
return None if number is None else number / scale
interval = None
if lower is not None or upper is not None:
interval = {
"lower": probability(lower),
"upper": probability(upper),
"level": confidence_level,
"method": confidence_method,
}
return {
"outcome": outcome,
"horizon_years": horizon_years,
"measure": "probability",
"value": probability(value),
"confidence_interval": interval,
"source": {
"file": file,
"sheet": sheet,
"row": row,
"unit": unit,
"value": value,
"lower": lower,
"upper": upper,
},
}
+1
View File
@@ -0,0 +1 @@
"""Reading the NCI's published workbooks without a spreadsheet library."""
+48
View File
@@ -0,0 +1,48 @@
"""The cells of an .xlsx file (stdlib only)."""
import re
import zipfile
from pathlib import Path
from xml.etree import ElementTree as ET
NS = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}"
REL = "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"
def _column(reference: str) -> int:
number = 0
for letter in re.match(r"[A-Z]+", reference).group():
number = number * 26 + ord(letter) - ord("A") + 1
return number
def _sheets(path: Path):
"""Each sheet's name and rows: (row number, {column number: text})."""
with zipfile.ZipFile(path) as book:
shared = []
if "xl/sharedStrings.xml" in book.namelist():
shared = ["".join(t.text or "" for t in item.iter(f"{NS}t"))
for item in ET.fromstring(book.read("xl/sharedStrings.xml"))] # fmt: skip
targets = {r.get("Id"): r.get("Target")
for r in ET.fromstring(book.read("xl/_rels/workbook.xml.rels"))} # fmt: skip
for sheet in ET.fromstring(book.read("xl/workbook.xml")).iter(f"{NS}sheet"):
target = targets[sheet.get(REL)].lstrip("/").removeprefix("xl/")
rows = []
root = ET.fromstring(book.read(f"xl/{target}"))
for row in root.iter(f"{NS}row"):
cells = {}
for cell in row.findall(f"{NS}c"):
value = cell.find(f"{NS}v")
if value is None:
text = "".join(t.text or "" for t in cell.iter(f"{NS}t"))
elif cell.get("t") == "s":
text = shared[int(value.text)]
else:
text = value.text
if text and text.strip():
cells[_column(cell.get("r"))] = text.strip()
if cells:
rows.append((int(row.get("r")), cells))
yield sheet.get("name"), rows
+9 -1
View File
@@ -7,9 +7,17 @@ RUN apt-get update \
COPY --from=ghcr.io/astral-sh/uv:0.12.21 /uv /bin/uv
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PROJECT_ENVIRONMENT=/venv PATH=/venv/bin:$PATH
WORKDIR /app
COPY . .
# Optional extras a machine opts into (`--extra dask` where a Dask cluster runs the batches).
ARG EXTRAS=""
# The dependencies first, from the manifests alone: a code change reuses their layer.
COPY pyproject.toml uv.lock ./
COPY Core/pyproject.toml Core/
COPY Persistance/pyproject.toml Persistance/
COPY models/pyproject.toml models/
COPY WebApi/pyproject.toml WebApi/
COPY synthetic/pyproject.toml synthetic/
RUN uv sync --frozen --no-dev --no-install-workspace $EXTRAS
COPY . .
RUN uv sync --frozen --no-dev $EXTRAS
ENV ISSSTELEON_DATA=/data DAGSTER_HOME=/data/dagster DLT_DATA_DIR=/data/dlt
+13
View File
@@ -3,6 +3,7 @@ version: "0.0.0"
profile: isssteleon
model-paths: ["models"]
macro-paths: ["macros"]
seed-paths: ["seeds"]
target-path: "target"
models:
isssteleon:
@@ -12,6 +13,18 @@ models:
gold:
+schema: gold
+materialized: table
seeds:
isssteleon:
nci: # published reference tables, generated by tools/nci_seeds.py
+schema: gold
+full_refresh: true # a new column recreates the table instead of failing
nci_risk_row:
+column_types: {row_id: text, previous_two: text, history: text, hpv: text,
cytology: text, referral: text, biopsy: text, pre_colposcopy: text,
post_colposcopy_history: text, biopsy_before_treatment: text,
book: text, sheet: text, source_sha256: text}
nci_risk_estimate:
+column_types: {row_id: text, risk: float, risk_percent: float, lower: float, upper: float}
on-run-start:
- "{% if target.type == 'sqlite' %}PRAGMA silver.journal_mode=WAL{% endif %}"
- "{% if target.type == 'sqlite' %}PRAGMA gold.journal_mode=WAL{% endif %}"
+13
View File
@@ -0,0 +1,13 @@
{#
A sample's screening: subsequent when she was past a colposcopy or a treatment, or her form
says she was screened before; initial when it says never; null (unknown) when it says nothing.
#}
{% macro cacu_detection(sample, follow_up) -%}
case
when {{ sample }}.sample_date is null then null
when {{ follow_up }}.first_colposcopy < {{ sample }}.sample_date
or {{ follow_up }}.first_treatment < {{ sample }}.sample_date then 'subsequent'
when {{ sample }}.screening_history = 'never' then 'initial'
when {{ sample }}.screening_history is not null then 'subsequent'
end
{%- endmacro %}
@@ -0,0 +1,130 @@
{% macro cacu_prior_outcome(cohort) -%}
exists (
select 1 from {{ ref('cacu_events') }} as e
where e.person_id = {{ cohort }}.person_id and e.type = 'biopsy'
and e.date <= {{ as_of() }} and e.date < {{ cohort }}.index_date
and e.value_code in {{ sql_list(var('cacu').cin2_plus) }}
)
{%- endmacro %}
{% macro cacu_no_index_result(cohort) -%}
not exists (
select 1 from {{ ref('cacu_events') }} as e
where e.person_id = {{ cohort }}.person_id
and e.type in ('bethesda', 'glandular', 'hpv') and e.value_code is not null
and e.source_table = {{ cohort }}.source_table
and e.source_id = {{ cohort }}.source_id and e.date <= {{ as_of() }}
)
{%- endmacro %}
{% macro cacu_unreported_biopsy(cohort) -%}
{{ cohort }}.unreported > 0
{%- endmacro %}
{% macro cacu_outcome_by_index(cohort) -%}
exists (
select 1 from {{ ref('cacu_events') }} as e
where e.person_id = {{ cohort }}.person_id and e.type = 'biopsy'
and e.date <= {{ cohort }}.index_date and e.date <= {{ as_of() }}
and e.value_code in {{ sql_list(var('cacu').cin2_plus) }}
)
{%- endmacro %}
{% macro cacu_cancer_history(cohort) -%}
exists (
select 1 from {{ ref('cacu_events') }} as e
where e.person_id = {{ cohort }}.person_id and e.type = 'history'
and e.date <= {{ cohort }}.index_date and e.date <= {{ as_of() }}
)
{%- endmacro %}
{% macro cacu_prior_treatment(cohort) -%}
exists (
select 1 from {{ ref('cacu_events') }} as e
where e.person_id = {{ cohort }}.person_id and e.type = 'treatment'
and e.date <= {{ cohort }}.index_date and e.date <= {{ as_of() }}
)
{%- endmacro %}
{#
Her referral: the cytology gold.cacu_procedures links to her first colposcopy. High grade
needs no HPV; low grade (ASC-US, LSIL or NILM) counts only with a positive HPV.
#}
{% macro cacu_no_referral(cohort) -%}
not exists (
select 1 from {{ ref('cacu_procedures') }} as p
where p.person_id = {{ cohort }}.person_id and p.type = 'colposcopy'
and p.date = {{ cohort }}.colposcopy_date and p.sample_date is not null
)
{%- endmacro %}
{% macro cacu_referral_grade(cohort) -%}
{%- set k = var('cacu').kpnc_3 -%}
(select case
when max(case when r.result in {{ sql_list(k['High Grade']) }}
or r.glandular in {{ sql_list(k['High Grade']) }} then 1 else 0 end) = 1
then 'high'
when max(case when r.hpv and r.result in {{ sql_list(k['ASC-US/LSIL'] + k['NILM']) }}
then 1 else 0 end) = 1 then 'low'
end
from {{ ref('cacu_procedures') }} as p
join {{ ref('cervical_cytology') }} as r
on r.person_id = p.person_id and r.sample_date = p.sample_date
where p.person_id = {{ cohort }}.person_id and p.type = 'colposcopy'
and p.date = {{ cohort }}.colposcopy_date)
{%- endmacro %}
{% macro cacu_referral_not_graded(cohort) -%}
(not ({{ cacu_no_referral(cohort) }}) and {{ cacu_referral_grade(cohort) }} is null)
{%- endmacro %}
{% macro cacu_no_cotest(cohort) -%}
(not exists (
select 1 from {{ ref('cacu_events') }} as e
where e.person_id = {{ cohort }}.person_id and e.type = 'hpv'
and e.value_code is not null and e.source_table = {{ cohort }}.source_table
and e.source_id = {{ cohort }}.source_id and e.date <= {{ as_of() }}
) or not exists (
select 1 from {{ ref('cacu_events') }} as e
where e.person_id = {{ cohort }}.person_id and e.type in ('bethesda', 'glandular')
and e.value_code is not null and e.source_table = {{ cohort }}.source_table
and e.source_id = {{ cohort }}.source_id and e.date <= {{ as_of() }}
))
{%- endmacro %}
{% macro cacu_no_pretreatment_biopsy(cohort) -%}
not exists (
select 1 from {{ ref('cacu_events') }} as e
where e.person_id = {{ cohort }}.person_id and e.type = 'biopsy'
and e.value_code is not null and e.date <= {{ cohort }}.treatment_date
and e.date <= {{ as_of() }}
and {{ days_between('e.date', cohort ~ '.treatment_date') }}
<= {{ var('cacu').post_treatment_lookback_days }}
)
{%- endmacro %}
{% macro cacu_outcome_before_index(cohort) -%}
exists (
select 1 from {{ ref('cacu_events') }} as e
where e.person_id = {{ cohort }}.person_id and e.type = 'biopsy'
and e.date > {{ cohort }}.treatment_date and e.date < {{ cohort }}.index_date
and e.date <= {{ as_of() }}
and e.value_code in {{ sql_list(var('cacu').cin2_plus) }}
)
{%- endmacro %}
{% macro cacu_no_birth_date(cohort) -%}
not exists (
select 1 from {{ ref('cacu_events') }} as e
where e.person_id = {{ cohort }}.person_id and e.type = 'birth'
and e.date <= {{ as_of() }}
)
{%- endmacro %}
{% macro cacu_died_by_index(cohort) -%}
exists (
select 1 from {{ ref('cacu_events') }} as e
where e.person_id = {{ cohort }}.person_id and e.type = 'death'
and e.date <= {{ cohort }}.index_date and e.date <= {{ as_of() }}
)
{%- endmacro %}
@@ -0,0 +1,43 @@
{% macro cacu_hysterectomy_exam(event) -%}
{{ event }}.type = 'gynecologic_condition'
and {{ event }}.value_code = 'hysterectomy'
and {{ event }}.source_table = 'cervical_cytology'
{%- endmacro %}
{% macro cacu_hysterectomy_by_index(cohort) -%}
exists (
select 1 from {{ ref('cacu_events') }} as exam
where exam.person_id = {{ cohort }}.person_id
and exam.evidence_date < {{ cohort }}.index_date
and {{ cacu_available_by_index('exam', cohort ~ '.index_date') }}
and {{ cacu_hysterectomy_exam('exam') }}
)
{%- endmacro %}
{% macro cacu_available_by_index(evidence, index_date) -%}
{{ return(adapter.dispatch('cacu_available_by_index', 'isssteleon')(evidence, index_date)) }}
{%- endmacro %}
{% macro default__cacu_available_by_index(evidence, index_date) -%}
substr(cast({{ evidence }}.source_available_at as {{ dbt.type_string() }}), 1, 10)
<= substr(cast({{ index_date }} as {{ dbt.type_string() }}), 1, 10)
{%- endmacro %}
{% macro sqlserver__cacu_available_by_index(evidence, index_date) -%}
substring(cast({{ evidence }}.source_available_at as {{ dbt.type_string() }}), 1, 10)
<= substring(cast({{ index_date }} as {{ dbt.type_string() }}), 1, 10)
{%- endmacro %}
{% macro cacu_common_exclusion_cases(cohort) -%}
when {{ cacu_hysterectomy_by_index(cohort) }} then 'hysterectomy'
when {{ cacu_under_18_by_index(cohort) }} then 'under_18'
{%- endmacro %}
{% macro cacu_under_18_by_index(cohort) -%}
exists (
select 1 from {{ ref('cacu_events') }} as birth
where birth.person_id = {{ cohort }}.person_id and birth.type = 'birth'
and birth.date <= {{ cohort }}.index_date
and {{ age_years('birth.date', cohort ~ '.index_date') }} < 18
)
{%- endmacro %}
@@ -0,0 +1,69 @@
{#
Per sample, what the other books ask of her past: the second visit and the master table's
history.
#}
{% macro cacu_nci_book_facts_ctes() -%}
-- her one earlier sample, when the sample is her second visit
nci_previous as (
select s.person_id, s.sample_date,
max(case when p.valid = 1 and p.report_date <= s.sample_date then 1 else 0 end)
as available,
max(case when p.hpv is null then 1 else 0 end) as no_hpv,
max(case when p.hpv = false and (p.hpv_16 = true or p.hpv_18 = true)
then 1 else 0 end) as contradictory
from nci_sample as s
join {{ ref('cacu_samples') }} as p
on p.person_id = s.person_id and p.sample_date = s.previous_sample_date
where s.visit_number = 2
group by s.person_id, s.sample_date
),
-- the master table: a CIN2+ already reported, and her earlier tests with HPV known by the
-- sample, the latest first
nci_cin2 as (
select distinct s.person_id, s.sample_date
from nci_sample as s
join {{ ref('cacu_procedures') }} as b
on b.type = 'biopsy' and b.person_id = s.person_id and b.report_date <= s.sample_date
and b.histology in {{ sql_list(var('cacu').cin2_plus) }}
),
nci_tests as (
select s.person_id, s.sample_date, t.sample_date as tested,
case when t.hpv = true or coalesce(t.finding, '') <> 'NILM' then 1 else 0 end
as abnormal,
row_number() over (partition by s.person_id, s.sample_date
order by t.sample_date desc) as n
from nci_sample as s
join {{ ref('cacu_samples') }} as t
on t.person_id = s.person_id and t.sample_date < s.sample_date
and t.report_date <= s.sample_date and t.valid = 1 and t.hpv is not null
),
nci_history as (
select l.person_id, l.sample_date,
{{ days_between('l.tested', 'l.sample_date') }} as last_age,
l.abnormal as last_abnormal,
case when p.abnormal = 1
and {{ days_between('p.tested', 'l.tested') }} <= {{ var('cacu').nci_history_days }}
then 1 else 0 end as earlier_abnormal
from nci_tests as l
left join nci_tests as p
on p.person_id = l.person_id and p.sample_date = l.sample_date and p.n = 2
where l.n = 1
),
nci_book_facts as (
select a.*, p.available, p.no_hpv as previous_no_hpv,
p.contradictory as previous_contradictory,
case when c.person_id is null then 0 else 1 end as cin2_before,
h.last_age, h.last_abnormal, h.earlier_abnormal
from nci_aged as a
left join nci_cin2 as c
on c.person_id = a.person_id and c.sample_date = a.sample_date
left join nci_history as h
on h.person_id = a.person_id and h.sample_date = a.sample_date
left join nci_previous as p
on p.person_id = a.person_id and p.sample_date = a.sample_date
),
{%- endmacro %}
+50
View File
@@ -0,0 +1,50 @@
{#
The requirements of each scenario (`nci_books`: one row per scenario, person, sample date and
requirement not met; a null criterion when it meets them all).
#}
{% macro cacu_nci_rules_ctes() -%}
-- every book needs these of the sample (nci_sample); the others, what a few books add
{% set scenarios = [
('nci_sample', [
('missing_or_ineligible_age', 'age is null'),
('age_outside_25_65',
'age < ' ~ var('cacu').nci_age_range[0] ~ ' or age > ' ~ var('cacu').nci_age_range[1]),
('missing_or_ambiguous_index_sample', 'samples <> 1'),
('hysterectomy_declared', 'hysterectomy = 1'),
('missing_hpv', 'no_hpv = 1'),
('contradictory_hpv', 'contradictory = 1'),
]),
('nci_master', [
('colposcopy_or_treatment_before', 'done_by_sample > 0'),
('registered_cin2_plus_before', 'cin2_before = 1'),
('hysterectomy_declared', 'hysterectomy = 1'),
('no_earlier_test_registered', 'last_age is null'),
('earlier_test_older_than_5_years', 'last_age > ' ~ var('cacu').nci_history_days),
('history_is_a_surveillance_scenario', 'last_abnormal = 1 or earlier_abnormal = 1'),
]),
('nci_second_visit', [
('prior_procedure_requires_other_scenario', 'procedures + treatments > 0'),
('missing_or_ambiguous_previous_visit', 'visit_number <> 2'),
('previous_result_not_available_by_index', 'available = 0'),
('contradictory_previous_hpv', 'previous_contradictory = 1'),
('missing_previous_hpv', 'previous_no_hpv = 1'),
]),
] %}
nci_books as (
{% for scenario, rules in scenarios %}
select '{{ scenario }}' as scenario, f.person_id, f.sample_date, r.criterion
from nci_book_facts as f
left join (
{% for criterion, broken in rules %}
select '{{ criterion }}' as criterion {% if not loop.last %}union all{% endif %}
{% endfor %}
) as r
on {% for criterion, broken in rules %}
{% if not loop.first %}or{% endif %} (r.criterion = '{{ criterion }}' and ({{ broken }}))
{% endfor %}
{% if not loop.last %}union all{% endif %}
{% endfor %}
union all
select 'nci_post_colposcopy', person_id, sample_date, criterion from nci_post_colposcopy
)
{%- endmacro %}
+127
View File
@@ -0,0 +1,127 @@
{#
What the NCI books require of a sample, decided in gold, as CTEs for cacu_eligibility, in
three macros: the sample and book 17 (this one), the facts the other books add
(cacu_nci_book_facts) and their rules (cacu_nci_rules). Which requirement the reference names
first, and looking the book's row up, stay in Python (core.cacu.risk_series).
#}
{% macro cacu_nci_sample_ctes() -%}
nci_sample as (
select person_id, sample_date, count(*) as samples,
max(birth_date) as birth_date,
max(case when hpv is null then 1 else 0 end) as no_hpv,
max(case when hpv = false and (hpv_16 = true or hpv_18 = true) then 1 else 0 end)
as contradictory,
max(hysterectomy_declared_by_sample) as hysterectomy,
max(treatments_by_sample) as treatments,
max(biopsies_pending) as pending,
max(biopsy_reports_before) as reports,
max(case when hpv = true and coalesce(hpv_16, false) = false
and (hpv_16 is null or hpv_18 is null) then 1 else 0 end) as no_genotypes,
max(case when hpv = true then 0 else 1 end) as not_positive,
max(visit_number) as visit_number,
max(previous_hpv_tests) as previous_hpv_tests,
max(colposcopies_by_sample + treatments_by_sample + biopsy_requests_by_sample)
as done_by_sample,
max(previous_sample_date) as previous_sample_date,
max(colposcopies_by_sample + biopsy_requests_by_sample) as procedures
from {{ ref('cacu_samples') }}
where valid = 1 and report_date <= {{ as_of() }}
group by person_id, sample_date
),
nci_aged as (
select s.*, {{ age_years('s.birth_date', 's.sample_date') }} as age from nci_sample as s
),
-- the biopsy reported before the sample, when it is the only one
nci_prior as (
select s.person_id, s.sample_date, b.date as request_date, b.report_date, b.histology,
b.sample_date as referral_date
from nci_sample as s
join {{ ref('cacu_procedures') }} as b
on b.type = 'biopsy' and b.person_id = s.person_id and b.report_date < s.sample_date
where s.reports = 1
),
-- grouped joins, not correlated subqueries: older planners repeat those per row
nci_referrals as (
select p.person_id, p.sample_date, count(*) as referrals
from nci_prior as p
join {{ ref('cacu_samples') }} as r
on r.person_id = p.person_id and r.sample_date = p.referral_date
and r.valid = 1 and r.report_date <= p.request_date
group by p.person_id, p.sample_date
),
nci_colposcopies as (
select distinct p.person_id, p.sample_date
from nci_prior as p
join {{ ref('cacu_events') }} as e
on e.person_id = p.person_id and e.type = 'colposcopy' and e.date = p.request_date
),
nci_visits as (
select distinct p.person_id, p.sample_date
from nci_prior as p
join {{ ref('cacu_samples') }} as v
on v.person_id = p.person_id and v.sample_date > p.report_date
and v.sample_date < p.sample_date
),
nci_linked as (
select p.person_id, p.sample_date, p.request_date, p.report_date, p.histology,
p.referral_date, coalesce(r.referrals, 0) as referrals,
case when c.person_id is null then 0 else 1 end as colposcopy,
case when v.person_id is null then 0 else 1 end as visit_between
from nci_prior as p
left join nci_referrals as r
on r.person_id = p.person_id and r.sample_date = p.sample_date
left join nci_colposcopies as c
on c.person_id = p.person_id and c.sample_date = p.sample_date
left join nci_visits as v
on v.person_id = p.person_id and v.sample_date = p.sample_date
),
nci_facts as (
select a.*, l.request_date, l.report_date, l.histology, l.referral_date, l.referrals,
l.colposcopy, l.visit_between
from nci_aged as a
left join nci_linked as l on l.person_id = a.person_id and l.sample_date = a.sample_date
),
{% set rules = [
('missing_or_ineligible_age', 'age is null'),
('age_outside_25_65',
'age < ' ~ var('cacu').nci_age_range[0] ~ ' or age > ' ~ var('cacu').nci_age_range[1]),
('missing_or_ambiguous_index_sample', 'samples <> 1'),
('hysterectomy_declared', 'hysterectomy = 1'),
('missing_hpv', 'no_hpv = 1'),
('contradictory_hpv', 'contradictory = 1'),
('treatment_before_index', 'treatments > 0'),
('prior_biopsy_pending_at_index', 'pending > 0'),
('no_prior_biopsy_report', 'reports = 0'),
('multiple_prior_biopsy_reports', 'reports > 1'),
('intermediate_visit_not_supported', 'visit_between = 1'),
('biopsy_not_demonstrably_below_cin2',
"reports = 1 and coalesce(histology, '') not in ('normal', 'LSIL')"),
('referral_link_not_recorded', 'reports = 1 and referral_date is null'),
('linked_referral_not_available', 'referral_date is not null and referrals = 0'),
('multiple_linked_referral_samples', 'referrals > 1'),
('colposcopy_not_documented', 'referral_date is not null and colposcopy = 0'),
('invalid_biopsy_chronology',
'referral_date is not null and not (referral_date < request_date and request_date <= report_date)'),
] %}
-- one pass over the facts: each sample joins the requirements it does not meet
nci_post_colposcopy as (
select f.person_id, f.sample_date, r.criterion
from nci_facts as f
left join (
{% for criterion, broken in rules %}
select '{{ criterion }}' as criterion {% if not loop.last %}union all{% endif %}
{% endfor %}
) as r
on {% for criterion, broken in rules %}
{% if not loop.first %}or{% endif %} (r.criterion = '{{ criterion }}' and ({{ broken }}))
{% endfor %}
),
{%- endmacro %}
@@ -0,0 +1,101 @@
{% macro cacu_post_colposcopy_index(visit, require_biopsy_report=true) %}
{% set p = var('cacu') %}
with known as (
select * from {{ ref('cacu_events') }} where date <= {{ as_of() }}
),
colposcopies as (
select
person_id, date,
row_number() over (partition by person_id order by date, source_table, source_id) as n
from known
where type = 'colposcopy'
),
first_colposcopy as (
select person_id, date as colposcopy_date from colposcopies where n = 1
),
orders as (
select distinct o.person_id, o.source_table, o.source_id
from known as o
join first_colposcopy as f on f.person_id = o.person_id and o.date = f.colposcopy_date
where o.type = 'biopsy_order'
),
reports as (
select r.person_id, r.date, r.source_table, r.source_id
from known as r
join orders as o
on o.person_id = r.person_id and o.source_table = r.source_table and o.source_id = r.source_id
where r.type = 'biopsy'
),
episode as (
select
f.person_id,
f.colposcopy_date,
coalesce((select max(r.date) from reports as r where r.person_id = f.person_id),
f.colposcopy_date) as result_date
{% if require_biopsy_report %}
, (select count(*) from orders as o
where o.person_id = f.person_id and not exists (
select 1 from reports as r
where r.person_id = o.person_id and r.source_table = o.source_table
and r.source_id = o.source_id)) as unreported
{% endif %}
from first_colposcopy as f
),
closed as (
select
ep.*,
(select min(c.date) from known as c
where c.person_id = ep.person_id and c.type = 'colposcopy'
and c.date > ep.result_date) as closing_date
from episode as ep
),
visits as (
select
s.person_id, s.date, s.source_table, s.source_id,
row_number() over (partition by s.person_id order by s.date, s.source_id) as n
from known as s
join closed as ep on ep.person_id = s.person_id
where s.type = 'cytology' and s.date > ep.result_date
and (ep.closing_date is null or s.date < ep.closing_date)
),
indexed as (
select ep.*, v.date as index_date, v.source_table, v.source_id,
prior.date as previous_date, prior.source_table as previous_source_table,
prior.source_id as previous_source_id
from closed as ep
join visits as v on v.person_id = ep.person_id and v.n = {{ visit }}
left join visits as prior on prior.person_id = v.person_id and prior.n = v.n - 1
where v.date >= '{{ p.recruitment[0] }}' and v.date < '{{ p.recruitment[1] }}'
)
select
i.person_id,
'post_colposcopy' as scenario,
i.index_date,
i.source_table, i.source_id,
i.previous_date, i.previous_source_table, i.previous_source_id,
i.source_table as index_source_table, i.source_id as index_source_id,
i.colposcopy_date,
{% if require_biopsy_report %}i.unreported{% else %}0{% endif %} as unreported,
case
{{ cacu_common_exclusion_cases('i') }}
{% if require_biopsy_report %}
when {{ cacu_unreported_biopsy('i') }} then 'unreported_biopsy'
{% endif %}
when {{ cacu_outcome_by_index('i') }} then 'outcome_by_index'
when {{ cacu_cancer_history('i') }} then 'cancer_history'
when {{ cacu_prior_treatment('i') }} then 'prior_treatment'
when {{ cacu_no_referral('i') }} then 'no_referral'
when {{ cacu_referral_not_graded('i') }} then 'referral_not_graded'
when {{ cacu_no_cotest('i') }} then 'no_cotest'
end as excluded_by
from indexed as i
{% endmacro %}
@@ -0,0 +1,46 @@
{% macro cacu_surveillance_index(visit=1, before_referral=false) %}
{% set p = var('cacu') %}
with known as (
select * from {{ ref('cacu_events') }} where date <= {{ as_of() }}
),
samples as (
select
person_id, date, source_table, source_id,
row_number() over (partition by person_id order by date, source_id) as n
from known as s
where type = 'cytology'
{% if before_referral %}
and not exists (
select 1 from known as e
where e.person_id = s.person_id and e.type in ('colposcopy', 'biopsy')
and e.date <= s.date
)
{% endif %}
),
indexed as (
select v.person_id, v.date as index_date, v.source_table, v.source_id,
prior.date as previous_date, prior.source_table as previous_source_table,
prior.source_id as previous_source_id
from samples as v
left join samples as prior on prior.person_id = v.person_id and prior.n = v.n - 1
where v.n = {{ visit }}
and v.date >= '{{ p.recruitment[0] }}' and v.date < '{{ p.recruitment[1] }}'
)
select
i.person_id,
'{{ "pre_colposcopy" if before_referral else "surveillance" }}' as scenario,
i.index_date,
i.source_table, i.source_id,
i.previous_date, i.previous_source_table, i.previous_source_id,
i.source_table as index_source_table, i.source_id as index_source_id,
cast(null as date) as colposcopy_date, cast(0 as integer) as unreported,
case
{{ cacu_common_exclusion_cases('i') }}
when {{ cacu_prior_outcome('i') }} then 'prior_outcome'
when {{ cacu_no_index_result('i') }} then 'no_index_result'
end as excluded_by
from indexed as i
{% endmacro %}
@@ -0,0 +1,5 @@
{# A valid cytology: a reported result, of satisfactory (or unknown) adequacy. #}
{% macro cacu_valid_cytology(c) -%}
(({{ c }}.result is not null or {{ c }}.glandular is not null) and {{ c }}.report_date is not null
and coalesce({{ c }}.adequacy, '') <> 'unsatisfactory')
{%- endmacro %}
+9
View File
@@ -15,3 +15,12 @@
{% macro as_of() -%}
'{{ var("as_of", run_started_at.strftime("%Y-%m-%d")) }}'
{%- endmacro %}
{# Completed years on a date; the ISO month and day determine whether the birthday has passed. #}
{% macro age_years(birth, on_date) -%}
(cast(substr(cast({{ on_date }} as {{ dbt.type_string() }}), 1, 4) as integer)
- cast(substr(cast({{ birth }} as {{ dbt.type_string() }}), 1, 4) as integer)
- case when substr(cast({{ on_date }} as {{ dbt.type_string() }}), 6, 5)
< substr(cast({{ birth }} as {{ dbt.type_string() }}), 6, 5)
then 1 else 0 end)
{%- endmacro %}
@@ -4,7 +4,7 @@
end exclusive), up to the as-of date. Out (`excluded_by`): no birth date (no age at the
index), a death on or before the index.
#}
{% macro first_biopsy_cohort(events, grades, recruitment) %}
{% macro first_biopsy_cohort(events, grades, recruitment, cacu_rules=false) %}
with timeline as (
select * from {{ ref(events) }} where date <= {{ as_of() }}
),
@@ -27,8 +27,13 @@ death as (
select
i.person_id, i.index_date,
case
{% if cacu_rules %}
when {{ cacu_no_birth_date('i') }} then 'no_birth_date'
when {{ cacu_died_by_index('i') }} then 'died_by_index'
{% else %}
when b.person_id is null then 'no_birth_date'
when d.date <= i.index_date then 'died_by_index'
{% endif %}
end as excluded_by
from indexed as i
left join birth as b on b.person_id = i.person_id
+9 -2
View File
@@ -2,10 +2,11 @@
One study, wide: one row per study instance (person and the study's key), one column per
field of the catalog (core.catalog), from the long `silver.observation`. `known_at` is when
anything of the instance was first known, `<event>_known_at` when its event was (a report can
arrive loads after its sample). A subquery, for
arrive loads after its sample). Opt-in `timestamped_fields` expose source dates,
reference and ingestion time of the specific value. A subquery, for
`from {{ pivot('cervical_cytology') }} as c`, or a whole model.
#}
{% macro pivot(study) -%}
{% macro pivot(study, timestamped_fields=[]) -%}
{%- set s = var('catalog')[study] -%}
(
select
@@ -25,6 +26,12 @@
{%- set mine = s.fields | dictsort | selectattr('1.event', 'equalto', event) | map('first') | list %}
min(case when field in {{ sql_list(mine) }} then known_at end) as {{ event }}_known_at,
{%- endfor %}
{%- for field in timestamped_fields %}
min(case when field = '{{ field }}' then field_known_at end) as {{ field }}_known_at,
{%- for column in ['source_clinical_date', 'source_available_at', 'source_ref'] %}
max(case when field = '{{ field }}' then {{ column }} end) as {{ field }}_{{ column }},
{%- endfor %}
{%- endfor %}
max(rows_merged) as rows_merged
from {{ ref('observation') }}
where study = '{{ study }}'
+49
View File
@@ -1,7 +1,56 @@
version: 2
models:
- name: cacu_eligibility
description: >-
One row per indexed candidate and detected exclusion criterion. Eligible candidates
have a null criterion; multiple common criteria produce multiple rows. The scenario
nci_post_colposcopy has one candidate per valid reported cytology sample (what NCI
book 17 requires of it); readers get it only by naming the scenario.
columns:
- name: scenario
description: Cohort scenario at the indexed visit.
- name: person_id
description: Stable patient identifier.
- name: index_date
description: Clinical date used as the visit cutoff.
- name: index_sample_id
description: Sample key when the candidate is based on a visit feature row.
- name: criterion
description: Exclusion criterion; null means the candidate is eligible.
- name: eligible
description: Whether the candidate has no detected exclusion criteria.
- name: cacu_samples
description: One row per cytology sample.
columns:
- name: visit_number
description: "Ordinal of this sample among the patient's cytology samples."
- name: previous_sample_date
description: "Date of the sample before this one."
- name: previous_hpv_tests
description: "Earlier samples with an HPV result; a missing HPV is not a test."
- name: visit_since_colposcopy
description: "Ordinal of this sample after the first colposcopy; null if not after it."
- name: visit_since_treatment
description: "Ordinal of this sample after the first treatment; null if not after it."
- name: colposcopies_by_sample
description: "Colposcopy days up to and including the sample day."
- name: treatments_by_sample
description: "Treatment days up to and including the sample day."
- name: biopsy_requests_by_sample
description: "Biopsies requested up to and including the sample day."
- name: biopsy_reports_before
description: "Biopsies reported before the sample day."
- name: biopsies_pending
description: "Biopsies requested before the sample day and not reported before it."
- name: hysterectomy_declared_by_sample
description: "1 when a cytology up to the sample day declared hysterectomy."
- name: cacu_follow_up
columns:
- name: person_id
data_tests: [unique, not_null]
- name: treated_biopsy_request_date
description: >-
Request date of the biopsy her first treatment answers: the last one with a result
reported in the post_treatment_lookback_days up to that treatment, that day included.
Null when there is none. Read by the NCI post-treatment books.
@@ -0,0 +1,24 @@
{#
Beside each eligible member of the cohorts whose models stratify or need HPV: what is known
of her screening at the index, and whether the model can evaluate her. Nobody is excluded
here: without an HPV result at the index she stays in the cohort and is not evaluated.
#}
with members as (
{%- for scenario in ['surveillance', 'post_colposcopy', 'post_treatment'] %}
{% if not loop.first %}union all{% endif %}
select '{{ scenario }}' as scenario, person_id, index_date, index_source_table, index_source_id
from {{ ref('cacu_cohort_' ~ scenario) }}
where excluded_by is null
{%- endfor %}
)
select
m.scenario, m.person_id, m.index_date, s.screening_history, s.detection,
case when exists (
select 1 from {{ ref('cacu_events') }} as e
where e.person_id = m.person_id and e.type = 'hpv' and e.value_code is not null
and e.source_table = m.index_source_table and e.source_id = m.index_source_id
) then 1 else 0 end as index_hpv_recorded
from members as m
left join {{ ref('cacu_samples') }} as s
on s.person_id = m.person_id and s.sample_date = m.index_date
@@ -6,119 +6,12 @@
order: a biopsy ordered that day without a report (unreported_biopsy); an outcome biopsy
up to the index (outcome_by_index); a cervical cancer history (cancer_history); a
hysterectomy (hysterectomy); a treatment (prior_treatment), each up to the index; no
cytology or HPV result in the REFERRAL_LOOKBACK_DAYS before the colposcopy (no_referral);
referral cytology linked to the colposcopy (no_referral); a low grade one without a
positive HPV (referral_not_graded);
an index sample without both a cytology and an HPV result (no_cotest).
#}
{% set p = var('cacu') %}
with known as (
select * from {{ ref('cacu_events') }} where date <= {{ as_of() }}
),
colposcopies as (
select
person_id, date,
row_number() over (partition by person_id order by date, source_table, source_id) as n
from known
where type = 'colposcopy'
),
first_colposcopy as (
select person_id, date as colposcopy_date from colposcopies where n = 1
),
orders as (
select distinct o.person_id, o.source_table, o.source_id
from known as o
join first_colposcopy as f on f.person_id = o.person_id and o.date = f.colposcopy_date
where o.type = 'biopsy_order'
),
reports as (
select r.person_id, r.date, r.source_table, r.source_id
from known as r
join orders as o
on o.person_id = r.person_id and o.source_table = r.source_table and o.source_id = r.source_id
where r.type = 'biopsy'
),
episode as (
select
f.person_id,
f.colposcopy_date,
coalesce((select max(r.date) from reports as r where r.person_id = f.person_id),
f.colposcopy_date) as result_date,
(select count(*) from orders as o
where o.person_id = f.person_id and not exists (
select 1 from reports as r
where r.person_id = o.person_id and r.source_table = o.source_table
and r.source_id = o.source_id)) as unreported
from first_colposcopy as f
),
closed as (
select
ep.*,
(select min(c.date) from known as c
where c.person_id = ep.person_id and c.type = 'colposcopy'
and c.date > ep.result_date) as closing_date
from episode as ep
),
visits as (
select
s.person_id, s.date, s.source_table, s.source_id,
row_number() over (partition by s.person_id order by s.date, s.source_id) as n
from known as s
join closed as ep on ep.person_id = s.person_id
where s.type = 'cytology' and s.date > ep.result_date
and (ep.closing_date is null or s.date < ep.closing_date)
),
indexed as (
select ep.*, v.date as index_date, v.source_table, v.source_id
from closed as ep
join visits as v on v.person_id = ep.person_id and v.n = {{ p.post_colposcopy_visit }}
where v.date >= '{{ p.recruitment[0] }}' and v.date < '{{ p.recruitment[1] }}'
)
select
i.person_id,
i.index_date,
case
when i.unreported > 0 then 'unreported_biopsy'
when exists (
select 1 from known as e
where e.person_id = i.person_id and e.type = 'biopsy' and e.date <= i.index_date
and e.value_code in {{ sql_list(p.cin2_plus) }}
) then 'outcome_by_index'
when exists (
select 1 from known as e
where e.person_id = i.person_id and e.type = 'history' and e.date <= i.index_date
) then 'cancer_history'
when exists (
select 1 from known as e
where e.person_id = i.person_id and e.type = 'note' and e.date <= i.index_date
and e.value_code in {{ sql_list(p.hysterectomy_icd10) }}
) then 'hysterectomy'
when exists (
select 1 from known as e
where e.person_id = i.person_id and e.type = 'treatment' and e.date <= i.index_date
) then 'prior_treatment'
when not exists (
select 1 from known as e
where e.person_id = i.person_id and e.type in ('bethesda', 'glandular', 'hpv')
and e.value_code is not null and e.date <= i.colposcopy_date
and {{ days_between('e.date', 'i.colposcopy_date') }} <= {{ p.referral_lookback_days }}
) then 'no_referral'
when not exists (
select 1 from known as e
where e.person_id = i.person_id and e.type = 'hpv' and e.value_code is not null
and e.source_table = i.source_table and e.source_id = i.source_id
) or not exists (
select 1 from known as e
where e.person_id = i.person_id and e.type in ('bethesda', 'glandular')
and e.value_code is not null
and e.source_table = i.source_table and e.source_id = i.source_id
) then 'no_cotest'
end as excluded_by
from indexed as i
select person_id, index_date, index_source_table, index_source_id, colposcopy_date,
unreported, excluded_by, {{ cacu_referral_grade('cohort') }} as referral_grade
from (
{{ cacu_post_colposcopy_index(var('cacu').post_colposcopy_visit) }}
) as cohort
@@ -36,24 +36,13 @@ indexed as (
select
i.person_id,
i.index_date,
i.source_table as index_source_table,
i.source_id as index_source_id,
i.treatment_date,
case
when not exists (
select 1 from known as e
where e.person_id = i.person_id and e.type = 'biopsy' and e.value_code is not null
and e.date <= i.treatment_date
and {{ days_between('e.date', 'i.treatment_date') }} <= {{ p.post_treatment_lookback_days }}
) then 'no_pretreatment_biopsy'
when exists (
select 1 from known as e
where e.person_id = i.person_id and e.type = 'biopsy'
and e.date > i.treatment_date and e.date < i.index_date
and e.value_code in {{ sql_list(p.cin2_plus) }}
) then 'outcome_before_index'
when not exists (
select 1 from known as e
where e.person_id = i.person_id and e.type in ('bethesda', 'glandular', 'hpv')
and e.source_table = i.source_table and e.source_id = i.source_id
and e.value_code is not null
) then 'no_index_result'
{{ cacu_common_exclusion_cases('i') }}
when {{ cacu_no_pretreatment_biopsy('i') }} then 'no_pretreatment_biopsy'
when {{ cacu_outcome_before_index('i') }} then 'outcome_before_index'
when {{ cacu_no_index_result('i') }} then 'no_index_result'
end as excluded_by
from indexed as i
@@ -3,39 +3,8 @@
the recruitment window. Out, in order: an outcome biopsy (CIN2+) before the index
(prior_outcome); an index sample with no cytology or HPV result (no_index_result).
#}
{% set p = var('cacu') %}
with known as (
select * from {{ ref('cacu_events') }} where date <= {{ as_of() }}
),
samples as (
select
person_id, date, source_table, source_id,
row_number() over (partition by person_id order by date, source_id) as n
from known
where type = 'cytology'
),
indexed as (
select person_id, date as index_date, source_table, source_id
from samples
where n = 1 and date >= '{{ p.recruitment[0] }}' and date < '{{ p.recruitment[1] }}'
)
select
i.person_id,
i.index_date,
case
when exists (
select 1 from known as e
where e.person_id = i.person_id and e.type = 'biopsy' and e.date < i.index_date
and e.value_code in {{ sql_list(p.cin2_plus) }}
) then 'prior_outcome'
when not exists (
select 1 from known as e
where e.person_id = i.person_id and e.type in ('bethesda', 'glandular', 'hpv')
and e.source_table = i.source_table and e.source_id = i.source_id
and e.value_code is not null
) then 'no_index_result'
end as excluded_by
from indexed as i
select person_id, index_date, source_table as index_source_table,
source_id as index_source_id, excluded_by
from (
{{ cacu_surveillance_index() }}
) as cohort
@@ -1,3 +1,8 @@
{# Survival: indexed at the first biopsy reported as carcinoma or carcinoma in situ (core.cacu CASE). #}
{# Survival: indexed at the first biopsy reported as invasive carcinoma (core.cacu CASE). #}
{% set p = var('cacu') %}
{{ first_biopsy_cohort('cacu_events', p.case, p.recruitment) }}
select i.person_id, i.index_date,
case {{ cacu_common_exclusion_cases('i') }}
else i.excluded_by end as excluded_by
from (
{{ first_biopsy_cohort('cacu_events', p.case, p.recruitment, cacu_rules=true) }}
) as i
@@ -0,0 +1,148 @@
{# One row per indexed candidate and every applicable exclusion criterion. #}
with candidates as (
select 'surveillance' as scenario, person_id, index_date,
cast(null as {{ dbt.type_string() }}) as index_sample_id,
index_source_table as source_table, index_source_id as source_id,
cast(null as date) as colposcopy_date, cast(null as date) as treatment_date,
cast(0 as integer) as unreported
from {{ ref('cacu_cohort_surveillance') }}
union all
select 'pre_colposcopy', person_id, index_date, index_sample_id,
'cervical_cytology', index_sample_id,
colposcopy_date, cast(null as date), cast(0 as integer)
from {{ ref('cacu_second_visit_features') }} where scenario = 'pre_colposcopy'
union all
select 'post_colposcopy', person_id, index_date,
index_source_id, index_source_table, index_source_id,
colposcopy_date, cast(null as date), unreported
from {{ ref('cacu_cohort_post_colposcopy') }}
union all
select 'post_colposcopy_second_visit', person_id, index_date, index_sample_id,
'cervical_cytology', index_sample_id,
colposcopy_date, cast(null as date), cast(0 as integer)
from {{ ref('cacu_second_visit_features') }} where scenario = 'post_colposcopy'
union all
select 'post_treatment', person_id, index_date,
index_source_id, index_source_table, index_source_id,
cast(null as date), treatment_date, cast(0 as integer)
from {{ ref('cacu_cohort_post_treatment') }}
union all
select 'survival', person_id, index_date,
cast(null as {{ dbt.type_string() }}), cast(null as {{ dbt.type_string() }}),
cast(null as {{ dbt.type_string() }}), cast(null as date), cast(null as date),
cast(0 as integer)
from {{ ref('cacu_cohort_survival') }}
),
reasons as (
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'hysterectomy' as criterion
from candidates as c where {{ cacu_hysterectomy_by_index('c') }}
union all
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'under_18'
from candidates as c where {{ cacu_under_18_by_index('c') }}
union all
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'prior_outcome'
from candidates as c
where c.scenario in ('surveillance', 'pre_colposcopy')
and {{ cacu_prior_outcome('c') }}
union all
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'no_index_result'
from candidates as c
where c.scenario in ('surveillance', 'pre_colposcopy', 'post_treatment')
and {{ cacu_no_index_result('c') }}
union all
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'unreported_biopsy'
from candidates as c
where c.scenario = 'post_colposcopy' and {{ cacu_unreported_biopsy('c') }}
union all
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'outcome_by_index'
from candidates as c
where c.scenario in ('post_colposcopy', 'post_colposcopy_second_visit')
and {{ cacu_outcome_by_index('c') }}
union all
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'cancer_history'
from candidates as c
where c.scenario in ('post_colposcopy', 'post_colposcopy_second_visit')
and {{ cacu_cancer_history('c') }}
union all
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'prior_treatment'
from candidates as c
where c.scenario in ('post_colposcopy', 'post_colposcopy_second_visit')
and {{ cacu_prior_treatment('c') }}
union all
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'no_referral'
from candidates as c
where c.scenario in ('post_colposcopy', 'post_colposcopy_second_visit')
and {{ cacu_no_referral('c') }}
union all
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'referral_not_graded'
from candidates as c
where c.scenario in ('post_colposcopy', 'post_colposcopy_second_visit')
and {{ cacu_referral_not_graded('c') }}
union all
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'no_cotest'
from candidates as c
where c.scenario in ('post_colposcopy', 'post_colposcopy_second_visit')
and {{ cacu_no_cotest('c') }}
union all
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'no_pretreatment_biopsy'
from candidates as c
where c.scenario = 'post_treatment' and {{ cacu_no_pretreatment_biopsy('c') }}
union all
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'outcome_before_index'
from candidates as c
where c.scenario = 'post_treatment' and {{ cacu_outcome_before_index('c') }}
union all
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'no_birth_date'
from candidates as c where c.scenario = 'survival' and {{ cacu_no_birth_date('c') }}
union all
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'died_by_index'
from candidates as c where c.scenario = 'survival' and {{ cacu_died_by_index('c') }}
),
distinct_reasons as (
select distinct scenario, person_id, index_date, index_sample_id, criterion from reasons
),
{{ cacu_nci_sample_ctes() }}
{{ cacu_nci_book_facts_ctes() }}
{{ cacu_nci_rules_ctes() }}
select c.scenario, c.person_id, c.index_date, c.index_sample_id, r.criterion,
false as eligible
from candidates as c
join distinct_reasons as r
on r.scenario = c.scenario and r.person_id = c.person_id and r.index_date = c.index_date
and (r.index_sample_id = c.index_sample_id or
(r.index_sample_id is null and c.index_sample_id is null))
union all
select c.scenario, c.person_id, c.index_date, c.index_sample_id,
cast(null as {{ dbt.type_string() }}) as criterion, true as eligible
from candidates as c
where not exists (
select 1 from distinct_reasons as r
where r.scenario = c.scenario and r.person_id = c.person_id and r.index_date = c.index_date
and (r.index_sample_id = c.index_sample_id or
(r.index_sample_id is null and c.index_sample_id is null))
)
union all
-- the NCI reference's candidates are samples, not cohort members (macros cacu_nci_*)
select scenario, person_id, sample_date,
{{ dbt.concat(['person_id', "'|'", 'cast(sample_date as ' ~ dbt.type_string() ~ ')']) }},
criterion, case when criterion is null then true else false end as eligible
from nci_books
@@ -0,0 +1,10 @@
{# Independent evidence uses the timeline's columns for candidate eligibility queries. #}
select person_id, evidence_date as date, evidence_code_known_at as known_at,
evidence_type as type,
case when evidence_type = 'condition' then replace(evidence_code, '.', '')
else evidence_code end as value_code,
cast(null as {{ dbt.type_float() }}) as value_num,
'cacu_eligibility_evidence' as source_table, evidence_id as source_id,
evidence_date, evidence_code_source_available_at as source_available_at,
evidence_code_source_ref as source_ref
from {{ pivot('cacu_eligibility_evidence', timestamped_fields=['evidence_code']) }} as evidence
@@ -3,6 +3,8 @@
dated when they were reported; a cytology's results and a biopsy's order and report share
their source (`source_table`, `source_id`), so a model can tell which sample a result
belongs to.
For eligibility inputs, `evidence_date` and `source_available_at` preserve the source's
clinical and documentation times. `known_at` remains a platform ingestion timestamp.
Procedures silver has no record of are inferred from notes and biopsies (core.cacu):
- diagnosis: a note with a diagnosis ICD-10 by a diagnosing specialty;
@@ -25,7 +27,8 @@ biopsy as (
note as (
select
person_id, note_date, specialty, known_at,
person_id, note_date, specialty, known_at, icd10_known_at, icd10_source_clinical_date,
icd10_source_available_at, icd10_source_ref,
replace(icd10, '.', '') as icd10,
{{ plain_upper('reason') }} as reason,
{{ plain_upper('diagnosis_text') }} as diagnosis_text,
@@ -93,23 +96,50 @@ events as (
from {{ ref('death') }}
union all
select person_id, sample_date, known_at, 'cytology', adequacy, null,
select person_id, sample_date, known_at, 'cytology', null, null,
'cervical_cytology', cast(sample_date as {{ dbt.type_string() }})
from cytology
union all
select person_id, report_date, report_known_at, 'adequacy', adequacy, null,
'cervical_cytology', cast(sample_date as {{ dbt.type_string() }})
from cytology where adequacy is not null and report_date is not null
{% for field, availability in [
('gynecologic_condition', 'gynecologic_condition_known_at'),
('presenting_symptom', 'sample_known_at'),
('cervix_appearance', 'sample_known_at')
] %}
union all
select person_id, sample_date, {{ availability }}, '{{ field }}', {{ field }}, null,
'cervical_cytology', cast(sample_date as {{ dbt.type_string() }})
from cytology where {{ field }} is not null
{% endfor %}
union all
select person_id, report_date, known_at, 'bethesda', result, null,
'cervical_cytology', cast(sample_date as {{ dbt.type_string() }})
from cytology where result is not null and report_date is not null
union all
select person_id, report_date, known_at, 'glandular', glandular, null,
'cervical_cytology', cast(sample_date as {{ dbt.type_string() }})
from cytology where glandular is not null and report_date is not null
union all
select person_id, report_date, known_at, 'hpv',
case when hpv then 'positive' else 'negative' end, null,
'cervical_cytology', cast(sample_date as {{ dbt.type_string() }})
from cytology where hpv is not null and report_date is not null
{% for genotype in p.hpv_genotype_fields %}
union all
select person_id, report_date, report_known_at, '{{ genotype }}',
case when {{ genotype }} then 'positive' else 'negative' end, null,
'cervical_cytology', cast(sample_date as {{ dbt.type_string() }})
from cytology where {{ genotype }} is not null and report_date is not null
{% endfor %}
union all
select person_id, report_date, known_at, 'hpv_16_18', null,
case when hpv_16 or hpv_18 then 1.0 else 0.0 end,
case when hpv_16 or hpv_18 then 1.0
when hpv_16 is not null and hpv_18 is not null then 0.0 end,
'cervical_cytology', cast(sample_date as {{ dbt.type_string() }})
from cytology where (hpv_16 is not null or hpv_18 is not null) and report_date is not null
from cytology where (hpv_16 or hpv_18 or (hpv_16 is not null and hpv_18 is not null))
and report_date is not null
union all
select person_id, request_date, known_at, 'biopsy_order', null, null,
@@ -121,9 +151,14 @@ events as (
from biopsy where histology is not null and report_date is not null
union all
select person_id, note_date, known_at, 'note', icd10, null, 'clinical_note', source_id
select person_id, note_date, case when icd10 is null then known_at else icd10_known_at end,
'note', icd10, null, 'clinical_note', source_id
from note
union all
select person_id, note_date, icd10_known_at, 'gynecologic_condition', 'hysterectomy', null,
'clinical_note', source_id
from note where icd10 in {{ sql_list(p.hysterectomy_icd10) }}
union all
select person_id, note_date, known_at, 'diagnosis', null, null, 'clinical_note', source_id
from diagnosis
union all
@@ -137,6 +172,53 @@ events as (
union all
select person_id, date, known_at, 'colposcopy', null, null, source_table, source_id
from colposcopy
),
source_dates as (
{% for table, relation, procedure_day, columns in [
('cervical_cytology', 'cytology', 'sample_date', [
('gynecologic_condition', 'gynecologic_condition'), ('bethesda', 'result'),
('glandular', 'glandular'),
('hpv', 'hpv'), ('hpv_16', 'hpv_16'), ('hpv_18', 'hpv_18')
]),
('cervical_biopsy', 'biopsy', 'request_date', [('biopsy', 'histology')]),
('clinical_note', 'note', none, [
('note', 'icd10'), ('gynecologic_condition', 'icd10'), ('diagnosis', 'icd10'),
('history', 'icd10'), ('treatment', 'icd10')
])
] %}
{% for event, field in columns %}
{% if not (loop.first and table == 'cervical_cytology') %}union all{% endif %}
select person_id, '{{ table }}' as source_table,
{% if procedure_day %}cast({{ procedure_day }} as {{ dbt.type_string() }})
{% else %}source_id{% endif %} as source_id,
'{{ event }}' as type, {{ field }}_source_clinical_date as evidence_date,
{{ field }}_source_available_at as source_available_at, {{ field }}_source_ref as source_ref
from {{ relation }} where {{ field }} is not null
{% endfor %}
{% endfor %}
)
select * from events where date is not null
select e.*, coalesce(s.evidence_date, e.date) as evidence_date,
s.source_available_at, s.source_ref
from events as e
left join source_dates as s
on s.person_id = e.person_id and s.source_table = e.source_table
and s.source_id = e.source_id and s.type = e.type
where e.date is not null
union all
select person_id,
date, known_at,
case when (type = 'condition' and value_code in {{ sql_list(p.hysterectomy_icd10) }})
or (type = 'gynecologic_condition' and value_code = 'hysterectomy')
then 'gynecologic_condition'
else type end as type,
case when (type = 'condition' and value_code in {{ sql_list(p.hysterectomy_icd10) }})
or (type = 'gynecologic_condition' and value_code = 'hysterectomy')
then 'hysterectomy'
else value_code end as value_code,
value_num, source_table, source_id,
evidence_date, source_available_at, source_ref
from {{ ref('cacu_eligibility_evidence') }}
@@ -1,16 +1,47 @@
{#
One row per CaCu patient: the first day of each follow-up step, from her timeline. Her
status at any day follows from them (core.measures.follow_up_status): a case (a biopsy
reported CASE grade), after treatment, after colposcopy, or before colposcopy.
reported CASE grade), after treatment, after colposcopy, or before colposcopy. And the
biopsy her first treatment answers, by the post-treatment cohort's rule (a result in the
POST_TREATMENT_LOOKBACK_DAYS up to it, that day included): the last reported.
#}
{% set p = var('cacu') %}
with first_events as (
select
p.person_id,
min(case when e.type = 'biopsy' and e.value_code in {{ sql_list(p.case) }}
then e.date end) as first_case,
min(case when e.type = 'treatment' then e.date end) as first_treatment,
min(case when e.type = 'colposcopy' then e.date end) as first_colposcopy,
min(case when e.type = 'history' then e.date end) as first_history
min(case when e.type = 'history' then e.date end) as first_history,
min(case when {{ cacu_hysterectomy_exam('e') }} then e.date end) as first_hysterectomy
from {{ ref('person') }} as p
left join {{ ref('cacu_events') }} as e on e.person_id = p.person_id
group by p.person_id
),
treated as (
select f.person_id, b.date as request_date,
row_number() over (partition by f.person_id
order by b.report_date desc, b.date desc) as n
from first_events as f
join {{ ref('cacu_procedures') }} as b
on b.type = 'biopsy' and b.person_id = f.person_id and b.histology is not null
and b.report_date <= f.first_treatment
and {{ days_between('b.report_date', 'f.first_treatment') }}
<= {{ p.post_treatment_lookback_days }}
),
follow_up as (
select f.*,
min(case when e.type = 'cytology' and e.date > f.first_colposcopy
then e.date end) as first_postcolposcopy_cytology
from first_events as f
left join {{ ref('cacu_events') }} as e on e.person_id = f.person_id
group by f.person_id, f.first_case, f.first_treatment, f.first_colposcopy,
f.first_history, f.first_hysterectomy
)
select f.*, t.request_date as treated_biopsy_request_date
from follow_up as f
left join treated as t on t.person_id = f.person_id and t.n = 1
@@ -58,7 +58,7 @@ referred as (
order by c.sample_date desc, c.report_date desc) as n
from procedures as x
join {{ ref('cervical_cytology') }} as c on c.person_id = x.person_id
where c.result is not null and coalesce(c.adequacy, '') <> 'unsatisfactory'
where {{ cacu_valid_cytology('c') }}
and c.sample_date < x.date and c.report_date < x.date
and {{ days_between('c.report_date', 'x.date') }} <= {{ p.cytology_before_days }}
)
@@ -4,6 +4,8 @@
select model, version, person_id, index_date, horizon_years, probability, ci_low, ci_high,
{% if staged_has_column('model_scores', 'scenarios') -%} scenarios
{%- else -%} cast(null as {{ dbt.type_string() }}) as scenarios {%- endif %},
{% if staged_has_column('model_scores', 'input_values') -%} input_values
{%- else -%} cast(null as {{ dbt.type_string() }}) as input_values {%- endif %},
scored_at
from {{ source('bronze', 'model_scores') }}
where model like 'cacu.%'
@@ -11,9 +11,14 @@
{% set h = p.horizons %}
with sample as (
select
c.person_id, c.sample_date, c.report_date, c.result, c.adequacy, c.known_at,
c.report_known_at, c.screening_history, c.hpv, c.hpv_16, c.hpv_18,
case when c.result is not null then c.report_date end as result_date,
c.person_id, c.sample_date, c.report_date, c.result, c.glandular, c.adequacy,
-- the finding that speaks for the sample: a glandular one outranks a squamous one
-- below high grade
case when c.glandular is not null and coalesce(c.result, 'NILM') in ('NILM', 'ASC-US', 'LSIL')
then c.glandular else c.result end as finding, c.known_at,
c.report_known_at, c.screening_history, c.gynecologic_condition, c.hpv, c.hpv_16, c.hpv_18,
case when c.result is not null or c.glandular is not null then c.report_date end as result_date,
case when {{ cacu_valid_cytology('c') }} then 1 else 0 end as valid,
{{ dbt.concat(['c.person_id', "'|'", 'cast(c.sample_date as ' ~ dbt.type_string() ~ ')']) }} as sample_id,
p.birth_date
from {{ ref('cervical_cytology') }} as c
@@ -47,15 +52,6 @@ diagnosis_code as ( -- the ICD-10 of the note that dates the diagnosis
group by d.sample_id
),
diagnosis_treatment as (
select d.sample_id, min(e.date) as date
from diagnosis as d
join sample as s on s.sample_id = d.sample_id
join events as e on e.person_id = s.person_id and e.type = 'treatment' and e.date > d.date
where {{ days_between('d.date', 'e.date') }} < {{ h.diagnosis_to_treatment }}
group by d.sample_id
),
biopsy_diagnosis as (
select b.sample_id, min(e.date) as date
from biopsy as b
@@ -63,22 +59,99 @@ biopsy_diagnosis as (
join events as e on e.person_id = s.person_id and e.type = 'diagnosis' and e.date > b.date
where {{ days_between('b.date', 'e.date') }} < {{ h.biopsy_to_diagnosis }}
group by b.sample_id
),
diagnosis_treatment as ( -- from the diagnosis "tras biopsia"; that same day counts, as 0 days
select d.sample_id, min(e.date) as date
from biopsy_diagnosis as d
join sample as s on s.sample_id = d.sample_id
join events as e on e.person_id = s.person_id and e.type = 'treatment' and e.date >= d.date
where {{ days_between('d.date', 'e.date') }} < {{ h.diagnosis_to_treatment }}
group by d.sample_id
),
-- What preceded each sample, counted once here for whoever asks (consultation, not cohorts).
-- "before": strictly earlier days; "by": up to and including the sample's day.
earlier_samples as (
select
s.sample_id,
count(e.sample_date) as samples,
max(e.sample_date) as last_date,
sum(case when e.hpv is not null then 1 else 0 end) as hpv_tests,
sum(case when e.sample_date > f.first_colposcopy then 1 else 0 end) as since_colposcopy,
sum(case when e.sample_date > f.first_treatment then 1 else 0 end) as since_treatment
from sample as s
left join {{ ref('cacu_follow_up') }} as f on f.person_id = s.person_id
left join sample as e on e.person_id = s.person_id and e.sample_date < s.sample_date
group by s.sample_id
),
events_by as (
select
s.sample_id,
count(distinct case when e.type = 'colposcopy' then e.date end) as colposcopies,
count(distinct case when e.type = 'treatment' then e.date end) as treatments
from sample as s
join events as e on e.person_id = s.person_id and e.type in ('colposcopy', 'treatment')
and e.date <= s.sample_date
group by s.sample_id
),
biopsies_by as (
select
s.sample_id,
count(*) as requested,
sum(case when b.report_date < s.sample_date then 1 else 0 end) as reported_before,
sum(case when b.date < s.sample_date
and (b.report_date is null or b.report_date >= s.sample_date)
then 1 else 0 end) as pending
from sample as s
join {{ ref('cacu_procedures') }} as b
on b.type = 'biopsy' and b.person_id = s.person_id and b.date <= s.sample_date
group by s.sample_id
),
hysterectomy_by as (
select distinct s.sample_id
from sample as s
join sample as e on e.person_id = s.person_id and e.sample_date <= s.sample_date
where e.gynecologic_condition = 'hysterectomy'
)
select
s.*,
es.samples + 1 as visit_number,
es.last_date as previous_sample_date,
es.hpv_tests as previous_hpv_tests,
case when s.sample_date > f.first_colposcopy then es.since_colposcopy + 1 end
as visit_since_colposcopy,
case when s.sample_date > f.first_treatment then es.since_treatment + 1 end
as visit_since_treatment,
coalesce(ev.colposcopies, 0) as colposcopies_by_sample,
coalesce(ev.treatments, 0) as treatments_by_sample,
coalesce(bb.requested, 0) as biopsy_requests_by_sample,
coalesce(bb.reported_before, 0) as biopsy_reports_before,
coalesce(bb.pending, 0) as biopsies_pending,
case when hy.sample_id is null then 0 else 1 end as hysterectomy_declared_by_sample,
case when f.first_history < s.sample_date then 1 else 0 end as history,
f.first_case,
f.first_treatment,
f.first_colposcopy,
f.first_postcolposcopy_cytology,
{{ cacu_detection('s', 'f') }} as detection,
{{ days_between('s.sample_date', 's.result_date') }} as days_sample_result,
dx.date as diagnosis_date,
-- the consultation before her colposcopy: a diagnosis from that day on is not one
case when f.first_colposcopy is null or dx.date < f.first_colposcopy then dx.date end
as precolposcopy_diagnosis_date,
case when f.first_colposcopy is null or dx.date < f.first_colposcopy
then {{ days_between('s.sample_date', 'dx.date') }} end as days_sample_precolposcopy_diagnosis,
case when dc.codes > 1 then 'several' else dc.code end as diagnosis_code,
{{ days_between('s.sample_date', 'dx.date') }} as days_sample_diagnosis,
tx.date as treatment_date,
{{ days_between('s.sample_date', 'tx.date') }} as days_sample_treatment,
dt.date as diagnosis_treatment_date,
{{ days_between('dx.date', 'dt.date') }} as days_diagnosis_treatment,
{{ days_between('bd.date', 'dt.date') }} as days_diagnosis_treatment,
col.date as colposcopy_date,
{{ days_between('s.sample_date', 'col.date') }} as days_sample_colposcopy,
bx.date as biopsy_date,
@@ -91,6 +164,7 @@ select
then {{ days_between('rc.date', 'bx.date') }}
end as days_colposcopy_biopsy,
bd.date as biopsy_diagnosis_date,
{{ days_between('s.sample_date', 'bd.date') }} as days_sample_biopsy_diagnosis,
{{ days_between('bx.date', 'bd.date') }} as days_biopsy_diagnosis
from sample as s
left join {{ ref('cacu_follow_up') }} as f on f.person_id = s.person_id
@@ -102,3 +176,7 @@ left join colposcopy as col on col.sample_id = s.sample_id
left join biopsy as bx on bx.sample_id = s.sample_id
left join result_colposcopy as rc on rc.sample_id = s.sample_id
left join biopsy_diagnosis as bd on bd.sample_id = s.sample_id
left join earlier_samples as es on es.sample_id = s.sample_id
left join events_by as ev on ev.sample_id = s.sample_id
left join biopsies_by as bb on bb.sample_id = s.sample_id
left join hysterectomy_by as hy on hy.sample_id = s.sample_id
@@ -0,0 +1,60 @@
{#
One row per patient and scenario. Visit two is the index; visit one comes from
the same scenario. Use only results from visit one reported by the index sample
date. Visit two's results may arrive later, through the build's data cut-off.
#}
{% set fields = var('cacu').second_visit_fields %}
{% set results = ['bethesda', 'glandular', 'hpv'] + var('cacu').hpv_genotype_fields %}
with pre as (
{{ cacu_surveillance_index(visit=2, before_referral=true) }}
),
post as (
{{ cacu_post_colposcopy_index(visit=2, require_biopsy_report=false) }}
),
candidates as (
select * from pre
union all
select * from post
),
visits as (
select c.scenario, c.person_id, c.index_date, c.previous_date, c.source_table, c.source_id,
c.previous_source_table, c.previous_source_id,
c.colposcopy_date, c.excluded_by
from candidates as c
),
matched as (
select v.person_id, v.scenario, v.index_date, v.previous_date, v.colposcopy_date,
v.excluded_by,
v.source_id as index_sample_id, v.previous_source_id as previous_sample_id,
e.type, e.value_code, e.date,
case when e.source_table = v.source_table and e.source_id = v.source_id
then 'index' else 'previous' end as visit
from visits as v
left join {{ ref('cacu_events') }} as e
on v.excluded_by is null and e.person_id = v.person_id
and e.type in {{ sql_list(fields) }}
and e.date <= {{ as_of() }}
and ((e.source_table = v.source_table and e.source_id = v.source_id)
or (e.source_table = v.previous_source_table and e.source_id = v.previous_source_id
and e.date <= v.index_date))
)
select person_id, scenario, index_date, index_sample_id, previous_date, previous_sample_id,
colposcopy_date,
{{ as_of() }} as data_cutoff, excluded_by,
max(case when visit = 'index' and type in {{ sql_list(results) }} then date end)
as index_result_date
{% for visit in ['previous', 'index'] %}
{% for field in fields %}
, max(case when visit = '{{ visit }}' and type = '{{ field }}' then value_code end)
as {{ visit }}_{{ field }}
{% endfor %}
{% endfor %}
from matched
group by person_id, scenario, index_date, index_sample_id, previous_date, previous_sample_id,
colposcopy_date, excluded_by
+14
View File
@@ -3,6 +3,20 @@ version: 2
models:
- name: cama_mammograms
columns:
- name: biopsy_date
description: Primer reporte válido de biopsia vinculada a la mastografía.
- name: biopsy_date_known_at
description: Disponibilidad del reporte seleccionado.
- name: biopsy_diagnosis_date
description: Primer diagnóstico posterior al reporte dentro de la ventana provisional.
- name: biopsy_diagnosis_known_at
description: Disponibilidad del diagnóstico seleccionado.
- name: diagnosis_treatment_date
description: Primer tratamiento desde el diagnóstico, incluido el mismo día, dentro de la ventana provisional.
- name: diagnosis_treatment_known_at
description: Disponibilidad del tratamiento seleccionado.
- name: days_diagnosis_treatment
description: Días entre diagnóstico y tratamiento; nulo si falta alguno.
- name: mammogram_id
data_tests: [unique, not_null]
- name: cama_biopsies
@@ -1,11 +1,17 @@
{#
One row per mammogram and each reported biopsy it led to (one row with no biopsy when it led
to none): what the measures that follow a mammogram to its biopsy count over.
to none): what the measures that follow a mammogram to its biopsy count over. The biopsy is
the one whose request names the mammogram (`cama_biopsies`); none is matched by dates.
`days_report_biopsy`: days from the mammogram's report to the biopsy's report; empty when
either date is missing, and when the biopsy was reported before the mammogram (inconsistent).
#}
select
m.*,
b.biopsy_id, b.report_date as biopsy_report_date, b.histology, b.histology_rank,
b.report_known_at as biopsy_known_at
b.report_known_at as biopsy_known_at,
case
when b.report_date >= m.report_date then {{ days_between('m.report_date', 'b.report_date') }}
end as days_report_biopsy
from {{ ref('cama_mammograms') }} as m
left join {{ ref('cama_biopsies') }} as b
on b.mammogram_id = m.mammogram_id and b.report_date is not null
@@ -21,6 +21,29 @@ events as (select * from {{ ref('cama_events') }}),
{{ first_after('diagnosis', 's.exam_date', 'diagnosis', p.horizons.to_diagnosis, key='mammogram_id') }},
{{ first_after('report_diagnosis', 's.report_date', 'diagnosis', p.horizons.to_diagnosis, strict=false, key='mammogram_id') }},
biopsy_dates as (
select s.mammogram_id, min(b.report_date) as date
from sample as s join {{ ref('breast_biopsy') }} as b
on b.person_id = s.person_id and b.mammogram_exam_date = s.exam_date
where b.report_date >= s.exam_date group by s.mammogram_id
),
biopsy as (
select s.mammogram_id, s.person_id, b.date, min(x.report_known_at) as known_at
from biopsy_dates as b join sample as s on s.mammogram_id = b.mammogram_id
join {{ ref('breast_biopsy') }} as x on x.person_id = s.person_id
and x.mammogram_exam_date = s.exam_date and x.report_date = b.date
group by s.mammogram_id, s.person_id, b.date
),
{{ first_after('biopsy_diagnosis', 's.date', 'diagnosis', p.horizons.biopsy_to_diagnosis, units='biopsy', key='mammogram_id') }},
diagnosis_units as (
select s.person_id, d.mammogram_id, d.date
from biopsy_diagnosis as d join sample as s on s.mammogram_id = d.mammogram_id
),
{{ first_after('diagnosis_treatment', 's.date', 'treatment', p.horizons.diagnosis_to_treatment, strict=false, units='diagnosis_units', key='mammogram_id') }},
event_known as (
select person_id, type, date, min(known_at) as known_at
from events where type in ('diagnosis', 'treatment') group by person_id, type, date
),
known as (
select person_id, date, min(known_at) as known_at
from events where type = 'diagnosis' group by person_id, date
@@ -45,9 +68,19 @@ select
{{ days_between('s.exam_date', 'd.date') }} as days_sample_diagnosis,
r.date as report_diagnosis_date,
{{ days_between('s.report_date', 'r.date') }} as days_report_diagnosis,
b.date as biopsy_date, b.known_at as biopsy_date_known_at,
bd.date as biopsy_diagnosis_date, bdk.known_at as biopsy_diagnosis_known_at,
dt.date as diagnosis_treatment_date, dtk.known_at as diagnosis_treatment_known_at,
{{ days_between('bd.date', 'dt.date') }} as days_diagnosis_treatment,
case when h.first_history < s.exam_date then 1 else 0 end as history
from sample as s
left join diagnosis as d on d.mammogram_id = s.mammogram_id
left join known as kd on kd.person_id = s.person_id and kd.date = d.date
left join report_diagnosis as r on r.mammogram_id = s.mammogram_id
left join history as h on h.person_id = s.person_id
left join biopsy as b on b.mammogram_id = s.mammogram_id
left join biopsy_diagnosis as bd on bd.mammogram_id = s.mammogram_id
left join diagnosis_treatment as dt on dt.mammogram_id = s.mammogram_id
left join event_known as bdk on bdk.person_id = s.person_id and bdk.type = 'diagnosis' and bdk.date = bd.date
left join event_known as dtk on dtk.person_id = s.person_id and dtk.type = 'treatment' and dtk.date = dt.date
+22
View File
@@ -0,0 +1,22 @@
version: 2
seeds:
- name: nci_risk_row
description: >-
Each published combination of the NCI master table. An empty condition is one its table
does not use, never a negative result. Generated by tools/nci_seeds.py from the NCI's five
general tables, with each row's file, sheet, row and SHA-256.
columns:
- name: row_id
data_tests: [unique, not_null]
- name: nci_risk_estimate
description: >-
One risk with its 95% limits per row, outcome (CIN2+, CIN3+, cancer) and horizon;
empty when the tables leave it blank. The table of results after colposcopy has CIN3+ alone.
columns:
- name: row_id
data_tests: [not_null]
models:
- name: nci_risk_lookup
description: nci_risk_row as it is searched, by `asked_cytology`.
@@ -0,0 +1,30 @@
{#
The row of the NCI master table for a combination, queried by equality: one row per published
combination under its own cytology category (`exact`) and, for each result a group category
holds, under that result (`table_group`) when no row names the result itself. The groups are
the tables' own (core.cacu.reference_risk.vocabulary.GROUPS).
#}
{%- set same = ['scenario', 'previous_two', 'history', 'hpv', 'referral', 'biopsy',
'pre_colposcopy', 'post_colposcopy_history', 'biopsy_before_treatment'] %}
with members as (
{% for group, results in var('cacu').nci_cytology_groups.items() %}
{% for result in results %}
select '{{ group }}' as category, '{{ result }}' as member
union all
{% endfor %}
{% endfor %}
select null as category, null as member
)
select r.*, r.cytology as asked_cytology, 'exact' as matched_via
from {{ ref('nci_risk_row') }} as r
union all
select r.*, m.member as asked_cytology, 'table_group' as matched_via
from {{ ref('nci_risk_row') }} as r
join members as m on m.category = r.cytology
where not exists (
select 1 from {{ ref('nci_risk_row') }} as x
where x.cytology = m.member
{%- for column in same %}
and coalesce(x.{{ column }}, '') = coalesce(r.{{ column }}, '')
{%- endfor %}
)
@@ -1,3 +1,3 @@
{{ config(materialized='table') }}
{#- cervical_biopsy, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('cervical_biopsy') }} as p
select * from {{ pivot('cervical_biopsy', timestamped_fields=['histology']) }} as p
@@ -1,3 +1,5 @@
{{ config(materialized='table') }}
{#- cervical_cytology, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('cervical_cytology') }} as p
select * from {{ pivot('cervical_cytology', timestamped_fields=[
'gynecologic_condition', 'result', 'glandular', 'hpv', 'hpv_16', 'hpv_18'
]) }} as p
@@ -1,3 +1,3 @@
{{ config(materialized='table') }}
{#- clinical_note, wide (one row per instance): what gold and the API read. -#}
select * from {{ pivot('clinical_note') }} as p
select * from {{ pivot('clinical_note', timestamped_fields=['icd10']) }} as p
+35 -3
View File
@@ -5,7 +5,8 @@
- rows of one instance are one record: values that complement each other are merged; a
field with two different values is a conflict, and the whole instance stays out until a
reviewer rejects the wrong row;
- an instance is known from when its first row was (`known_at`).
- an instance is known from when its first row was (`known_at`);
- `field_known_at` is ingestion time. Source dates come from one accepted contributor.
#}
{%- if not staged_exists('staged__observation') %}
select
@@ -18,11 +19,22 @@ select
cast(null as {{ dbt.type_boolean() }}) as value_bool,
cast(null as date) as value_date,
cast(null as {{ dbt.type_timestamp() }}) as known_at,
cast(null as {{ dbt.type_timestamp() }}) as field_known_at,
cast(null as date) as source_clinical_date,
cast(null as {{ dbt.type_string() }}) as source_available_at,
cast(null as {{ dbt.type_string() }}) as source_ref,
0 as rows_merged
where 1 = 0
{%- else %}
{% set source_metadata = [('source_clinical_date', 'date'),
('source_available_at', dbt.type_string()),
('source_ref', dbt.type_string())] %}
with accepted as (
select * from {{ source('bronze', 'staged__observation') }} as s
select s.*
{%- for column, kind in source_metadata if not staged_has_column('staged__observation', column) %}
, cast(null as {{ kind }}) as {{ column }}
{%- endfor %}
from {{ source('bronze', 'staged__observation') }} as s
where s.person_id is not null
{%- if staged_exists('review_log') %}
and not exists (
@@ -32,12 +44,28 @@ with accepted as (
{%- endif %}
),
ranked_evidence as (
select *, row_number() over (
partition by person_id, study, instance, field
order by case when source_available_at is null then 1 else 0 end,
source_available_at,
case when source_clinical_date is null then 1 else 0 end,
source_clinical_date, _record, _index
) as evidence_rank
from accepted
where value_text is not null or value_num is not null
or value_date is not null or value_bool is not null
),
cells as (
select
person_id, study, instance, field,
max(value_text) as value_text, count(distinct value_text) as n_text,
max(value_num) as value_num, count(distinct value_num) as n_num,
max(value_date) as value_date, count(distinct value_date) as n_date,
min(case when value_text is not null or value_num is not null
or value_date is not null or value_bool is not null
then known_at end) as field_known_at,
max(case when value_bool then 1 else 0 end) as bool_any,
min(case when value_bool then 1 else 0 end) as bool_all,
count(value_bool) as n_bool
@@ -64,10 +92,14 @@ select
c.value_text, c.value_num,
case when c.n_bool = 0 then null else c.bool_any = 1 end as value_bool,
c.value_date,
i.known_at, i.rows_merged
i.known_at, c.field_known_at, i.rows_merged,
e.source_clinical_date, e.source_available_at, e.source_ref
from cells as c
join instances as i
on i.person_id = c.person_id and i.study = c.study and i.instance = c.instance
left join ranked_evidence as e
on e.person_id = c.person_id and e.study = c.study and e.instance = c.instance
and e.field = c.field and e.evidence_rank = 1
where not exists (
select 1 from conflicted as x
where x.person_id = c.person_id and x.study = c.study and x.instance = c.instance
File diff suppressed because it is too large Load Diff
+180
View File
@@ -0,0 +1,180 @@
row_id,scenario,previous_two,history,hpv,cytology,referral,biopsy,pre_colposcopy,post_colposcopy_history,biopsy_before_treatment,published,shown,book,sheet,source_row,source_sha256
screening-2,screening,,NO HISTORY,HPV-negative,NILM,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,2,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-3,screening,,NO HISTORY,HPV-negative,ASC-US,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,3,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-4,screening,,NO HISTORY,HPV-negative,LSIL,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,4,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-5,screening,,NO HISTORY,HPV-negative,ASC-H,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,5,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-6,screening,,NO HISTORY,HPV-negative,AGC,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,6,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-7,screening,,NO HISTORY,HPV-negative,HSIL+,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,7,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-8,screening,,NO HISTORY,HPV-negative,ALL,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,8,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-9,screening,,NO HISTORY,HPV-positive,NILM,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,9,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-10,screening,,NO HISTORY,HPV-positive,ASC-US,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,10,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-11,screening,,NO HISTORY,HPV-positive,LSIL,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,11,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-12,screening,,NO HISTORY,HPV-positive,ASC-H,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,12,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-13,screening,,NO HISTORY,HPV-positive,AGC,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,13,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-14,screening,,NO HISTORY,HPV-positive,HSIL+,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,14,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-15,screening,,NO HISTORY,HPV16+,NILM,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,15,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-16,screening,,NO HISTORY,HPV16+,ASC-US,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,16,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-17,screening,,NO HISTORY,HPV16+,LSIL,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,17,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-18,screening,,NO HISTORY,HPV16+,ASC-H,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,18,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-19,screening,,NO HISTORY,HPV16+,AGC,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,19,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-20,screening,,NO HISTORY,HPV16+,HSIL+,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,20,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-21,screening,,NO HISTORY,"HPV16-, HPV18+",NILM,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,21,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-22,screening,,NO HISTORY,"HPV16-, HPV18+",ASC-US,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,22,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-23,screening,,NO HISTORY,"HPV16-, HPV18+",LSIL,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,23,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-24,screening,,NO HISTORY,"HPV16-, HPV18+",ASC-H,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,24,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-25,screening,,NO HISTORY,"HPV16-, HPV18+",AGC,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,25,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-26,screening,,NO HISTORY,"HPV16-, HPV18+",HSIL+,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,26,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-27,screening,,HPV-negative,HPV-negative,NILM,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,27,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-28,screening,,HPV-negative,HPV-negative,ASC-US,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,28,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-29,screening,,HPV-negative,HPV-negative,LSIL,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,29,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-30,screening,,HPV-negative,HPV-negative,ASC-H,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,30,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-31,screening,,HPV-negative,HPV-negative,AGC,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,31,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-32,screening,,HPV-negative,HPV-negative,HSIL+,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,32,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-33,screening,,HPV-negative,HPV-negative,ALL,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,33,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-34,screening,,HPV-negative,HPV-positive,NILM,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,34,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-35,screening,,HPV-negative,HPV-positive,ASC-US,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,35,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-36,screening,,HPV-negative,HPV-positive,LSIL,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,36,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-37,screening,,HPV-negative,HPV-positive,ASC-H,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,37,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-38,screening,,HPV-negative,HPV-positive,AGC,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,38,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-39,screening,,HPV-negative,HPV-positive,HSIL+,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,39,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-40,screening,,HPV-negative,HPV16+,NILM,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,40,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-41,screening,,HPV-negative,HPV16+,ASC-US,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,41,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-42,screening,,HPV-negative,HPV16+,LSIL,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,42,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-43,screening,,HPV-negative,HPV16+,High Grade,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,43,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-44,screening,,HPV-negative,"HPV16-, HPV18+",NILM,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,44,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-45,screening,,HPV-negative,"HPV16-, HPV18+",ASC-US,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,45,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-46,screening,,HPV-negative,"HPV16-, HPV18+",LSIL,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,46,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-47,screening,,HPV-negative,"HPV16-, HPV18+",High Grade,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,47,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-48,screening,,Cotest-negative,HPV-negative,NILM,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,48,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-49,screening,,Cotest-negative,HPV-negative,ASC-US,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,49,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-50,screening,,Cotest-negative,HPV-negative,LSIL,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,50,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-51,screening,,Cotest-negative,HPV-negative,ASC-H,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,51,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-52,screening,,Cotest-negative,HPV-negative,AGC,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,52,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-53,screening,,Cotest-negative,HPV-negative,HSIL+,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,53,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-54,screening,,Cotest-negative,HPV-negative,ALL,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,54,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-55,screening,,Cotest-negative,HPV-positive,NILM,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,55,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-56,screening,,Cotest-negative,HPV-positive,ASC-US,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,56,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-57,screening,,Cotest-negative,HPV-positive,LSIL,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,57,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-58,screening,,Cotest-negative,HPV-positive,ASC-H,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,58,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-59,screening,,Cotest-negative,HPV-positive,AGC,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,59,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-60,screening,,Cotest-negative,HPV-positive,HSIL+,,,,,,1,1,1-General_Table_for_Screening_locked.xlsx,Sheet1,60,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-61,screening,,Cotest-negative,HPV16+,NILM,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,61,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-62,screening,,Cotest-negative,HPV16+,ASC-US,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,62,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-63,screening,,Cotest-negative,HPV16+,LSIL,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,63,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-64,screening,,Cotest-negative,HPV16+,High Grade,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,64,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-65,screening,,Cotest-negative,"HPV16-, HPV18+",NILM,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,65,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-66,screening,,Cotest-negative,"HPV16-, HPV18+",ASC-US,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,66,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-67,screening,,Cotest-negative,"HPV16-, HPV18+",LSIL,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,67,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
screening-68,screening,,Cotest-negative,"HPV16-, HPV18+",High Grade,,,,,,1,0,1-General_Table_for_Screening_locked.xlsx,Sheet1,68,c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
surveillance-2,surveillance,,HPV-positive/NILM,HPV-negative,NILM,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,2,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-3,surveillance,,HPV-positive/NILM,HPV-negative,ASC-US,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,3,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-4,surveillance,,HPV-positive/NILM,HPV-negative,LSIL,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,4,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-5,surveillance,,HPV-positive/NILM,HPV-negative,ASC-H,,,,,,0,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,5,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-6,surveillance,,HPV-positive/NILM,HPV-negative,AGC,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,6,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-7,surveillance,,HPV-positive/NILM,HPV-negative,HSIL+,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,7,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-8,surveillance,,HPV-positive/NILM,HPV-negative,ALL,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,8,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-9,surveillance,,HPV-positive/NILM,HPV-positive,NILM,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,9,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-10,surveillance,,HPV-positive/NILM,HPV-positive,ASC-US,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,10,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-11,surveillance,,HPV-positive/NILM,HPV-positive,LSIL,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,11,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-12,surveillance,,HPV-positive/NILM,HPV-positive,ASC-H,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,12,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-13,surveillance,,HPV-positive/NILM,HPV-positive,AGC,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,13,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-14,surveillance,,HPV-positive/NILM,HPV-positive,HSIL+,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,14,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-15,surveillance,,HPV-negative/LSIL,HPV-negative,NILM,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,15,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-16,surveillance,,HPV-negative/LSIL,HPV-negative,ASC-US,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,16,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-17,surveillance,,HPV-negative/LSIL,HPV-negative,LSIL,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,17,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-18,surveillance,,HPV-negative/LSIL,HPV-negative,ASC-H,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,18,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-19,surveillance,,HPV-negative/LSIL,HPV-negative,AGC,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,19,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-20,surveillance,,HPV-negative/LSIL,HPV-negative,HSIL+,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,20,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-21,surveillance,,HPV-negative/LSIL,HPV-positive,NILM,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,21,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-22,surveillance,,HPV-negative/LSIL,HPV-positive,ASC-US,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,22,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-23,surveillance,,HPV-negative/LSIL,HPV-positive,LSIL,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,23,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-24,surveillance,,HPV-negative/LSIL,HPV-positive,ASC-H,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,24,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-25,surveillance,,HPV-negative/LSIL,HPV-positive,AGC,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,25,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-26,surveillance,,HPV-negative/LSIL,HPV-positive,HSIL+,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,26,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-27,surveillance,,HPV-negative/ASC-US,HPV-negative,NILM,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,27,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-28,surveillance,,HPV-negative/ASC-US,HPV-negative,ASC-US,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,28,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-29,surveillance,,HPV-negative/ASC-US,HPV-negative,LSIL,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,29,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-30,surveillance,,HPV-negative/ASC-US,HPV-negative,ASC-H,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,30,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-31,surveillance,,HPV-negative/ASC-US,HPV-negative,AGC,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,31,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-32,surveillance,,HPV-negative/ASC-US,HPV-negative,HSIL+,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,32,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-33,surveillance,,HPV-negative/ASC-US,HPV-positive,NILM,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,33,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-34,surveillance,,HPV-negative/ASC-US,HPV-positive,ASC-US,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,34,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-35,surveillance,,HPV-negative/ASC-US,HPV-positive,LSIL,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,35,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-36,surveillance,,HPV-negative/ASC-US,HPV-positive,ASC-H,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,36,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-37,surveillance,,HPV-negative/ASC-US,HPV-positive,AGC,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,37,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-38,surveillance,,HPV-negative/ASC-US,HPV-positive,HSIL+,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,38,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-39,surveillance,HPV-positive/NILM,Cotest-negative,HPV-negative,NILM,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,39,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-40,surveillance,HPV-positive/NILM,Cotest-negative,HPV-positive,NILM,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,40,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-41,surveillance,HPV-positive/NILM,Cotest-negative,HPV-positive,ASC-US/LSIL,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,41,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-42,surveillance,HPV-positive/NILM,Cotest-negative,HPV-positive,High Grade,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,42,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-43,surveillance,HPV-positive/NILM,HPV-negative,HPV-negative,ALL,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,43,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-44,surveillance,HPV-positive/NILM,HPV-negative,HPV-positive,NILM,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,44,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-45,surveillance,HPV-positive/NILM,HPV-negative,HPV-positive,ASC-US/LSIL,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,45,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-46,surveillance,HPV-positive/NILM,HPV-negative,HPV-positive,High Grade,,,,,,1,1,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,46,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-47,surveillance,,HPV-positive/NILM,HPV16+,NILM,,,,,,1,0,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,47,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-48,surveillance,,HPV-positive/NILM,HPV16+,ASC-US,,,,,,1,0,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,48,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-49,surveillance,,HPV-positive/NILM,HPV16+,LSIL,,,,,,1,0,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,49,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-50,surveillance,,HPV-positive/NILM,HPV16+,High Grade,,,,,,1,0,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,50,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-51,surveillance,,HPV-positive/NILM,"HPV16-, HPV18+",NILM,,,,,,1,0,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,51,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-52,surveillance,,HPV-positive/NILM,"HPV16-, HPV18+",ASC-US,,,,,,1,0,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,52,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-53,surveillance,,HPV-positive/NILM,"HPV16-, HPV18+",LSIL,,,,,,1,0,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,53,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
surveillance-54,surveillance,,HPV-positive/NILM,"HPV16-, HPV18+",High Grade,,,,,,1,0,2-General_Table_for_Surveillance_locked.xlsx,Sheet1,54,96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
colposcopy_results-2,colposcopy_results,,,,,HPV-positive NILM x2,<CIN1,,,,1,1,3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx,Sheet2,2,2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
colposcopy_results-3,colposcopy_results,,,,,HPV-positive ASC-US,<CIN1,,,,1,1,3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx,Sheet2,3,2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
colposcopy_results-4,colposcopy_results,,,,,HPV-positive LSIL,<CIN1,,,,1,1,3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx,Sheet2,4,2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
colposcopy_results-5,colposcopy_results,,,,,ASC-H,<CIN1,,,,1,1,3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx,Sheet2,5,2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
colposcopy_results-6,colposcopy_results,,,,,AGC,<CIN1,,,,1,1,3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx,Sheet2,6,2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
colposcopy_results-7,colposcopy_results,,,,,HSIL+,<CIN1,,,,1,1,3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx,Sheet2,7,2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
colposcopy_results-8,colposcopy_results,,,,,HPV-positive NILM x2,CIN1,,,,1,1,3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx,Sheet2,8,2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
colposcopy_results-9,colposcopy_results,,,,,HPV-positive ASC-US,CIN1,,,,1,1,3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx,Sheet2,9,2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
colposcopy_results-10,colposcopy_results,,,,,HPV-positive LSIL,CIN1,,,,1,1,3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx,Sheet2,10,2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
colposcopy_results-11,colposcopy_results,,,,,ASC-H,CIN1,,,,1,1,3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx,Sheet2,11,2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
colposcopy_results-12,colposcopy_results,,,,,AGC,CIN1,,,,1,1,3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx,Sheet2,12,2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
colposcopy_results-13,colposcopy_results,,,,,HSIL+,CIN1,,,,1,1,3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx,Sheet2,13,2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
colposcopy_results-14,colposcopy_results,,,,,,CIN2,,,,0,1,3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx,Sheet2,14,2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
colposcopy_results-15,colposcopy_results,,,,,,CIN3,,,,0,1,3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx,Sheet2,15,2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
colposcopy_results-16,colposcopy_results,,,,,,AIS,,,,0,1,3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx,Sheet2,16,2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
colposcopy_results-17,colposcopy_results,,,,,,Cancer,,,,0,1,3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx,Sheet2,17,2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
post_colposcopy-2,post_colposcopy,,,HPV-negative,NILM,,,Low Grade,,,1,1,4-General_Table_for_Post-Colpo.xlsx,Sheet1,2,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-3,post_colposcopy,,,HPV-negative,ASC-US/LSIL,,,Low Grade,,,1,1,4-General_Table_for_Post-Colpo.xlsx,Sheet1,3,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-4,post_colposcopy,,,HPV-positive,NILM,,,Low Grade,,,1,1,4-General_Table_for_Post-Colpo.xlsx,Sheet1,4,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-5,post_colposcopy,,,HPV-positive,ASC-US/LSIL,,,Low Grade,,,1,1,4-General_Table_for_Post-Colpo.xlsx,Sheet1,5,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-6,post_colposcopy,,,HPV-negative,High Grade,,,Low Grade,,,1,1,4-General_Table_for_Post-Colpo.xlsx,Sheet1,6,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-7,post_colposcopy,,,HPV-positive,High Grade,,,Low Grade,,,1,1,4-General_Table_for_Post-Colpo.xlsx,Sheet1,7,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-8,post_colposcopy,,,HPV-negative,NILM,,,High Grade,,,1,1,4-General_Table_for_Post-Colpo.xlsx,Sheet1,8,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-9,post_colposcopy,,,HPV-negative,ASC-US/LSIL,,,High Grade,,,1,1,4-General_Table_for_Post-Colpo.xlsx,Sheet1,9,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-10,post_colposcopy,,,HPV-positive,NILM,,,High Grade,,,1,1,4-General_Table_for_Post-Colpo.xlsx,Sheet1,10,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-11,post_colposcopy,,,HPV-positive,ASC-US/LSIL,,,High Grade,,,1,1,4-General_Table_for_Post-Colpo.xlsx,Sheet1,11,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-12,post_colposcopy,,,HPV-negative,High Grade,,,High Grade,,,1,1,4-General_Table_for_Post-Colpo.xlsx,Sheet1,12,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-13,post_colposcopy,,,HPV-positive,High Grade,,,High Grade,,,1,1,4-General_Table_for_Post-Colpo.xlsx,Sheet1,13,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-14,post_colposcopy,,,HPV-negative,ALL,,,Low Grade,,,1,1,4-General_Table_for_Post-Colpo.xlsx,Sheet1,14,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-15,post_colposcopy,,,HPV-negative,ALL,,,High Grade,,,1,1,4-General_Table_for_Post-Colpo.xlsx,Sheet1,15,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-16,post_colposcopy,,,HPV-negative,NILM,,,Low Grade,Cotest-negative,,1,0,4-General_Table_for_Post-Colpo.xlsx,Sheet1,16,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-17,post_colposcopy,,,HPV-negative,NILM,,,High Grade,Cotest-negative,,1,0,4-General_Table_for_Post-Colpo.xlsx,Sheet1,17,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-18,post_colposcopy,,,HPV-negative,ALL,,,Low Grade,HPV-negative,,1,0,4-General_Table_for_Post-Colpo.xlsx,Sheet1,18,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-19,post_colposcopy,,,HPV-negative,ALL,,,High Grade,HPV-negative,,1,0,4-General_Table_for_Post-Colpo.xlsx,Sheet1,19,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-20,post_colposcopy,,,HPV-negative,ASC-US/LSIL,,,Low Grade,Cotest-negative,,1,0,4-General_Table_for_Post-Colpo.xlsx,Sheet1,20,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-21,post_colposcopy,,,HPV-positive,NILM,,,Low Grade,Cotest-negative,,1,0,4-General_Table_for_Post-Colpo.xlsx,Sheet1,21,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-22,post_colposcopy,,,HPV-positive,ASC-US/LSIL,,,Low Grade,Cotest-negative,,1,0,4-General_Table_for_Post-Colpo.xlsx,Sheet1,22,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-23,post_colposcopy,,,HPV-negative,High Grade,,,Low Grade,Cotest-negative,,1,0,4-General_Table_for_Post-Colpo.xlsx,Sheet1,23,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-24,post_colposcopy,,,HPV-positive,High Grade,,,Low Grade,Cotest-negative,,1,0,4-General_Table_for_Post-Colpo.xlsx,Sheet1,24,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-25,post_colposcopy,,,HPV-negative,ASC-US/LSIL,,,High Grade,Cotest-negative,,1,0,4-General_Table_for_Post-Colpo.xlsx,Sheet1,25,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-26,post_colposcopy,,,HPV-positive,NILM,,,High Grade,Cotest-negative,,1,0,4-General_Table_for_Post-Colpo.xlsx,Sheet1,26,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-27,post_colposcopy,,,HPV-positive,ASC-US/LSIL,,,High Grade,Cotest-negative,,1,0,4-General_Table_for_Post-Colpo.xlsx,Sheet1,27,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-28,post_colposcopy,,,HPV-negative,NILM,,,Low Grade,HPV-negative/ASC-US/LSIL,,1,0,4-General_Table_for_Post-Colpo.xlsx,Sheet1,28,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-29,post_colposcopy,,,HPV-negative,ASC-US/LSIL,,,Low Grade,HPV-negative/ASC-US/LSIL,,1,0,4-General_Table_for_Post-Colpo.xlsx,Sheet1,29,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-30,post_colposcopy,,,HPV-negative,ALL,,,High Grade,HPV-negative x2,,1,0,4-General_Table_for_Post-Colpo.xlsx,Sheet1,30,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-31,post_colposcopy,,,HPV-negative,ALL,,,Low Grade,HPV-negative x2,,1,0,4-General_Table_for_Post-Colpo.xlsx,Sheet1,31,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-32,post_colposcopy,,,HPV-negative,NILM,,,Low Grade,Cotest-negative x2,,1,0,4-General_Table_for_Post-Colpo.xlsx,Sheet1,32,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_colposcopy-33,post_colposcopy,,,HPV-negative,NILM,,,High Grade,Cotest-negative x2,,1,0,4-General_Table_for_Post-Colpo.xlsx,Sheet1,33,2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
post_treatment-2,post_treatment,,,HPV-negative,NILM,,,,,CIN3,1,0,5-General_Table_for_Post-Treatment_locked.xlsx,Sheet1,2,b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
post_treatment-3,post_treatment,,,HPV-negative,ASC-US/LSIL,,,,,CIN3,1,0,5-General_Table_for_Post-Treatment_locked.xlsx,Sheet1,3,b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
post_treatment-4,post_treatment,,,HPV-positive,NILM,,,,,CIN3,1,0,5-General_Table_for_Post-Treatment_locked.xlsx,Sheet1,4,b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
post_treatment-5,post_treatment,,,HPV-positive,ASC-US/LSIL,,,,,CIN3,1,0,5-General_Table_for_Post-Treatment_locked.xlsx,Sheet1,5,b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
post_treatment-6,post_treatment,,,HPV-negative,High Grade,,,,,CIN3,1,0,5-General_Table_for_Post-Treatment_locked.xlsx,Sheet1,6,b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
post_treatment-7,post_treatment,,,HPV-positive,High Grade,,,,,CIN3,1,0,5-General_Table_for_Post-Treatment_locked.xlsx,Sheet1,7,b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
post_treatment-8,post_treatment,,,HPV-negative,ALL,,,,,CIN3,1,0,5-General_Table_for_Post-Treatment_locked.xlsx,Sheet1,8,b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
post_treatment-9,post_treatment,,,HPV-negative x2,,,,,,CIN3,1,0,5-General_Table_for_Post-Treatment_locked.xlsx,Sheet1,9,b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
post_treatment-10,post_treatment,,,Cotest-negative x2,,,,,,CIN3,1,0,5-General_Table_for_Post-Treatment_locked.xlsx,Sheet1,10,b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
post_treatment-11,post_treatment,,,HPV-negative x3,,,,,,CIN3,1,0,5-General_Table_for_Post-Treatment_locked.xlsx,Sheet1,11,b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
post_treatment-12,post_treatment,,,Cotest-negative x3,,,,,,CIN3,1,0,5-General_Table_for_Post-Treatment_locked.xlsx,Sheet1,12,b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
1 row_id scenario previous_two history hpv cytology referral biopsy pre_colposcopy post_colposcopy_history biopsy_before_treatment published shown book sheet source_row source_sha256
2 screening-2 screening NO HISTORY HPV-negative NILM 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 2 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
3 screening-3 screening NO HISTORY HPV-negative ASC-US 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 3 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
4 screening-4 screening NO HISTORY HPV-negative LSIL 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 4 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
5 screening-5 screening NO HISTORY HPV-negative ASC-H 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 5 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
6 screening-6 screening NO HISTORY HPV-negative AGC 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 6 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
7 screening-7 screening NO HISTORY HPV-negative HSIL+ 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 7 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
8 screening-8 screening NO HISTORY HPV-negative ALL 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 8 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
9 screening-9 screening NO HISTORY HPV-positive NILM 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 9 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
10 screening-10 screening NO HISTORY HPV-positive ASC-US 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 10 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
11 screening-11 screening NO HISTORY HPV-positive LSIL 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 11 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
12 screening-12 screening NO HISTORY HPV-positive ASC-H 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 12 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
13 screening-13 screening NO HISTORY HPV-positive AGC 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 13 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
14 screening-14 screening NO HISTORY HPV-positive HSIL+ 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 14 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
15 screening-15 screening NO HISTORY HPV16+ NILM 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 15 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
16 screening-16 screening NO HISTORY HPV16+ ASC-US 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 16 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
17 screening-17 screening NO HISTORY HPV16+ LSIL 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 17 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
18 screening-18 screening NO HISTORY HPV16+ ASC-H 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 18 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
19 screening-19 screening NO HISTORY HPV16+ AGC 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 19 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
20 screening-20 screening NO HISTORY HPV16+ HSIL+ 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 20 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
21 screening-21 screening NO HISTORY HPV16-, HPV18+ NILM 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 21 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
22 screening-22 screening NO HISTORY HPV16-, HPV18+ ASC-US 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 22 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
23 screening-23 screening NO HISTORY HPV16-, HPV18+ LSIL 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 23 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
24 screening-24 screening NO HISTORY HPV16-, HPV18+ ASC-H 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 24 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
25 screening-25 screening NO HISTORY HPV16-, HPV18+ AGC 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 25 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
26 screening-26 screening NO HISTORY HPV16-, HPV18+ HSIL+ 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 26 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
27 screening-27 screening HPV-negative HPV-negative NILM 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 27 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
28 screening-28 screening HPV-negative HPV-negative ASC-US 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 28 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
29 screening-29 screening HPV-negative HPV-negative LSIL 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 29 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
30 screening-30 screening HPV-negative HPV-negative ASC-H 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 30 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
31 screening-31 screening HPV-negative HPV-negative AGC 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 31 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
32 screening-32 screening HPV-negative HPV-negative HSIL+ 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 32 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
33 screening-33 screening HPV-negative HPV-negative ALL 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 33 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
34 screening-34 screening HPV-negative HPV-positive NILM 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 34 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
35 screening-35 screening HPV-negative HPV-positive ASC-US 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 35 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
36 screening-36 screening HPV-negative HPV-positive LSIL 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 36 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
37 screening-37 screening HPV-negative HPV-positive ASC-H 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 37 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
38 screening-38 screening HPV-negative HPV-positive AGC 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 38 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
39 screening-39 screening HPV-negative HPV-positive HSIL+ 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 39 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
40 screening-40 screening HPV-negative HPV16+ NILM 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 40 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
41 screening-41 screening HPV-negative HPV16+ ASC-US 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 41 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
42 screening-42 screening HPV-negative HPV16+ LSIL 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 42 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
43 screening-43 screening HPV-negative HPV16+ High Grade 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 43 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
44 screening-44 screening HPV-negative HPV16-, HPV18+ NILM 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 44 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
45 screening-45 screening HPV-negative HPV16-, HPV18+ ASC-US 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 45 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
46 screening-46 screening HPV-negative HPV16-, HPV18+ LSIL 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 46 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
47 screening-47 screening HPV-negative HPV16-, HPV18+ High Grade 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 47 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
48 screening-48 screening Cotest-negative HPV-negative NILM 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 48 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
49 screening-49 screening Cotest-negative HPV-negative ASC-US 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 49 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
50 screening-50 screening Cotest-negative HPV-negative LSIL 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 50 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
51 screening-51 screening Cotest-negative HPV-negative ASC-H 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 51 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
52 screening-52 screening Cotest-negative HPV-negative AGC 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 52 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
53 screening-53 screening Cotest-negative HPV-negative HSIL+ 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 53 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
54 screening-54 screening Cotest-negative HPV-negative ALL 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 54 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
55 screening-55 screening Cotest-negative HPV-positive NILM 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 55 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
56 screening-56 screening Cotest-negative HPV-positive ASC-US 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 56 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
57 screening-57 screening Cotest-negative HPV-positive LSIL 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 57 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
58 screening-58 screening Cotest-negative HPV-positive ASC-H 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 58 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
59 screening-59 screening Cotest-negative HPV-positive AGC 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 59 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
60 screening-60 screening Cotest-negative HPV-positive HSIL+ 1 1 1-General_Table_for_Screening_locked.xlsx Sheet1 60 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
61 screening-61 screening Cotest-negative HPV16+ NILM 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 61 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
62 screening-62 screening Cotest-negative HPV16+ ASC-US 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 62 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
63 screening-63 screening Cotest-negative HPV16+ LSIL 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 63 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
64 screening-64 screening Cotest-negative HPV16+ High Grade 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 64 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
65 screening-65 screening Cotest-negative HPV16-, HPV18+ NILM 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 65 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
66 screening-66 screening Cotest-negative HPV16-, HPV18+ ASC-US 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 66 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
67 screening-67 screening Cotest-negative HPV16-, HPV18+ LSIL 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 67 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
68 screening-68 screening Cotest-negative HPV16-, HPV18+ High Grade 1 0 1-General_Table_for_Screening_locked.xlsx Sheet1 68 c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb
69 surveillance-2 surveillance HPV-positive/NILM HPV-negative NILM 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 2 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
70 surveillance-3 surveillance HPV-positive/NILM HPV-negative ASC-US 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 3 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
71 surveillance-4 surveillance HPV-positive/NILM HPV-negative LSIL 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 4 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
72 surveillance-5 surveillance HPV-positive/NILM HPV-negative ASC-H 0 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 5 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
73 surveillance-6 surveillance HPV-positive/NILM HPV-negative AGC 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 6 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
74 surveillance-7 surveillance HPV-positive/NILM HPV-negative HSIL+ 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 7 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
75 surveillance-8 surveillance HPV-positive/NILM HPV-negative ALL 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 8 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
76 surveillance-9 surveillance HPV-positive/NILM HPV-positive NILM 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 9 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
77 surveillance-10 surveillance HPV-positive/NILM HPV-positive ASC-US 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 10 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
78 surveillance-11 surveillance HPV-positive/NILM HPV-positive LSIL 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 11 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
79 surveillance-12 surveillance HPV-positive/NILM HPV-positive ASC-H 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 12 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
80 surveillance-13 surveillance HPV-positive/NILM HPV-positive AGC 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 13 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
81 surveillance-14 surveillance HPV-positive/NILM HPV-positive HSIL+ 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 14 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
82 surveillance-15 surveillance HPV-negative/LSIL HPV-negative NILM 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 15 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
83 surveillance-16 surveillance HPV-negative/LSIL HPV-negative ASC-US 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 16 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
84 surveillance-17 surveillance HPV-negative/LSIL HPV-negative LSIL 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 17 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
85 surveillance-18 surveillance HPV-negative/LSIL HPV-negative ASC-H 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 18 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
86 surveillance-19 surveillance HPV-negative/LSIL HPV-negative AGC 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 19 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
87 surveillance-20 surveillance HPV-negative/LSIL HPV-negative HSIL+ 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 20 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
88 surveillance-21 surveillance HPV-negative/LSIL HPV-positive NILM 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 21 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
89 surveillance-22 surveillance HPV-negative/LSIL HPV-positive ASC-US 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 22 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
90 surveillance-23 surveillance HPV-negative/LSIL HPV-positive LSIL 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 23 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
91 surveillance-24 surveillance HPV-negative/LSIL HPV-positive ASC-H 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 24 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
92 surveillance-25 surveillance HPV-negative/LSIL HPV-positive AGC 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 25 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
93 surveillance-26 surveillance HPV-negative/LSIL HPV-positive HSIL+ 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 26 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
94 surveillance-27 surveillance HPV-negative/ASC-US HPV-negative NILM 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 27 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
95 surveillance-28 surveillance HPV-negative/ASC-US HPV-negative ASC-US 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 28 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
96 surveillance-29 surveillance HPV-negative/ASC-US HPV-negative LSIL 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 29 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
97 surveillance-30 surveillance HPV-negative/ASC-US HPV-negative ASC-H 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 30 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
98 surveillance-31 surveillance HPV-negative/ASC-US HPV-negative AGC 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 31 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
99 surveillance-32 surveillance HPV-negative/ASC-US HPV-negative HSIL+ 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 32 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
100 surveillance-33 surveillance HPV-negative/ASC-US HPV-positive NILM 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 33 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
101 surveillance-34 surveillance HPV-negative/ASC-US HPV-positive ASC-US 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 34 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
102 surveillance-35 surveillance HPV-negative/ASC-US HPV-positive LSIL 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 35 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
103 surveillance-36 surveillance HPV-negative/ASC-US HPV-positive ASC-H 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 36 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
104 surveillance-37 surveillance HPV-negative/ASC-US HPV-positive AGC 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 37 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
105 surveillance-38 surveillance HPV-negative/ASC-US HPV-positive HSIL+ 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 38 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
106 surveillance-39 surveillance HPV-positive/NILM Cotest-negative HPV-negative NILM 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 39 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
107 surveillance-40 surveillance HPV-positive/NILM Cotest-negative HPV-positive NILM 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 40 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
108 surveillance-41 surveillance HPV-positive/NILM Cotest-negative HPV-positive ASC-US/LSIL 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 41 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
109 surveillance-42 surveillance HPV-positive/NILM Cotest-negative HPV-positive High Grade 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 42 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
110 surveillance-43 surveillance HPV-positive/NILM HPV-negative HPV-negative ALL 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 43 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
111 surveillance-44 surveillance HPV-positive/NILM HPV-negative HPV-positive NILM 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 44 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
112 surveillance-45 surveillance HPV-positive/NILM HPV-negative HPV-positive ASC-US/LSIL 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 45 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
113 surveillance-46 surveillance HPV-positive/NILM HPV-negative HPV-positive High Grade 1 1 2-General_Table_for_Surveillance_locked.xlsx Sheet1 46 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
114 surveillance-47 surveillance HPV-positive/NILM HPV16+ NILM 1 0 2-General_Table_for_Surveillance_locked.xlsx Sheet1 47 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
115 surveillance-48 surveillance HPV-positive/NILM HPV16+ ASC-US 1 0 2-General_Table_for_Surveillance_locked.xlsx Sheet1 48 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
116 surveillance-49 surveillance HPV-positive/NILM HPV16+ LSIL 1 0 2-General_Table_for_Surveillance_locked.xlsx Sheet1 49 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
117 surveillance-50 surveillance HPV-positive/NILM HPV16+ High Grade 1 0 2-General_Table_for_Surveillance_locked.xlsx Sheet1 50 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
118 surveillance-51 surveillance HPV-positive/NILM HPV16-, HPV18+ NILM 1 0 2-General_Table_for_Surveillance_locked.xlsx Sheet1 51 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
119 surveillance-52 surveillance HPV-positive/NILM HPV16-, HPV18+ ASC-US 1 0 2-General_Table_for_Surveillance_locked.xlsx Sheet1 52 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
120 surveillance-53 surveillance HPV-positive/NILM HPV16-, HPV18+ LSIL 1 0 2-General_Table_for_Surveillance_locked.xlsx Sheet1 53 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
121 surveillance-54 surveillance HPV-positive/NILM HPV16-, HPV18+ High Grade 1 0 2-General_Table_for_Surveillance_locked.xlsx Sheet1 54 96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b
122 colposcopy_results-2 colposcopy_results HPV-positive NILM x2 <CIN1 1 1 3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx Sheet2 2 2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
123 colposcopy_results-3 colposcopy_results HPV-positive ASC-US <CIN1 1 1 3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx Sheet2 3 2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
124 colposcopy_results-4 colposcopy_results HPV-positive LSIL <CIN1 1 1 3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx Sheet2 4 2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
125 colposcopy_results-5 colposcopy_results ASC-H <CIN1 1 1 3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx Sheet2 5 2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
126 colposcopy_results-6 colposcopy_results AGC <CIN1 1 1 3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx Sheet2 6 2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
127 colposcopy_results-7 colposcopy_results HSIL+ <CIN1 1 1 3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx Sheet2 7 2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
128 colposcopy_results-8 colposcopy_results HPV-positive NILM x2 CIN1 1 1 3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx Sheet2 8 2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
129 colposcopy_results-9 colposcopy_results HPV-positive ASC-US CIN1 1 1 3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx Sheet2 9 2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
130 colposcopy_results-10 colposcopy_results HPV-positive LSIL CIN1 1 1 3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx Sheet2 10 2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
131 colposcopy_results-11 colposcopy_results ASC-H CIN1 1 1 3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx Sheet2 11 2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
132 colposcopy_results-12 colposcopy_results AGC CIN1 1 1 3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx Sheet2 12 2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
133 colposcopy_results-13 colposcopy_results HSIL+ CIN1 1 1 3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx Sheet2 13 2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
134 colposcopy_results-14 colposcopy_results CIN2 0 1 3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx Sheet2 14 2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
135 colposcopy_results-15 colposcopy_results CIN3 0 1 3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx Sheet2 15 2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
136 colposcopy_results-16 colposcopy_results AIS 0 1 3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx Sheet2 16 2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
137 colposcopy_results-17 colposcopy_results Cancer 0 1 3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx Sheet2 17 2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6
138 post_colposcopy-2 post_colposcopy HPV-negative NILM Low Grade 1 1 4-General_Table_for_Post-Colpo.xlsx Sheet1 2 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
139 post_colposcopy-3 post_colposcopy HPV-negative ASC-US/LSIL Low Grade 1 1 4-General_Table_for_Post-Colpo.xlsx Sheet1 3 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
140 post_colposcopy-4 post_colposcopy HPV-positive NILM Low Grade 1 1 4-General_Table_for_Post-Colpo.xlsx Sheet1 4 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
141 post_colposcopy-5 post_colposcopy HPV-positive ASC-US/LSIL Low Grade 1 1 4-General_Table_for_Post-Colpo.xlsx Sheet1 5 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
142 post_colposcopy-6 post_colposcopy HPV-negative High Grade Low Grade 1 1 4-General_Table_for_Post-Colpo.xlsx Sheet1 6 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
143 post_colposcopy-7 post_colposcopy HPV-positive High Grade Low Grade 1 1 4-General_Table_for_Post-Colpo.xlsx Sheet1 7 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
144 post_colposcopy-8 post_colposcopy HPV-negative NILM High Grade 1 1 4-General_Table_for_Post-Colpo.xlsx Sheet1 8 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
145 post_colposcopy-9 post_colposcopy HPV-negative ASC-US/LSIL High Grade 1 1 4-General_Table_for_Post-Colpo.xlsx Sheet1 9 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
146 post_colposcopy-10 post_colposcopy HPV-positive NILM High Grade 1 1 4-General_Table_for_Post-Colpo.xlsx Sheet1 10 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
147 post_colposcopy-11 post_colposcopy HPV-positive ASC-US/LSIL High Grade 1 1 4-General_Table_for_Post-Colpo.xlsx Sheet1 11 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
148 post_colposcopy-12 post_colposcopy HPV-negative High Grade High Grade 1 1 4-General_Table_for_Post-Colpo.xlsx Sheet1 12 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
149 post_colposcopy-13 post_colposcopy HPV-positive High Grade High Grade 1 1 4-General_Table_for_Post-Colpo.xlsx Sheet1 13 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
150 post_colposcopy-14 post_colposcopy HPV-negative ALL Low Grade 1 1 4-General_Table_for_Post-Colpo.xlsx Sheet1 14 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
151 post_colposcopy-15 post_colposcopy HPV-negative ALL High Grade 1 1 4-General_Table_for_Post-Colpo.xlsx Sheet1 15 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
152 post_colposcopy-16 post_colposcopy HPV-negative NILM Low Grade Cotest-negative 1 0 4-General_Table_for_Post-Colpo.xlsx Sheet1 16 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
153 post_colposcopy-17 post_colposcopy HPV-negative NILM High Grade Cotest-negative 1 0 4-General_Table_for_Post-Colpo.xlsx Sheet1 17 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
154 post_colposcopy-18 post_colposcopy HPV-negative ALL Low Grade HPV-negative 1 0 4-General_Table_for_Post-Colpo.xlsx Sheet1 18 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
155 post_colposcopy-19 post_colposcopy HPV-negative ALL High Grade HPV-negative 1 0 4-General_Table_for_Post-Colpo.xlsx Sheet1 19 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
156 post_colposcopy-20 post_colposcopy HPV-negative ASC-US/LSIL Low Grade Cotest-negative 1 0 4-General_Table_for_Post-Colpo.xlsx Sheet1 20 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
157 post_colposcopy-21 post_colposcopy HPV-positive NILM Low Grade Cotest-negative 1 0 4-General_Table_for_Post-Colpo.xlsx Sheet1 21 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
158 post_colposcopy-22 post_colposcopy HPV-positive ASC-US/LSIL Low Grade Cotest-negative 1 0 4-General_Table_for_Post-Colpo.xlsx Sheet1 22 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
159 post_colposcopy-23 post_colposcopy HPV-negative High Grade Low Grade Cotest-negative 1 0 4-General_Table_for_Post-Colpo.xlsx Sheet1 23 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
160 post_colposcopy-24 post_colposcopy HPV-positive High Grade Low Grade Cotest-negative 1 0 4-General_Table_for_Post-Colpo.xlsx Sheet1 24 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
161 post_colposcopy-25 post_colposcopy HPV-negative ASC-US/LSIL High Grade Cotest-negative 1 0 4-General_Table_for_Post-Colpo.xlsx Sheet1 25 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
162 post_colposcopy-26 post_colposcopy HPV-positive NILM High Grade Cotest-negative 1 0 4-General_Table_for_Post-Colpo.xlsx Sheet1 26 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
163 post_colposcopy-27 post_colposcopy HPV-positive ASC-US/LSIL High Grade Cotest-negative 1 0 4-General_Table_for_Post-Colpo.xlsx Sheet1 27 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
164 post_colposcopy-28 post_colposcopy HPV-negative NILM Low Grade HPV-negative/ASC-US/LSIL 1 0 4-General_Table_for_Post-Colpo.xlsx Sheet1 28 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
165 post_colposcopy-29 post_colposcopy HPV-negative ASC-US/LSIL Low Grade HPV-negative/ASC-US/LSIL 1 0 4-General_Table_for_Post-Colpo.xlsx Sheet1 29 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
166 post_colposcopy-30 post_colposcopy HPV-negative ALL High Grade HPV-negative x2 1 0 4-General_Table_for_Post-Colpo.xlsx Sheet1 30 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
167 post_colposcopy-31 post_colposcopy HPV-negative ALL Low Grade HPV-negative x2 1 0 4-General_Table_for_Post-Colpo.xlsx Sheet1 31 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
168 post_colposcopy-32 post_colposcopy HPV-negative NILM Low Grade Cotest-negative x2 1 0 4-General_Table_for_Post-Colpo.xlsx Sheet1 32 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
169 post_colposcopy-33 post_colposcopy HPV-negative NILM High Grade Cotest-negative x2 1 0 4-General_Table_for_Post-Colpo.xlsx Sheet1 33 2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b
170 post_treatment-2 post_treatment HPV-negative NILM CIN3 1 0 5-General_Table_for_Post-Treatment_locked.xlsx Sheet1 2 b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
171 post_treatment-3 post_treatment HPV-negative ASC-US/LSIL CIN3 1 0 5-General_Table_for_Post-Treatment_locked.xlsx Sheet1 3 b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
172 post_treatment-4 post_treatment HPV-positive NILM CIN3 1 0 5-General_Table_for_Post-Treatment_locked.xlsx Sheet1 4 b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
173 post_treatment-5 post_treatment HPV-positive ASC-US/LSIL CIN3 1 0 5-General_Table_for_Post-Treatment_locked.xlsx Sheet1 5 b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
174 post_treatment-6 post_treatment HPV-negative High Grade CIN3 1 0 5-General_Table_for_Post-Treatment_locked.xlsx Sheet1 6 b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
175 post_treatment-7 post_treatment HPV-positive High Grade CIN3 1 0 5-General_Table_for_Post-Treatment_locked.xlsx Sheet1 7 b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
176 post_treatment-8 post_treatment HPV-negative ALL CIN3 1 0 5-General_Table_for_Post-Treatment_locked.xlsx Sheet1 8 b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
177 post_treatment-9 post_treatment HPV-negative x2 CIN3 1 0 5-General_Table_for_Post-Treatment_locked.xlsx Sheet1 9 b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
178 post_treatment-10 post_treatment Cotest-negative x2 CIN3 1 0 5-General_Table_for_Post-Treatment_locked.xlsx Sheet1 10 b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
179 post_treatment-11 post_treatment HPV-negative x3 CIN3 1 0 5-General_Table_for_Post-Treatment_locked.xlsx Sheet1 11 b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
180 post_treatment-12 post_treatment Cotest-negative x3 CIN3 1 0 5-General_Table_for_Post-Treatment_locked.xlsx Sheet1 12 b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc
+19
View File
@@ -0,0 +1,19 @@
"""Compatibility for databases built before the second-cytology column existed."""
from sqlalchemy import inspect
def has_postcolposcopy_cytology(con, relation: str) -> bool:
return any(
c["name"] == "first_postcolposcopy_cytology"
for c in inspect(con).get_columns(relation, schema="gold")
)
def postcolposcopy_cytology(alias: str) -> str:
"""Same derivation as cacu_follow_up; no inference from a colposcopy alone."""
return (
"(select min(e.date) from gold.cacu_events as e "
f"where e.person_id = {alias}.person_id and e.type = 'cytology' "
f"and e.date > {alias}.first_colposcopy)"
)
+102 -5
View File
@@ -6,6 +6,7 @@ from datetime import date
from sqlalchemy import bindparam, inspect, text
from core import catalog
from persistance.cacu_compat import has_postcolposcopy_cytology, postcolposcopy_cytology
from persistance.destination import engine
PERSONS = """
@@ -15,7 +16,8 @@ PERSONS = """
group by person_id) as d on d.person_id = p.person_id{join}
"""
CACU_PERSONS = PERSONS.format(
extra=", f.first_case, f.first_treatment, f.first_colposcopy",
extra=", f.first_case, f.first_treatment, f.first_colposcopy, f.first_hysterectomy, "
"f.first_postcolposcopy_cytology",
join=" left join gold.cacu_follow_up as f on f.person_id = p.person_id",
)
CAMA_PERSONS = PERSONS.format(extra="", join="")
@@ -43,6 +45,12 @@ COMMON = {
where person_id in :persons and date <= :cutoff and type in :types
order by person_id, date, type
""",
# Biopsies and treatments, which say whether a model's risk still applies.
"risk_history": """
select person_id, date, type, value_code from gold.{domain}_events
where person_id in :persons and type in ('biopsy', 'treatment')
order by person_id, date
""",
"risk": """
select model, version, person_id, index_date, horizon_years, probability, ci_low,
ci_high, scenarios, scored_at
@@ -67,7 +75,8 @@ READS = {
order by w.recent desc, x.person_id
""",
# What followed each sample by the cut-off (gold): her colposcopy, her biopsy (its first
# request, and its report) and her diagnosis, with the days to it.
# request, and its report) and her diagnosis, with the days to it, and what shows where
# each stage comes from (core.cacu.stages).
"route": """
select s.person_id, s.sample_date,
case when s.history = 0 and s.diagnosis_date <= :cutoff
@@ -75,15 +84,77 @@ READS = {
case when s.diagnosis_date <= :cutoff then s.diagnosis_date end as diagnosis,
case when s.colposcopy_date <= :cutoff then s.colposcopy_date end as colposcopy,
case when s.biopsy_date <= :cutoff then s.biopsy_date end as biopsy,
b.requested, b.link
b.requested, b.link, b.reported, b.backwards,
case when exists (select 1 from gold.cacu_events as e
where e.person_id = s.person_id and e.type = 'colposcopy'
and e.date = s.colposcopy_date
and e.source_table = 'clinical_note')
then 1 else 0 end as colposcopy_note,
case when exists (select 1 from gold.cacu_events as e
where e.person_id = s.person_id and e.type = 'colposcopy'
and e.date = s.colposcopy_date
and e.source_table = 'cervical_biopsy')
then 1 else 0 end as colposcopy_biopsy,
case when exists (select 1 from gold.cacu_events as e
where e.person_id = s.person_id and e.type = 'diagnosis'
and e.date = s.diagnosis_date
and e.source_table = 'clinical_note')
then 1 else 0 end as diagnosis_note
from gold.cacu_samples as s
left join (select person_id, sample_date, min(date) as requested, min(link) as link
left join (select person_id, sample_date, min(date) as requested, min(link) as link,
min(case when report_date <= :cutoff
then report_date end) as reported,
max(case when report_date <= :cutoff and report_date < date
then 1 else 0 end) as backwards
from gold.cacu_procedures
where type = 'biopsy' and date <= :cutoff and person_id in :persons
group by person_id, sample_date) as b
on b.person_id = s.person_id and b.sample_date = s.sample_date
where s.person_id in :persons
""",
# What the NCI reference comparison reads of one patient (core.cacu.reference_risk), all of
# it from gold: her
# cytologies, her biopsies with the sample that led to each (gold.cacu_procedures: the one
# the record names, else the one inferred in time), and her colposcopies and treatments.
"reference_master": """
select l.row_id, l.scenario, l.asked_cytology, l.matched_via, l.history, l.hpv,
l.referral, l.biopsy, l.book, l.source_sha256, l.sheet, l.source_row,
l.published,
e.outcome, e.horizon_years, e.risk, e.risk_percent, e.lower, e.upper,
l.previous_two, l.pre_colposcopy, l.post_colposcopy_history
from gold.nci_risk_lookup as l
join gold.nci_risk_estimate as e on e.row_id = l.row_id
order by l.row_id, l.asked_cytology, e.outcome, e.horizon_years
""",
"reference_cytologies": """
select person_id, sample_date, report_date, finding as result, adequacy, hpv, hpv_16,
hpv_18, gynecologic_condition, valid
from gold.cacu_samples where person_id in :persons
order by person_id, sample_date
""",
"reference_biopsies": """
select person_id, date as request_date, report_date, histology,
sample_date as cytology_sample_date
from gold.cacu_procedures where type = 'biopsy' and person_id in :persons
order by person_id, date
""",
# what the NCI books require of each sample (gold.cacu_eligibility)
"reference_requirements": """
select person_id, index_date as sample_date, scenario, criterion
from gold.cacu_eligibility
where scenario like 'nci_%' and person_id in :persons
order by person_id, index_date, scenario, criterion
""",
"reference_events": """
select distinct e.person_id, e.date, e.type,
f.treated_biopsy_request_date as biopsy_request_date
from gold.cacu_events as e
left join gold.cacu_follow_up as f
on e.type = 'treatment' and f.person_id = e.person_id
and f.first_treatment = e.date
where e.person_id in :persons and e.type in ('colposcopy', 'treatment')
order by e.person_id, e.date, e.type
""",
},
"tea": {
"person": TEA_PERSONS + " where p.person_id = :id",
@@ -154,7 +225,26 @@ READS = {
def rows(domain: str, kind: str, **params) -> list[dict]:
"""The rows of one kind for the domain. `persons` (and `types`) limit them to those;
none when the table doesn't exist yet (no risk batch)."""
sql = text((READS.get(domain, {}).get(kind) or COMMON[kind]).replace("{domain}", domain))
query = (READS.get(domain, {}).get(kind) or COMMON[kind]).replace("{domain}", domain)
with engine().connect() as con:
if (
domain == "cacu"
and kind in {"person", "persons", "follow_up"}
and not has_postcolposcopy_cytology(con, "cacu_follow_up")
):
query = query.replace(
"f.first_postcolposcopy_cytology",
postcolposcopy_cytology("f") + " as first_postcolposcopy_cytology",
)
if kind == "risk" and not inspect(con).has_table(f"{domain}_risk", schema="gold"):
return []
if kind == "risk" and domain == "cacu":
names = {c["name"] for c in inspect(con).get_columns("cacu_risk", schema="gold")}
field = "input_values" if "input_values" in names else "null as input_values"
query = query.replace(
"ci_high, scenarios, scored_at", f"ci_high, scenarios, {field}, scored_at"
)
sql = text(query)
for many in ("persons", "types"):
if many in params:
sql = sql.bindparams(bindparam(many, expanding=True))
@@ -163,6 +253,13 @@ def rows(domain: str, kind: str, **params) -> list[dict]:
with engine().connect() as con:
if kind == "risk" and not inspect(con).has_table(f"{domain}_risk", schema="gold"):
return []
# gold built before the official NCI tables: the reference says it has no tables
if kind == "reference_master" and not (
inspect(con).has_table("nci_risk_estimate", schema="gold")
and "lower"
in {c["name"] for c in inspect(con).get_columns("nci_risk_estimate", schema="gold")}
):
return []
return [dict(r) for r in con.execute(sql, params).mappings()]
+153 -2
View File
@@ -1,21 +1,60 @@
"""What the models read from gold, and the risk batches they write back."""
from collections.abc import Sequence
from datetime import UTC, date, datetime
import dlt
import pandas as pd
from sqlalchemy import inspect, text
from core.cacu import SECOND_VISIT_FIELDS
from persistance.destination import engine, platform
TIMELINE = ["person_id", "index_date", "date", "type", "value_code", "value_num",
"source_table", "source_id", "record_number"] # fmt: skip
SECOND_VISIT_KEYS = (
"person_id", "scenario", "index_date", "index_sample_id", "previous_date",
"previous_sample_id", "data_cutoff", "excluded_by", "index_result_date",
) # fmt: skip
SECOND_VISIT_PREDICTORS = tuple(
f"{visit}_{field}" for visit in ("previous", "index") for field in SECOND_VISIT_FIELDS
)
CACU_ELIGIBILITY_COLUMNS = {
"scenario",
"person_id",
"index_date",
"index_sample_id",
"criterion",
"eligible",
}
class GoldSchemaError(RuntimeError):
"""Gold has not been updated to the schema required by a CaCu reader."""
def timelines(events: str, cohort: str, as_of: date | None = None) -> pd.DataFrame:
"""The events (`gold.<events>`) up to `as_of` (default: today) of every member of
`gold.<cohort>`, each with her index date and her record number (the lowest of the
hospital's numbers for her: a deterministic order among patients), in date order."""
hospital's numbers for her: a deterministic order among patients), in date order. A
cohort that grades the referral adds it as a `referral_grade` event at the colposcopy."""
with engine().connect() as con:
columns = con.execute(text(f"select * from gold.{cohort} limit 0")).keys()
referral = (
f"""
union all
select c.person_id, c.index_date, c.colposcopy_date, 'referral_grade', c.referral_grade,
null, 'cacu_procedures', cast(c.colposcopy_date as text), n.record_number
from gold.{cohort} as c
left join (select person_id, min(record_number) as record_number
from bronze.staged__identity group by person_id) as n
on n.person_id = c.person_id
where c.excluded_by is null and c.referral_grade is not null
and c.colposcopy_date <= :as_of
"""
if "referral_grade" in columns
else ""
)
sql = text(f"""
select e.person_id, c.index_date, e.date, e.type, e.value_code, e.value_num,
e.source_table, e.source_id, n.record_number
@@ -24,12 +63,50 @@ def timelines(events: str, cohort: str, as_of: date | None = None) -> pd.DataFra
left join (select person_id, min(record_number) as record_number
from bronze.staged__identity group by person_id) as n
on n.person_id = e.person_id
where c.excluded_by is null and e.date <= :as_of {referral}
order by 1, 3, 7, 8
""") # fmt: skip
with engine().connect() as con:
found = pd.read_sql(sql, con, params={"as_of": (as_of or date.today()).isoformat()})
return found.astype({"value_num": float})[TIMELINE]
def evidence_timelines(events: str, cohort: str, as_of: date | None = None) -> pd.DataFrame:
"""`timelines`' events with each one's clinical and availability dates
(`evidence_date`, `source_available_at`), for what must read only what was available
at the index (models.cacu.encoders)."""
sql = text(f"""
select e.person_id, c.index_date, e.date, e.type, e.value_code, e.value_num,
e.source_table, e.source_id, e.evidence_date, e.source_available_at
from gold.{events} as e
join gold.{cohort} as c on c.person_id = e.person_id
where c.excluded_by is null and e.date <= :as_of
order by e.person_id, e.date, e.source_table, e.source_id
""") # fmt: skip
with engine().connect() as con:
found = pd.read_sql(sql, con, params={"as_of": (as_of or date.today()).isoformat()})
return found.astype({"value_num": float})[TIMELINE]
return found.astype({"value_num": float})
def cervical_forms(cohort: str) -> pd.DataFrame:
"""The cytology forms (`silver.cervical_cytology`, one row per sample) of every member
of `gold.<cohort>`, whole: the reader decides what each index may see."""
sql = text(f"""
select s.*
from silver.cervical_cytology as s
join (select distinct person_id from gold.{cohort} where excluded_by is null) as c
on c.person_id = s.person_id
order by s.person_id, s.sample_date
""") # fmt: skip
with engine().connect() as con:
return pd.read_sql(sql, con)
def people(events: str, as_of: date) -> int:
"""How many people have any event in `gold.<events>` up to `as_of`."""
sql = text(f"select count(distinct person_id) from gold.{events} where date <= :as_of")
with engine().connect() as con:
return con.execute(sql, {"as_of": as_of.isoformat()}).scalar_one()
def person_numbers() -> dict[str, str]:
@@ -40,6 +117,79 @@ def person_numbers() -> dict[str, str]:
return dict(con.execute(sql).fetchall())
def cacu_second_visit_features(
scenario: str,
person_id: str | None = None,
*,
predictors: Sequence[str] | None = None,
include_excluded: bool = False,
) -> pd.DataFrame:
"""Read the requested predictors plus row keys for a cohort or one candidate."""
chosen = SECOND_VISIT_PREDICTORS if predictors is None else tuple(dict.fromkeys(predictors))
unknown = set(chosen).difference(SECOND_VISIT_PREDICTORS)
if unknown:
raise ValueError(f"Unknown CaCu predictors: {', '.join(sorted(unknown))}")
columns = ", ".join((*SECOND_VISIT_KEYS, *chosen))
person_filter = "and person_id = :person_id" if person_id is not None else ""
eligibility_filter = "" if include_excluded else "and excluded_by is null"
sql = text(f"""
select {columns} from gold.cacu_second_visit_features
where scenario = :scenario {person_filter} {eligibility_filter}
order by person_id
""")
with engine().connect() as con:
return pd.read_sql(sql, con, params={"scenario": scenario, "person_id": person_id})
def cacu_eligibility_report(
scenario: str | None = None,
person_id: str | None = None,
*,
cutoff: date | None = None,
) -> pd.DataFrame:
"""Candidates and every exclusion reason detected for their indexed visit.
Eligible candidates have one row with a null `criterion`; candidates with multiple
reasons have one row per reason. The required relation and columns are checked before
querying so an old gold installation gets an actionable error rather than SQL failure.
"""
with engine().connect() as con:
inspector = inspect(con)
relation = "cacu_eligibility"
if not inspector.has_table(relation, schema="gold"):
raise GoldSchemaError(
"CaCu eligibility gold is not materialized; rebuild gold.cacu_eligibility."
)
found = {column["name"] for column in inspector.get_columns(relation, schema="gold")}
missing = CACU_ELIGIBILITY_COLUMNS.difference(found)
if missing:
names = ", ".join(sorted(missing))
raise GoldSchemaError(
f"CaCu eligibility gold schema is outdated (missing {names}); "
"rebuild gold.cacu_eligibility."
)
filters = []
params = {}
if scenario is not None:
filters.append("scenario = :scenario")
params["scenario"] = scenario
else: # the NCI reference's rows, one per sample, only when asked for by name
filters.append("scenario not like 'nci\\_%' escape '\\'")
if person_id is not None:
filters.append("person_id = :person_id")
params["person_id"] = person_id
if cutoff is not None:
filters.append("index_date <= :cutoff")
params["cutoff"] = cutoff.isoformat()
where = f"where {' and '.join(filters)}" if filters else ""
sql = text(f"""
select scenario, person_id, index_date, index_sample_id, criterion, eligible
from gold.{relation} {where}
order by scenario, person_id, index_date, index_sample_id, criterion
""")
return pd.read_sql(sql, con, params=params)
SCORES = "model_scores"
@@ -54,5 +204,6 @@ def save_scores(model: str, version: int, scores: pd.DataFrame) -> None:
columns={"ci_low": {"data_type": "double", "nullable": True},
"ci_high": {"data_type": "double", "nullable": True},
"scenarios": {"data_type": "text", "nullable": True},
"input_values": {"data_type": "text", "nullable": True},
"index_date": {"data_type": "date"}}) # fmt: skip
dlt.pipeline(SCORES, destination=platform(), dataset_name="bronze").run(resource)
+66 -3
View File
@@ -3,6 +3,7 @@ measure gives (`Measure.rows`)."""
from sqlalchemy import inspect, text
from persistance.cacu_compat import has_postcolposcopy_cytology, postcolposcopy_cytology
from persistance.destination import engine
READS = {
@@ -14,9 +15,10 @@ READS = {
left join gold.cacu_sample_biopsies as b on b.sample_id = s.sample_id
""",
"procedures": """
select p.*, s.result, s.hpv, s.hpv_16, s.hpv_18, s.screening_history,
select p.*, s.result, s.hpv, s.hpv_16, s.hpv_18, s.screening_history, s.detection,
s.report_known_at as cytology_known_at,
f.first_case, f.first_treatment, f.first_colposcopy
f.first_case, f.first_treatment, f.first_colposcopy,
f.first_postcolposcopy_cytology
from gold.cacu_procedures as p
left join gold.cacu_samples as s
on s.person_id = p.person_id and s.sample_date = p.sample_date
@@ -33,8 +35,37 @@ READS = {
},
"cama": {
"mammograms": "select * from gold.cama_mammograms",
"diagnosis_treatment": "select * from gold.cama_mammograms",
"biopsies": "select * from gold.cama_biopsies where report_date is not null",
# An event names a biopsy by person and request date. If several biopsies share that
# key, or several matching type events exist, the event cannot be assigned safely.
"biopsy_types": """
with biopsy_keys as (
select person_id, request_date, count(*) as n
from gold.cama_biopsies group by person_id, request_date
), type_events as (
select person_id, source_id, date, count(*) as n, min(value_code) as value_code
from gold.cama_events
where type = 'histologic_type' and source_table = 'breast_biopsy'
group by person_id, source_id, date
)
select b.*, case when k.n = 1 and e.n = 1 then e.value_code end as histologic_type
from gold.cama_biopsies as b
join biopsy_keys as k on k.person_id = b.person_id and k.request_date = b.request_date
left join type_events as e on e.person_id = b.person_id
and e.source_id = cast(b.request_date as varchar(10)) and e.date = b.report_date
where b.report_date is not null
""",
"mammogram_biopsies": "select * from gold.cama_mammogram_biopsies",
# One row per mammogram: its first reported biopsy (ties: the lowest id), or the row
# with none. The biopsy is the one whose request names the mammogram.
"mammogram_first_biopsy": """
select * from (
select *, row_number() over (
partition by mammogram_id order by biopsy_report_date, biopsy_id) as nth
from gold.cama_mammogram_biopsies
) as x where nth = 1
""",
},
"tea": {
"screening": "select * from gold.tea_screening",
@@ -42,10 +73,42 @@ READS = {
},
}
# Keep the mammogram-to-biopsy link already materialized in gold. A missing or ambiguous type
# stays null; the biopsy's own classification and selection rules remain unchanged.
READS["cama"]["mammogram_biopsy_types"] = f"""
with biopsy_types as ({READS["cama"]["biopsy_types"]})
select mb.*, bt.histologic_type
from gold.cama_mammogram_biopsies as mb
left join biopsy_types as bt on bt.biopsy_id = mb.biopsy_id
"""
def rows(domain: str, kind: str, **params) -> list[dict]:
"""The rows of one kind; none while their tables don't exist (no risk batch yet)."""
with engine().connect() as con:
if kind == "risk" and not inspect(con).has_table(f"{domain}_risk", schema="gold"):
return []
return [dict(r) for r in con.execute(text(READS[domain][kind]), params).mappings()]
query = READS[domain][kind]
if (
domain == "cacu"
and kind == "procedures"
and not has_postcolposcopy_cytology(con, "cacu_follow_up")
):
query = query.replace(
"f.first_postcolposcopy_cytology",
postcolposcopy_cytology("f") + " as first_postcolposcopy_cytology",
)
if (
domain == "cacu"
and kind in {"samples", "sample_biopsies"}
and not has_postcolposcopy_cytology(con, "cacu_samples")
):
field = postcolposcopy_cytology("s") + " as first_postcolposcopy_cytology"
if kind == "samples":
query = query.replace(
"select * from gold.cacu_samples",
f"select s.*, {field} from gold.cacu_samples as s",
)
else:
query = query.replace("select s.*,", f"select s.*, {field},")
return [dict(r) for r in con.execute(text(query), params).mappings()]
+8
View File
@@ -17,6 +17,12 @@ from core.pipeline import HELD, QUOTES, RECORD
from core.schema import IDENTIFIER_SYSTEMS, RECORD_NUMBER_SYSTEM, Identity
from persistance.config import DBT_DIR
# Reference tables have no silver parents; include them in ingest and rebuild explicitly.
NCI_REFERENCES = (
"+nci_risk_lookup",
"nci_risk_estimate",
)
_DLT_TYPES = {date: "date", bool: "bool", float: "double", int: "bigint"}
@@ -35,6 +41,8 @@ OBSERVATION = {
"value_num": {"data_type": "double", "nullable": True},
"value_bool": {"data_type": "bool", "nullable": True},
"value_date": {"data_type": "date", "nullable": True},
"source_clinical_date": {"data_type": "date", "nullable": True},
"source_available_at": _text(), "source_ref": _text(),
**_BOOKKEEPING,
} # fmt: skip
# One row per held record of a study: why, and its values as they came.
+1 -1
Submodule WebApi updated: bd06a31d52...fecf7c9d12
+1 -1
Submodule WebApp updated: fe4dd55452...f92bcd80b9
+29
View File
@@ -0,0 +1,29 @@
# Capas: dónde vive cada regla
- **Plata** guarda hechos: lo que dicen las fuentes, normalizado.
- **Oro** (dbt) es el único lugar donde se decide elegibilidad y se construyen variables clínicas.
- **Python** (Core, modelos, API, web) lee de oro. Busca filas en tablas y presenta; no vuelve a
definir un criterio que oro ya tiene.
Antes de escribir un criterio, buscar si existe:
| Pregunta | Dónde está |
|---|---|
| ¿Cuenta esta citología? | macro `cacu_valid_cytology`, columna `gold.cacu_samples.valid` |
| ¿Qué citología llevó a un procedimiento? | `gold.cacu_procedures` |
| ¿Qué grado tenía la referencia? | macro `cacu_referral_grade` |
| ¿Qué biopsia respondió el tratamiento? | `gold.cacu_follow_up.treated_biopsy_request_date` |
| ¿Qué le falta a una muestra para un libro NCI? | macros `cacu_nci_*` |
| ¿Por qué se excluye una candidata? | `cacu_exclusion_rules`, `cacu_hysterectomy`, `gold.cacu_eligibility` |
Un dato ausente nunca se convierte en negativo.
## Lecturas directas de plata desde Python
`tests/test_layers.py` falla si aparece una nueva. Las que hay son para mostrar el registro de la
paciente, o son deuda por subir a oro (formularios de citología para los modelos). Las tablas NCI
leen sus hechos y sus requisitos de oro (macros `cacu_nci_*`, filas `nci_*` de
`cacu_eligibility`); Python traduce resultados a las categorías de cada libro y busca la fila.
Las series NCI visibles de los libros 1, 4 y 17 reciben los datos de las semillas de oro a través de Persistencia, igual que la maestra. Core reconstruye las filas y selecciona la coincidencia con los hechos y requisitos recibidos; no abre una conexión a la base. Los libros ocultos conservan su lector anterior. Las semillas de libros se generan con `tools/nci_book_seeds.py`.
+92
View File
@@ -0,0 +1,92 @@
# Codificadores binarios de CaCu
`models/models/cacu/encoders.py`: `encode(events, forms)` da una fila por paciente
(`person_id`, `index_date`) y 78 columnas con 1, 0 o NaN (faltante). Ningún modelo las usa:
no cambian predicciones, cohortes ni paridad.
```python
events = gold.evidence_timelines("cacu_events", cohorte, corte)
forms = gold.cervical_forms(cohorte) # sin esto, las columnas del formato salen faltantes
X = encode(events, forms)
```
## Qué se puede leer en la fecha índice
En Gold, `hpv_16_18` solo se publica como negativo cuando se conocen ambos genotipos
negativos; un positivo basta para publicarlo positivo y un negativo con el otro faltante no
produce un resultado combinado. La calidad (`adequacy`) es un evento de la fecha del reporte,
no un valor del evento de toma. Estas reglas no reconstruyen disponibilidad de origen cuando
la fuente no la proporciona; esa incertidumbre queda pendiente de resolver.
- La fecha del evento (en un resultado, la del reporte) y su fecha clínica, si la tiene, no
pasan del índice.
- Si la fuente dio `source_available_at`, su día no pasa del índice. Si no la dio, vale la
fecha del evento; la evidencia independiente de elegibilidad (fechada por su inicio
clínico) se descarta. En esto es más permisivo que las reglas de cohorte, que exigen
`source_available_at` para la histerectomía.
- Biopsias, órdenes, colposcopia, tratamiento, diagnóstico, antecedente e histerectomía:
solo días anteriores al índice (los del mismo día pueden ser el desenlace).
- Los resultados de la muestra índice, reportados después, salen faltantes si el índice es
el día de la toma. Es intencional; los modelos actuales sí los leen (hasta 30 días).
- `known_at` (fecha de carga a la plataforma) no se lee.
## Variables
"Faltante" nunca es 0. En un grupo `x__código`, si hay un valor válido, su columna es 1 y
las demás 0 (0 significa "no fue la opción registrada"); sin valor o con un código fuera
del catálogo, todas faltantes. Las columnas de "solo presencia" valen 1 o faltante.
La cobertura es el % de las 230 pacientes de la referencia `cohorte_total`
(`tests/fixtures/reference`), tomando como índice su último evento. Es una cota optimista
y no describe a la población real ni a los datos del stack, que no se consultaron.
"s/d": esa referencia no trae el campo (no significa que el sitio no lo capture).
| Variable | Columnas | Regla | Fuente | Cobertura |
|---|---|---|---|---|
| Edad | `age__<25`, `25-34`, `35-44`, `45-54`, `55-64`, `≥65` | bandas de `cacu.AGE_GROUPS` | evento `birth` (`silver.person`) | 100 |
| Bethesda | `bethesda__{NILM,ASC-US,ASC-H,LSIL,HSIL,CIS}` | último reporte; el más grave si hay varios ese día | evento `bethesda` | 92 |
| Umbrales de citología | `cytology_{ascus,lsil,hsil}_plus` | `cacu.PROCEDURE_CYTOLOGY` | igual | 92 |
| VPH alto riesgo | `hpv_positive` | último resultado | evento `hpv` | 67 |
| VPH 16, VPH 18 | `hpv_16_positive`, `hpv_18_positive` | último resultado de cada uno | eventos `hpv_16`, `hpv_18` | s/d |
| VPH 16 o 18 | `hpv_16_or_18_positive` | última muestra con genotipo; 0 solo si ambos negativos | igual | s/d |
| Condición ginecoobstétrica | `gynecologic_condition__*` (8) | último valor registrado | formato de citología en `cacu_events` | s/d |
| Síntoma actual | `presenting_symptom__*` (4) | igual | igual | s/d |
| Aspecto del cuello (examen) | `cervix_appearance__{healthy,lesion,not_seen}` | igual | igual | s/d |
| Detección previa declarada | `screening_history__*` (4) | último formato tomado hasta el índice | `silver.cervical_cytology` | s/d |
| Calidad de la muestra | `sample_unsatisfactory` | último reporte | `silver.cervical_cytology.adequacy` | s/d |
| Hallazgos del citólogo | las 27 `finding_*` | último reporte completo; sin mención, faltante | `silver.cervical_cytology` | s/d |
| Citología previa | `prior_cytology_sample` | solo presencia | evento `cytology` | 93 |
| Biopsia solicitada / reportada | `prior_biopsy_order`, `prior_biopsy_report` | solo presencia | `biopsy_order`, `biopsy` | 19 / 12 |
| Peor histología previa | `prior_biopsy_{lsil_plus,hsil_plus,carcinoma}` | 0/1 entre quienes tienen biopsia reportada | `biopsy` | 12 |
| Colposcopia previa | `prior_colposcopy` | solo presencia (inferida de notas y biopsias) | `colposcopy` | 23 |
| Tratamiento previo | `prior_treatment` | solo presencia (inferido de CIE-10 en notas) | `treatment` | 3 |
| Nota de diagnóstico | `prior_diagnosis_note` | solo presencia; incluye códigos de revisión (p. ej. Z014) | `diagnosis` | 51 |
| Antecedente CIE-10 D06/C53 | `history_cancer_icd10` | solo presencia | `history` | 6 |
| Histerectomía | `history_hysterectomy` | solo presencia | formato, notas Z907, evidencia FHIR | s/d |
| Motivo de referencia | `referral_high_grade` | `features._referral_grade`; 1 alto, 0 bajo, faltante sin grado | citología, VPH, colposcopia | 23 |
Con el índice en la fecha de reclutamiento de `cacu_cohort_surveillance` de la referencia
(186 pacientes) solo la edad tiene datos: esa referencia no tiene historia anterior.
## Sin codificador
| Dato | Motivo |
|---|---|
| Glandulares / AGC / adenocarcinoma | Los modelos leen el evento `glandular`, pero ni el catálogo ni `cacu_events` lo producen; `result` tampoco admite AGC. |
| `findings` (texto libre), motivo y diagnóstico de las notas | Texto: codificarlo exigiría inventar categorías. |
| Otros CIE-10 (notas y evidencia `condition`) | No hay agrupación definida en la plataforma. |
| Tipo de tratamiento, márgenes, hallazgos colposcópicos | No existen como campos. |
| Otros genotipos de VPH, carga viral | No existen. |
| Tabaquismo, paridad, inicio de vida sexual, parejas, anticoncepción (salvo DIU y hormonal del formato), vacunación, VIH o inmunosupresión | No existen. |
| Sexo, defunción | El sexo no está en la línea de tiempo; la defunción es desenlace o exclusión. |
## Limitaciones de las fuentes
- `silver.cervical_cytology` no guarda `source_available_at` de `screening_history`,
`adequacy` ni los hallazgos: se usa la fecha de toma (historia) o de reporte (los demás).
- `cacu_events` fecha la calidad de la muestra (evento `cytology`) el día de la toma, aunque
es un dato del reporte. Por eso se lee del formato, con la fecha de reporte.
- El `hpv_16_18` de `cacu_events` vale 0 cuando un genotipo es negativo y el otro no se
reportó. No se usa aquí; los modelos y la vista quedan como estaban.
- Colposcopia, tratamiento y diagnóstico son inferidos, no registros del procedimiento.
- `encode` admite una sola fecha índice por paciente.
+44
View File
@@ -0,0 +1,44 @@
# Fechas, estados FHIR y elegibilidad con información insuficiente
## Fechas de evidencia
El día de la evidencia normalizada es el local de Monterrey (`America/Monterrey`), tanto para la
fecha clínica de un instante con zona como para su disponibilidad (issue #32). Una fecha completa
sin hora conserva su día. Un año, año-mes, fecha inválida o fecha y hora sin zona no identifica un
día verificable: la fuente se guarda sin fecha y gold usa la fecha del evento como respaldo.
## Estados FHIR
`entered-in-error`: no se usa nada del reporte u observación anulados. `preliminary`: se conserva
la toma, sin resultado ni fecha de reporte (pendiente). Falta comprobar que una anulación posterior
retire un resultado ya cargado como final.
## Propuesta: información insuficiente
Actualmente, una evidencia de histerectomía anterior al índice sin disponibilidad de origen no
cumple la condición de exclusión; el candidato puede aparecer elegible. Esa ausencia no demuestra
que la paciente sea elegible. Propuesta, sin activar:
1. Evaluar por candidato y fecha índice: si existe evidencia clínicamente anterior sin fecha de
disponibilidad comprobable, y no hay otro criterio que ya excluya, informar
`insufficient_information`.
2. Mantener `excluded` si existe un criterio de exclusión comprobado y, además, exponer la
incertidumbre como motivo independiente. `eligible` solo cuando los criterios requeridos
puedan evaluarse suficientemente.
3. Extender cada `candidate` de `$eligibility` con `eligibility-status` (`eligible`, `excluded`,
`insufficient_information`) y repetir `uncertainty` con código
`hysterectomy_source_availability_unknown`. Mantener `eligible` por compatibilidad solo tras
definir su versión y transición; un booleano no representa tres estados sin ambigüedad.
Ejemplo del fragmento FHIR propuesto (no publicado por la API actual):
```json
{"name":"candidate","part":[
{"name":"eligibility-status","valueCode":"insufficient_information"},
{"name":"uncertainty","valueCode":"hysterectomy_source_availability_unknown"}
]}
```
Falta decidir qué hacer cuando la fecha clínica también es desconocida y cómo reconciliar
fuentes contradictorias. La cohorte, el reporte de deserción, la predicción y la ficha deben
consumir la misma decisión antes de activar este contrato.
+25
View File
@@ -0,0 +1,25 @@
# Estados y escenarios CaCu
El estado de seguimiento se calcula con prioridad: cáncer (`first_case`, biopsia de
carcinoma), tratamiento (`first_treatment`), postcolposcopia y, en ausencia de esos eventos,
precolposcopia. Antes se pasaba a postcolposcopia con la primera colposcopia. Esta rama exige
además una toma de citología posterior a dicha colposcopia. El mismo día no cuenta como
posterior. Tratamiento y cáncer mantienen prioridad. No se interpreta la ausencia de una
biopsia como una biopsia negativa.
Las cohortes no son esta máquina: vigilancia usa la primera citología, postcolposcopia usa
una visita tras el resultado del episodio de colposcopia, postratamiento sigue su índice de
tratamiento y supervivencia usa su cohorte de biopsia. Cada cohorte aplica exclusiones propias;
el estado visual por sí solo no demuestra elegibilidad para un modelo. El código de series NCI
selecciona una muestra y comprueba historia y vínculos por separado. La ficha consume el
estado que publica la API; sus cambios quedan pendientes por la restricción de no tocar WebApp.
La consulta previa a la API 5710, corte 2026-11-30, clasificaba 1,719 pacientes: 946 pre,
137 postcolposcopia, 209 postratamiento y 427 casos. Son los estados del código desplegado,
no un conteo de la regla nueva; no se ha modificado ni recalculado 5710.
Pendientes: los modelos actuales no seleccionan todos la última citología como índice;
validar qué hacer con tratamientos, cáncer y colposcopias repetidas, disponibilidad tardía,
reingresos y evidencia sin fecha. Gold debe reconstruirse antes de que la API lea la nueva
columna `first_postcolposcopy_cytology`. Verificar actualización de esquema anterior antes
de despliegue. Las fechas clínicas y de disponibilidad no están completamente unificadas.
+33
View File
@@ -0,0 +1,33 @@
# Evaluación de regresión de desarrollo
`cacu_development_evaluation` es un job explícito de Dagster. Lee las pacientes elegibles de
`cacu_cohort_surveillance`, codifica la información visible al índice y evalúa CIN2+ a un año.
No genera scores, no registra un modelo promovible y no forma parte del entrenamiento rutinario.
El nombre `cacu.cin2_firth_development` está en `DEVELOPMENT`. El resultado se guarda en el run
de MLflow como `reports/development_evaluation.json`.
Se consideran hasta cinco variables binarias con al menos 70 % de cobertura y ambos valores,
ordenadas por cobertura y nombre; se eliminan duplicadas y complementarias. Se prueban todas
las combinaciones de hasta dos variables, más el intercepto: como máximo 16 por método y
partición. La selección, la imputación mediana y la comprobación de rango se hacen sin usar las
observaciones de prueba de la partición exterior. Cada combinación se evalúa dentro de esa
partición mediante validación cruzada interna y se elige por pérdida logarítmica. Se evalúan
Firth, FLIC y FLAC por separado en CV estratificada exterior y LOOCV anidada. El informe
incluye intentos, errores, selección por partición, frecuencia de variables, AUC, Brier,
pendiente e intercepto de calibración, pérdida logarítmica y cantidad sin estimar.
La cota por defecto es `3 * (n + 3) * (16 * 2 + 1)` ajustes. Para 1,000 pacientes son
99,297; una referencia orientativa de 50 ms por ajuste daría 4,965 segundos, aunque el tiempo
real depende de convergencia y hardware. El job rechaza más de 100,000 ajustes estimados salvo
configuración explícita. Si una partición no puede ajustar una combinación, registra el fallo;
no la reemplaza por una probabilidad de otra combinación.
El estimador Firth/FLIC/FLAC procede de `edgar/camodels`, commit
`2392d54fd4a3942b56dae803906586bc65600728`, archivo `selection/firth.py`; usa `firthmodels`.
La selección implementada aquí usa búsqueda exhaustiva acotada y validación anidada.
Limitaciones: la cohorte actual de vigilancia indexa la primera citología, no necesariamente la
última deseada por el usuario. La imputación es técnica y debe validarse clínicamente; la fecha
de disponibilidad faltante de algunos formularios sigue siendo incierta. Las métricas de una
muestra pequeña y las variantes con fallos de ajuste no deben interpretarse como validación
clínica. Solo se ha ejecutado con datos sintéticos en pruebas aisladas.
+104
View File
@@ -0,0 +1,104 @@
# Trabajo nocturno CaCu
Árbol: `/home/admon/worktree/cacu-noche`, rama local `cacu-noche`. No se hizo
push, despliegue, ni entrenamiento sobre datos de pacientes. La 5710 se
consultó únicamente en lectura.
## 1. Estados y segunda citología
La transición a postcolposcopia exige una citología posterior a la primera
colposcopia; se mantuvo el significado previo de primera/subsiguiente ronda y
las prioridades existentes. Se documentaron las reglas y discrepancias en
`docs/cacu-estados.md`. Pruebas con dbt y SQLite temporal.
Compatibilidad: la API y los indicadores calculan temporalmente la fecha a
partir de `gold.cacu_events` si falta la columna en el gold anterior, con la
misma condición de dbt. Es necesario reconstruir gold para materializarla y
mantener coherentes las demás consultas; la compatibilidad no sustituye esa
actualización. Los conteos documentados de la 5710 son anteriores a la nueva
clasificación.
## 2. Referencia NCI
Se distinguen biopsia ausente, múltiples informes, vínculo no registrado,
referencia vinculada ausente y referencias múltiples. La referencia se usa
solo si existe vínculo explícito; no se deduce por cercanía temporal. Las
cuentas y condiciones por libro están en el commit `3f02377` (`docs/nci-libros-adicionales.md`).
En la API existente había 0/137 coincidencias para CIN2+ entre las pacientes
postcolposcopia evaluadas; no se desplegó esta versión para volver a contar
con los nuevos motivos. Los libros revisados no justifican equiparar ausencia
de biopsia con biopsia negativa.
## 3. Codificadores
Un genotipo combinado negativo exige ambos resultados negativos; un positivo
basta para resultado positivo. La calidad de la muestra se fecha al informe,
no a la toma. Quedan descritas en `docs/cacu-codificadores.md` las limitaciones
de disponibilidad histórica desconocida de algunas fuentes.
## 4. Logística en desarrollo
Firth, FLIC y FLAC usan selección exhaustiva dentro de un conjunto acotado,
validación cruzada anidada y LOOCV. Un job separado guarda la evaluación en
MLflow sin registrar ni promover un modelo. El límite de combinaciones,
tratamiento de faltantes, métricas y procedencia de camodels se describen en
`docs/cacu-logistica-desarrollo.md`. Las pruebas usan datos sintéticos; no se
ha entrenado ni validado clínicamente un modelo.
## 5. Bayesianos: incompleta
Se incorporó y probó la base de Gibbs de prevalencia de bayes-pim, con
procedencia en `models/models/cacu/bayes_development/README.md`. Es un
fundamento transversal, no el Gibbs de múltiples visitas solicitado. Faltan
Markov y Klausch, el adaptador gold por fecha de disponibilidad, NUTS/PyMC
como extra opcional, la ejecución y el artefacto con R-hat, ESS, divergencias,
recuperación y comparación con máxima verosimilitud. No hay integración ni
promoción del modelo.
El código original usa desenlaces CIN3+ no distinguibles en patología local y
una verosimilitud `models.cacu.cin2_pim.likelihood` ausente de esta rama. Hay
que verificar la correspondencia de desenlaces y la equivalencia matemática
con el PIM actual sin recodificar CIN2+ como CIN3+. También hace falta definir
cómo se corta la historia de visitas para estimar sin fuga temporal.
## Commits locales
- `824fbee` Exigir citología posterior para seguimiento postcolposcopia.
- `660b287` Aclarar vínculos de biopsia y referencia NCI.
- `7791c72` Evitar fechas y genotipos incompletos engañosos.
- `bad58d5` Añadir evaluación logística de desarrollo; models `d27b585`.
- models `3a033ef` Incorporar base bayesiana de investigación.
Los cambios en models requieren conservar los commits locales del submódulo al
publicar posteriormente. No se cambió WebApp ni se modificó la instancia 5710.
## Revisión longitudinal bayesiana: correspondencia no demostrada
En `bayes-pim` `1cef69be90a7a9ea30378118cd2a2c9fa312943e`,
`markov_gibbs._likelihoods` y `markov_discrete.likelihoods` tratan una
biopsia positiva como observación inequívoca del estado latente D = CIN3+;
una biopsia negativa excluye ese estado. `klausch.pim_series` también usa
CIN3+ como positivo y <CIN3 como negativo. En cambio el gold local agrupa
NIC2/NIC3 como HSIL: ese resultado no demuestra ninguna de las dos categorías.
El carcinoma es positivo CIN3+, pero no resuelve la clasificación de HSIL ni
permite etiquetar como negativas las demás biopsias indistintamente. Tomar
HSIL como positivo, negativo o ausencia cambiaría la verosimilitud y no sería
una adaptación equivalente.
El PIM local (`models.cacu.pim.neg_loglik`) utiliza una incidencia con base
I-spline; el `fitting.py` de origen depende de un Weibull en el módulo ausente
`models.cacu.cin2_pim.likelihood`. La semejanza del formato `(c,l,r)` no
prueba equivalencia de modelos, ni la comparación de sus coeficientes sería
válida sin comprobar que estiman la misma cantidad. Por ello no se conecta
Markov/Klausch a gold ni se publica una evaluación longitudinal como válida.
Para una adaptación posterior se necesita, como mínimo, un desenlace
identificable con sus categorías de biopsia y una verosimilitud definida para
observaciones ambiguas; después habría que demostrarla con datos simulados y
comparar probabilidades del mismo desenlace y horizonte. Las visitas deberían
seleccionarse por paciente y fecha índice con fecha clínica y disponibilidad
no posteriores al índice, y conservar como desconocida la disponibilidad
indeterminada. El codificador `visible` actual admite algunos registros sin
fecha de disponibilidad; no basta reutilizarlo sin resolver esa excepción.
> La base Gibbs (`models/cacu/bayes_development`) se retiró el 2026-12-04; se recupera de git en `models` `68e5b78`.
+26
View File
@@ -0,0 +1,26 @@
# Referencias NCI: de dónde se leen y quién decide
Fuentes y comprobación: [nci-referencias.md](nci-referencias.md).
## Datos
Una sola fuente, la **maestra**: `tools/nci_seeds.py` genera las semillas de
`Persistance/dbt/seeds/nci/` desde las cinco tablas generales del NCI (Excel originales, con
archivo, hoja, fila y SHA-256): CIN2+, CIN3+ y cáncer, inmediato y a 1 a 5 años, con sus límites
al 95%. `nci_risk_lookup` añade las filas de grupo (High Grade, ASC-US/LSIL) donde no hay una
exacta.
La API solo consulta las tablas de oro. Al desplegar hay que reconstruir oro; sin las tablas,
la maestra responde `missing_data`.
## Quién decide
Los requisitos clínicos se deciden en oro (`macros/cacu_nci_*.sql`, filas `nci_*` de
`cacu_eligibility`). Python elige la tabla (tamizaje, vigilancia en segunda visita, poscolposcopía en primera visita
o resultados tras colposcopía), traduce los resultados a sus categorías y busca la fila.
## Qué se muestra
`core.cacu.visibility`: el postratamiento y la segunda visita poscolposcopía responden
`not_evaluated`, el genotipo NCI no se lee (una muestra genotipada es VPH positiva) y los
modelos de `core.models.HIDDEN` no se entrenan ni puntúan por omisión.
+59
View File
@@ -0,0 +1,59 @@
# Referencias de las tablas NCI
Riesgos de la cohorte Kaiser Permanente Northern California (2003 a 2017, 25 a 65 años). No
están validados para la población de la plataforma.
## Fuentes
| Qué respalda | Referencia | Enlace |
|---|---|---|
| Estimaciones que sustentan las guías | Egemen D. y cols., J Low Genit Tract Dis 2020 | https://doi.org/10.1097/LGT.0000000000000529 (texto: https://pmc.ncbi.nlm.nih.gov/articles/PMC7147417/) |
| Métodos de estimación | Cheung L. C. y cols., 2020 | https://doi.org/10.1097/LGT.0000000000000528 |
| Guías de manejo ASCCP 2019 | Perkins R. B. y cols., 2020 | https://pmc.ncbi.nlm.nih.gov/articles/PMC7147428/ |
| Libros suplementarios (ya no se usan) | `AdditionalTables.zip`, LHNCBC (Biblioteca Nacional de Medicina) | https://data.lhncbc.nlm.nih.gov/public/cervixca/AdditionalTables.zip |
| Página que publica las tablas (archivada el 10-jul-2024) | LHNCBC | https://web.archive.org/web/20240710095705/https://lhncbc.nlm.nih.gov/LHC-research/LHC-projects/image-processing/cervixca.html |
## Libros suplementarios frente a la maestra (2026-12-04)
Antes de retirarlos se compararon los libros 1, 4 y 17 con las tablas generales (CIN2+, CIN3+ y
cáncer, inmediato y a 5 años). Libros 1 y 17: todas las cifras comparables, iguales. Libro 4:
iguales salvo la hoja "HPV-neg LSIL" (3 cifras, hasta 1.6 puntos) y 2 de "HPV-pos NILM" (menos
de 0.1 puntos). Sin equivalente en la maestra: la hoja "Pap-negative", filas "ALL" de algunas
hojas y los años 6 y 7.
## CIN3+, CIN2+ y cáncer
La conducta de las guías se decide con el riesgo de CIN3+. CIN2+ y cáncer son resultados
complementarios publicados. Ninguno es comparable sin más con la probabilidad de LIEAG+ del
modelo institucional.
## Libros retirados
La plataforma usa solo la maestra. Los libros y su código se recuperan de git: los de ingreso,
segunda visita y poscolposcopía en el commit `2f2fcdd`; los de genotipo y postratamiento en
`3f02377`. Todos están también en `AdditionalTables.zip`.
## Tabla maestra: las cinco tablas generales
`tools/nci_seeds.py` la genera desde estos Excel, guardados sin cambios en
`Core/core/cacu/nci_source_workbooks`. Descargados el 2026-12-04 de
`https://data.lhncbc.nlm.nih.gov/public/cervixca/`
(el servidor los fecha el 28-ago-2024).
| Archivo (URL: la carpeta más el nombre) | SHA-256 |
|---|---|
| `1-General_Table_for_Screening_locked.xlsx` | `c7ee5bd72f2af4aafd486cb0548e2b9b7e7ffd52c50dcddd2787051423b9a2eb` |
| `2-General_Table_for_Surveillance_locked.xlsx` | `96d54b2f74298d133a5cc6733b349c70bbb2c003c91c7c50afd41152683f9f8b` |
| `3-General_Table_for_Risk_Following_Colposcpy_locked.xlsx` | `2e362fc200e2e2dda69c78e7fda6df12f9d9fd599de261b9881d8618eeb653b6` |
| `4-General_Table_for_Post-Colpo.xlsx` | `2139d1a053422923328cf948fa574d1ea016f9034c481c1006c9ca11eec9ba3b` |
| `5-General_Table_for_Post-Treatment_locked.xlsx` | `b2fb85982e40907cdc193a4b0dcae84fd49b5cba714d482ac2ed77661eb694bc` |
Se publican CIN2+, CIN3+ y cáncer, inmediato y a 1 a 5 años, sin redondear y con sus límites
al 95% (la tabla de resultados tras colposcopía solo trae CIN3+, a 1 y 5 años, sin límites);
`NA`, `#NUM!` o vacío es "no publicado". Se traducen las grafías del archivo
(`tools/nci_seeds.py`, `SPELLINGS`). La referencia "HPV-positive NILM" de la tabla 3 se lee
como dos cotestes (`HPV-positive NILM x2`): interpretación nuestra, falta confirmación clínica.
La transcripción anterior (`nci_risk_tables.json`, 184 filas) se retiró; cinco de sus filas no
están en las fuentes y ya no se publican. `$reference-risk` sigue respondiendo 503; la serie
"NCI" de `$risk-series` usa estas tablas.
@@ -0,0 +1,84 @@
# Propuesta: tiempo de diagnóstico tras biopsia a tratamiento en CaMa
Estado: **bosquejo, no implementado**. Reutiliza la estructura de CaCu; requiere acordar las reglas clínicas antes de publicarlo o reconstruir gold. No implica desplegar ni modificar instalaciones.
## Puntos a decidir
- Ventanas desde el reporte de biopsia al diagnóstico y desde el diagnóstico al tratamiento. Los 60 días de CaCu no se adoptan automáticamente para CaMa.
- Si cuenta el tratamiento iniciado el mismo día del diagnóstico; el ejemplo usa `>=`, de modo que produce cero días. CaCu ya cuenta el mismo día (`>=`).
- Si cuenta cualquier tipo de tratamiento y qué hacer cuando existen tratamientos anteriores, múltiples biopsias o episodios de la misma paciente.
- Si la población debe excluir antecedentes de cáncer y si la unidad es mastografía o paciente; el ejemplo conserva la exclusión y la unidad de las medidas actuales de mastografía.
- Qué diagnóstico posterior a biopsia cuenta. Los diagnósticos de CaMa proceden de notas y no todos indican cáncer.
- La selección de la primera biopsia vinculada, los límites temporales y la forma de conservar la fecha en que cada hecho fue conocido. Sin un vínculo o fecha suficientes no se debe inventar un intervalo.
## Bosquejo dbt
Propuesta de modelo nuevo `gold.cama_diagnostico_tratamiento`, basado en `cacu_samples`. Las claves `biopsy_to_diagnosis` y `diagnosis_to_treatment` **aún no existen** en los horizontes de CaMa y no tienen valores propuestos en este documento.
```sql
{% set h = var('cama')['horizons'] %}
with mammograms as (
select * from {{ ref('cama_mammograms') }}
),
events as (
select * from {{ ref('cama_events') }}
),
biopsy as (
-- El enlace mastografía-biopsia ya fue materializado; no inferirlo por proximidad.
select mammogram_id, min(biopsy_report_date) as biopsy_date
from {{ ref('cama_mammogram_biopsies') }}
where biopsy_report_date is not null
group by mammogram_id
),
biopsy_diagnosis as (
select m.mammogram_id, m.person_id, min(e.date) as biopsy_diagnosis_date
from mammograms as m
join biopsy as b on b.mammogram_id = m.mammogram_id
join events as e
on e.person_id = m.person_id and e.type = 'diagnosis' and e.date > b.biopsy_date
where {{ days_between('b.biopsy_date', 'e.date') }} < {{ h.biopsy_to_diagnosis }}
group by m.mammogram_id, m.person_id
),
diagnosis_treatment as (
select d.mammogram_id, min(e.date) as diagnosis_treatment_date
from biopsy_diagnosis as d
join events as e
on e.person_id = d.person_id and e.type = 'treatment'
and e.date >= d.biopsy_diagnosis_date
where {{ days_between('d.biopsy_diagnosis_date', 'e.date') }} < {{ h.diagnosis_to_treatment }}
group by d.mammogram_id
)
select m.*, b.biopsy_date, d.biopsy_diagnosis_date, t.diagnosis_treatment_date,
{{ days_between('d.biopsy_diagnosis_date', 't.diagnosis_treatment_date') }}
as days_diagnosis_treatment
from mammograms as m
left join biopsy as b on b.mammogram_id = m.mammogram_id
left join biopsy_diagnosis as d on d.mammogram_id = m.mammogram_id
left join diagnosis_treatment as t on t.mammogram_id = m.mammogram_id
```
Antes de usar este SQL hay que completar las reglas anteriores, filtrar fechas inconsistentes y propagar las fechas de conocimiento de la biopsia, del diagnóstico y del tratamiento para que una consulta histórica no use información posterior. La ausencia de una biopsia o un tratamiento no es un resultado negativo.
## Bosquejo de medida
```python
Measure(
"CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO",
"Tiempo de diagnóstico tras biopsia a tratamiento",
"diagnosis_treatment",
Duration(
"days_diagnosis_treatment",
"diagnosis_treatment_date",
"biopsy_diagnosis_date",
H["diagnosis_to_treatment"],
units=lambda r: r["history"] == 0 and r["biopsy_diagnosis_date"] is not None,
unit="mammogram_id",
date="exam_date",
),
"decrease",
# Añadir known/facts de acuerdo con las fechas de disponibilidad de gold.
)
```
Registrar la lectura `diagnosis_treatment` en `Persistance/persistance/measures.py`, conectar la tarjeta a la medida y probar, en un entorno aislado, ausencia de eventos, tratamiento anterior y del mismo día, varios eventos, límites de ventanas y disponibilidad histórica. No se ha implementado la medida ni se han generado datos con este bosquejo.
+1 -1
Submodule models updated: 1a1ea5c7a9...4e077b2ff2
+3 -1
View File
@@ -201,6 +201,7 @@ def pathology_report(p: dict, b: dict) -> bytes:
p: surname_first (name as the report prints it), age, sex (F/M).
b: requested (date), reported (date), time (HH:MM), physician, number (P-25-000000),
mammogram (date of the mammogram it came from, when the request names it),
clinical (clinical diagnosis), specimen, macroscopic, organ, diagnosis, pathologist,
pathologist_id."""
pdf = _pdf()
@@ -230,9 +231,10 @@ def pathology_report(p: dict, b: dict) -> bytes:
pdf.line(40, 208, 572, 208)
pdf.set_font("helvetica", "", 8)
pdf.set_xy(40, 218)
summary = f"MASTOGRAFÍA DEL {_dmy(b['mammogram'])}" if b.get("mammogram") else "no referido"
pdf.multi_cell(
532, 10,
"Notas Clínicas\nTiempo de evolución: no referido. Resumen Clínico: no referido. "
f"Notas Clínicas\nTiempo de evolución: no referido. Resumen Clínico: {summary}. "
f"Diagnóstico Clínico: {b['clinical']}.\n\nEspecimen\n1 - {b['specimen']}\n"
f"Descripción Macroscópica:\n{b['macroscopic']}\n\nSe incluye total del especimen en "
"un cassette.\n\nNo estudios previos",
+36 -2
View File
@@ -356,9 +356,36 @@ CAUSE = {"cervical": ("TUMOR MALIGNO DEL CUELLO DEL ÚTERO", "C53.9"),
None: ("INFARTO AGUDO DEL MIOCARDIO", "I21.9")} # fmt: skip
def mammogram_of_biopsies(bundle: dict) -> dict[str, str]:
"""The exam date of the mammogram each breast biopsy came from, by the biopsy's request
date. Synthea keeps one encounter open from a mammogram to the biopsy it leads to, so a
biopsy report and its mammogram's report name the same encounter: that is the source's own
link. An encounter with no mammogram, or with two, names none (nothing is inferred)."""
by_encounter: dict[str, dict[str, list[str]]] = {}
for entry in bundle["entry"]:
r = entry["resource"]
code = (r.get("code") or {}).get("coding", [{}])[0].get("code")
encounter = (r.get("encounter") or {}).get("reference")
if r["resourceType"] == "DiagnosticReport" and encounter and code in STUDY_LINK:
by_encounter.setdefault(encounter, {}).setdefault(code, []).append(
r["effectiveDateTime"][:10]
)
found: dict[str, set[str]] = {}
for studies in by_encounter.values():
exams = set(studies.get("mammography", []))
if len(studies.get("mammography", [])) == 1:
for requested in studies.get("breast_biopsy", []):
found.setdefault(requested, set()).update(exams)
return {requested: exams.pop() for requested, exams in found.items() if len(exams) == 1}
STUDY_LINK = ("mammography", "breast_biopsy")
def people_and_studies(bundles: list[dict]) -> dict[str, dict]:
"""Each Synthea patient's birth date, and her studies as platform rows (core.fhir_in):
a biopsy Synthea sent as several same-day reports is one study."""
a biopsy Synthea sent as several same-day reports is one study, which names the
mammogram it came from (`mammogram_exam_date`) when the source does."""
people = {}
for bundle in bundles:
patient = next(
@@ -373,7 +400,11 @@ def people_and_studies(bundles: list[dict]) -> dict[str, dict]:
merged.setdefault(r["request_date"], {}).update(
{k: v for k, v in r.items() if v is not None}
)
rows = list(merged.values())
origin = mammogram_of_biopsies(bundle)
rows = [
{**r, "mammogram_exam_date": origin[requested]} if requested in origin else r
for requested, r in merged.items()
]
studies[entity] = [{k: v for k, v in r.items() if not k.startswith("_")} for r in rows]
if any(studies.values()):
people[patient["id"]] = {"birth_date": _d(patient["birthDate"]), "studies": studies,
@@ -737,6 +768,9 @@ def build(
)
}
values = {k: v for k, v in values.items() if v is not None}
if r.get("mammogram_exam_date"): # the request names its mammogram
report["mammogram"] = _d(r["mammogram_exam_date"])
values["mammogram_exam_date"] = r["mammogram_exam_date"]
side = rng.choice(("IZQUIERDA", "DERECHA"))
if r["histology"] == "benign":
lines = [
+2 -1
View File
@@ -148,6 +148,7 @@
"patterns": {
"request_date": "solicitud:\\s*(\\d{2}/\\d{2}/\\d{4})",
"report_date": "reporte:\\s*(\\d{2}/\\d{2}/\\d{4})",
"mammogram_exam_date": "res[uú]men cl[ií]nico:\\s*mastograf[ií]a del (\\d{2}/\\d{2}/\\d{4})",
"histology": "biopsia:[\\s\\S]{0,300}?(negativo para malignidad|in situ|infiltrante)",
"histologic_type": "\\((\\d{4}/\\d)\\)",
"grade": "nottingham\\):\\s*(\\d)",
@@ -158,7 +159,7 @@
"size_mm": "tama[ñn]o tumoral:\\s*(\\d+)\\s*mm", "positive_nodes": "ganglios linf[aá]ticos positivos:\\s*(\\d+)",
"stage": "estadio cl[ií]nico\\s+([0-9IVlO|]{1,4}[ABC]?)\\b"},
"concept_map": "erick_site",
"formats": {"request_date": "%d/%m/%Y", "report_date": "%d/%m/%Y"}},
"formats": {"request_date": "%d/%m/%Y", "report_date": "%d/%m/%Y", "mammogram_exam_date": "%d/%m/%Y"}},
{"id": "mchat_forms", "kind": "route", "label": "Formatos M-CHAT", "inputs": ["text"], "when": [{"column": "text", "op": "matches", "value": "(?i)cuestionario m-chat"}]},
{"id": "ados2_reports", "kind": "route", "label": "Reportes ADOS-2", "inputs": ["text"], "when": [{"column": "text", "op": "matches", "value": "(?i)informe de evaluaci[oó]n ados-2"}]},
+3 -1
View File
@@ -8,6 +8,7 @@
{"id": "cytology", "kind": "fhir", "label": "Citología", "inputs": ["inbox"], "entity": "cervical_cytology"},
{"id": "biopsy", "kind": "fhir", "label": "Biopsia", "inputs": ["inbox"], "entity": "cervical_biopsy"},
{"id": "notes", "kind": "fhir", "label": "Notas médicas", "inputs": ["inbox"], "entity": "clinical_note"},
{"id": "evidence", "kind": "fhir", "label": "Evidencia clínica CaCu", "inputs": ["inbox"], "entity": "cacu_eligibility_evidence"},
{"id": "persons", "kind": "link", "label": "Quién es quién", "inputs": ["who"],
"fields": ["record_number", "curp", "nss", "full_name", "birth_date", "sex"]},
@@ -15,6 +16,7 @@
{"id": "deaths_out", "kind": "target", "label": "Defunciones", "inputs": ["deaths", "persons"], "entity": "death"},
{"id": "cytology_out", "kind": "target", "label": "Citologías", "inputs": ["cytology", "persons"], "entity": "cervical_cytology"},
{"id": "biopsy_out", "kind": "target", "label": "Biopsias", "inputs": ["biopsy", "persons"], "entity": "cervical_biopsy"},
{"id": "notes_out", "kind": "target", "label": "Notas médicas", "inputs": ["notes", "persons"], "entity": "clinical_note"}
{"id": "notes_out", "kind": "target", "label": "Notas médicas", "inputs": ["notes", "persons"], "entity": "clinical_note"},
{"id": "evidence_out", "kind": "target", "label": "Evidencia clínica CaCu", "inputs": ["evidence", "persons"], "entity": "cacu_eligibility_evidence"}
]
}
+45 -20
View File
@@ -93,7 +93,24 @@ states["Initial"] = {"type": "Initial", "direct_transition": "Age_25"}
states["Age_25"] = {
"type": "Delay",
"exact": {"quantity": 25, "unit": "years"},
"direct_transition": "Screening",
"direct_transition": "Opening",
}
# The clinic's records start here: short histories, a few visits per woman.
SINCE = 2021
states["Opening"] = {
"type": "Guard",
"allow": {"condition_type": "Date", "operator": ">=", "year": SINCE},
"direct_transition": "First_Visit",
}
# Women do not all come the first week.
states["First_Visit"] = {
"type": "Delay",
"range": {"low": 0, "high": 24, "unit": "months"},
# Screening ends at 65, also for who is already past it when the records start.
"conditional_transition": [
{"condition": age("<", 65), "transition": "Screening"},
{"transition": "Terminal"},
],
}
# Cytology results (Bethesda), in the general population and once a colposcopy or a
@@ -107,19 +124,21 @@ RESULTS = [
("CIS", 0.003),
]
FOLLOW_UP = [
("NILM", 0.60),
("ASC-US", 0.08),
("LSIL", 0.08),
("ASC-H", 0.06),
("HSIL", 0.16),
("CIS", 0.02),
("NILM", 0.77),
("ASC-US", 0.07),
("LSIL", 0.07),
("ASC-H", 0.03),
("HSIL", 0.05),
("CIS", 0.01),
]
UNSATISFACTORY = 0.04
def results(mix):
return [{"distribution": UNSATISFACTORY, "transition": "Cytology_Unsat"}] + [
{"distribution": round(p * (1 - UNSATISFACTORY), 5), "transition": f"Result_{r}"}
def results(mix, unsatisfactory=UNSATISFACTORY):
"""The results of a sample; in follow-up every one can be read (`unsatisfactory` 0)."""
unread = [{"distribution": unsatisfactory, "transition": "Cytology_Unsat"}]
return (unread if unsatisfactory else []) + [
{"distribution": round(p * (1 - unsatisfactory), 5), "transition": f"Result_{r}"}
for r, p in mix
]
@@ -130,7 +149,10 @@ states["Screening"] = {
"reason": "",
"codes": [{"system": "SNOMED-CT", "code": "185349003", "display": "Encounter for check up"}],
"complex_transition": [
{"condition": attribute("cervical_follow_up", True), "distributions": results(FOLLOW_UP)},
{
"condition": attribute("cervical_follow_up", True),
"distributions": results(FOLLOW_UP, 0),
},
{"distributions": results(RESULTS)},
],
}
@@ -146,7 +168,7 @@ states["Cytology_Unsat"] = {
"direct_transition": "End_Repeat",
}
# HPV: tested from 35 (70%), on every ASC-US, and always once in follow-up (a co-test);
# HPV: tested from 35 (70%), on every ASC-US and LSIL, and always once in follow-up (a co-test);
# positive by cytology; genotypes of positives.
TESTED = 0.70
POSITIVE = {"NILM": 0.08, "ASC-US": 0.50, "LSIL": 0.80, "ASC-H": 0.75, "HSIL": 0.92, "CIS": 0.95}
@@ -160,6 +182,8 @@ VARIANTS = {
"pos18": (True, False, True),
"pos1618": (True, True, True),
}
# A low-grade referral has a grade only with a positive HPV.
REFLEX = ("ASC-US", "LSIL")
for r, _ in RESULTS:
p, p16 = POSITIVE[r], HPV16[r]
pos = [
@@ -172,7 +196,7 @@ for r, _ in RESULTS:
{"distribution": round(p * w, 5), "transition": f"Cytology_{r}_{v}"} for v, w in pos
]
cotest = {"condition": attribute("cervical_follow_up", True), "distributions": tested}
if r == "ASC-US": # reflex HPV on every ASC-US
if r in REFLEX: # reflex HPV on every low-grade result
states[f"Result_{r}"] = {"type": "Simple", "distributed_transition": tested}
else:
states[f"Result_{r}"] = {
@@ -194,7 +218,7 @@ for r, _ in RESULTS:
],
}
for v, hpv in VARIANTS.items():
if r == "ASC-US" and v == "none":
if r in REFLEX and v == "none":
continue
observations = [
report_obs(
@@ -213,7 +237,7 @@ for r, _ in RESULTS:
elif r == "ASC-US":
after = "End_Colposcopy_ASCUS" if hpv[0] else "End_Repeat_Year"
elif r == "LSIL":
after = "End_Colposcopy_LSIL"
after = "End_Colposcopy_LSIL" if hpv[0] else "End_Repeat_Year"
else:
after = f"End_Colposcopy_{r.replace('-', '')}"
states[f"Cytology_{r}_{v}"] = {
@@ -411,11 +435,12 @@ module = {
"gmf_version": 2,
"remarks": [
"Synthetic data for the platform (CaCu): a cervical screening clinic as NOM-014-SSA2",
"runs it. Cytology from 25 to 64 (Bethesda; 4% unsatisfactory, repeated), HPV co-test",
"with genotypes 16/18 from 35, on every ASC-US and always in follow-up. Colposcopy",
"clinic visit, then colposcopy and biopsy for ASC-US with HPV and anything worse (85%",
"attend; a quarter of those who don't come back later with cancer). Below CIN2:",
"co-tests from a year later; CIN2+: LEEP (D06.9) and co-tests; invasive: oncology",
"runs it, records from 2021 on. Cytology from 25 to 64 (4% unsatisfactory), HPV co-test",
"with genotypes 16/18 from 35, on every ASC-US and LSIL and always in follow-up (where",
"every sample can be read). Colposcopy clinic visit, then colposcopy and biopsy for",
"ASC-US or LSIL with HPV and anything worse (85% attend; a quarter of those who don't",
"come back later with cancer). Below CIN2: co-tests from a year later; CIN2+: LEEP",
"(D06.9) and co-tests; invasive: oncology",
"(C53.9), about 2 in 5 die within five years. Enriched in cancer and in abnormal",
"follow-up results so every CaCu model has events (tests/fixtures/synthea/",
"make_cervical_screening.py writes this file). Codes are the platform's catalog.",
+60 -129
View File
@@ -3,11 +3,12 @@
"gmf_version": 2,
"remarks": [
"Synthetic data for the platform (CaCu): a cervical screening clinic as NOM-014-SSA2",
"runs it. Cytology from 25 to 64 (Bethesda; 4% unsatisfactory, repeated), HPV co-test",
"with genotypes 16/18 from 35, on every ASC-US and always in follow-up. Colposcopy",
"clinic visit, then colposcopy and biopsy for ASC-US with HPV and anything worse (85%",
"attend; a quarter of those who don't come back later with cancer). Below CIN2:",
"co-tests from a year later; CIN2+: LEEP (D06.9) and co-tests; invasive: oncology",
"runs it, records from 2021 on. Cytology from 25 to 64 (4% unsatisfactory), HPV co-test",
"with genotypes 16/18 from 35, on every ASC-US and LSIL and always in follow-up (where",
"every sample can be read). Colposcopy clinic visit, then colposcopy and biopsy for",
"ASC-US or LSIL with HPV and anything worse (85% attend; a quarter of those who don't",
"come back later with cancer). Below CIN2: co-tests from a year later; CIN2+: LEEP",
"(D06.9) and co-tests; invasive: oncology",
"(C53.9), about 2 in 5 die within five years. Enriched in cancer and in abnormal",
"follow-up results so every CaCu model has events (tests/fixtures/synthea/",
"make_cervical_screening.py writes this file). Codes are the platform's catalog."
@@ -23,7 +24,38 @@
"quantity": 25,
"unit": "years"
},
"direct_transition": "Screening"
"direct_transition": "Opening"
},
"Opening": {
"type": "Guard",
"allow": {
"condition_type": "Date",
"operator": ">=",
"year": 2021
},
"direct_transition": "First_Visit"
},
"First_Visit": {
"type": "Delay",
"range": {
"low": 0,
"high": 24,
"unit": "months"
},
"conditional_transition": [
{
"condition": {
"condition_type": "Age",
"operator": "<",
"quantity": 65,
"unit": "years"
},
"transition": "Screening"
},
{
"transition": "Terminal"
}
]
},
"Screening": {
"type": "Encounter",
@@ -46,31 +78,27 @@
},
"distributions": [
{
"distribution": 0.04,
"transition": "Cytology_Unsat"
},
{
"distribution": 0.576,
"distribution": 0.77,
"transition": "Result_NILM"
},
{
"distribution": 0.0768,
"distribution": 0.07,
"transition": "Result_ASC-US"
},
{
"distribution": 0.0768,
"distribution": 0.07,
"transition": "Result_LSIL"
},
{
"distribution": 0.0576,
"distribution": 0.03,
"transition": "Result_ASC-H"
},
{
"distribution": 0.1536,
"distribution": 0.05,
"transition": "Result_HSIL"
},
{
"distribution": 0.0192,
"distribution": 0.01,
"transition": "Result_CIS"
}
]
@@ -1217,126 +1245,29 @@
},
"Result_LSIL": {
"type": "Simple",
"complex_transition": [
"distributed_transition": [
{
"condition": {
"condition_type": "Attribute",
"attribute": "cervical_follow_up",
"operator": "==",
"value": true
},
"distributions": [
{
"distribution": 0.2,
"transition": "Cytology_LSIL_neg"
},
{
"distribution": 0.528,
"transition": "Cytology_LSIL_pos"
},
{
"distribution": 0.176,
"transition": "Cytology_LSIL_pos16"
},
{
"distribution": 0.072,
"transition": "Cytology_LSIL_pos18"
},
{
"distribution": 0.024,
"transition": "Cytology_LSIL_pos1618"
}
]
"distribution": 0.2,
"transition": "Cytology_LSIL_neg"
},
{
"condition": {
"condition_type": "Age",
"operator": ">=",
"quantity": 35,
"unit": "years"
},
"distributions": [
{
"distribution": 0.14,
"transition": "Cytology_LSIL_neg"
},
{
"distribution": 0.3696,
"transition": "Cytology_LSIL_pos"
},
{
"distribution": 0.1232,
"transition": "Cytology_LSIL_pos16"
},
{
"distribution": 0.0504,
"transition": "Cytology_LSIL_pos18"
},
{
"distribution": 0.0168,
"transition": "Cytology_LSIL_pos1618"
},
{
"distribution": 0.3,
"transition": "Cytology_LSIL_none"
}
]
"distribution": 0.528,
"transition": "Cytology_LSIL_pos"
},
{
"distributions": [
{
"distribution": 1,
"transition": "Cytology_LSIL_none"
}
]
"distribution": 0.176,
"transition": "Cytology_LSIL_pos16"
},
{
"distribution": 0.072,
"transition": "Cytology_LSIL_pos18"
},
{
"distribution": 0.024,
"transition": "Cytology_LSIL_pos1618"
}
]
},
"Cytology_LSIL_none": {
"type": "DiagnosticReport",
"codes": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/study",
"code": "cervical_cytology",
"display": "Citología cervical"
}
],
"observations": [
{
"category": "laboratory",
"unit": "",
"codes": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/catalog-field",
"code": "cervical_cytology.adequacy",
"display": "Calidad de la muestra"
}
],
"value_code": {
"system": "https://isssteleon.org/fhir/CodeSystem/adequacy",
"code": "satisfactory",
"display": "satisfactory"
}
},
{
"category": "laboratory",
"unit": "",
"codes": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/catalog-field",
"code": "cervical_cytology.result",
"display": "Resultado (Bethesda)"
}
],
"value_code": {
"system": "https://isssteleon.org/fhir/CodeSystem/bethesda",
"code": "LSIL",
"display": "LSIL"
}
}
],
"direct_transition": "End_Colposcopy_LSIL"
},
"Cytology_LSIL_neg": {
"type": "DiagnosticReport",
"codes": [
@@ -1428,7 +1359,7 @@
}
}
],
"direct_transition": "End_Colposcopy_LSIL"
"direct_transition": "End_Repeat_Year"
},
"Cytology_LSIL_pos": {
"type": "DiagnosticReport",
+87
View File
@@ -0,0 +1,87 @@
"""For tests that hand-make a patient's facts: what gold would say of her past (scenarios
nci_master), when the facts do not state it. Only a stand-in: the rules are
SQL (macro cacu_nci_*), tested in test_cacu_nci_requirements."""
import tempfile
from datetime import date
from functools import cache
from pathlib import Path
import pytest
from core import cacu
from core.cacu import reference_risk as ref
from persistance import destination, silver
from persistance import fhir as reads
_real = ref.unmet
def _past(facts, scenario, when):
cytologies = facts.get("cytologies", [])
earlier = [c for c in cytologies if ref._day(c["sample_date"]) < when]
found = set()
if any(
ref._day(e["date"]) <= when
for e in facts.get("events", [])
if e["type"] in ("colposcopy", "treatment")
) or any(ref._day(b["request_date"]) <= when for b in facts.get("biopsies", [])):
found.add("colposcopy_or_treatment_before")
if any(
c.get("gynecologic_condition") == "hysterectomy" and ref._day(c["sample_date"]) <= when
for c in cytologies
):
found.add("hysterectomy_declared")
tests = sorted(
(
c
for c in earlier
if c.get("hpv") is not None and ref._valid(c) and ref._day(c["report_date"]) <= when
),
key=lambda c: ref._day(c["sample_date"]),
reverse=True,
)
if not tests:
return found | {"no_earlier_test_registered"}
if (when - ref._day(tests[0]["sample_date"])).days > cacu.NCI_HISTORY_DAYS:
found.add("earlier_test_older_than_5_years")
if any(c["hpv"] or c["result"] != "NILM" for c in tests[:1]) or any(
(c["hpv"] or c["result"] != "NILM")
and (ref._day(tests[0]["sample_date"]) - ref._day(c["sample_date"])).days
<= cacu.NCI_HISTORY_DAYS
for c in tests[1:2]
):
found.add("history_is_a_surveillance_scenario")
return found
def _unmet(facts, scenario, day):
said = any(r.get("scenario") == scenario for r in facts.get("requirements", []))
if said or scenario != "nci_master":
return _real(facts, scenario, day)
return _past(facts, scenario, day)
@cache
def master() -> list[dict]:
"""The master table as gold holds it: the seeds, built and read as the API reads them."""
folder = Path(tempfile.mkdtemp())
with pytest.MonkeyPatch.context() as patch:
patch.setenv("ISSSTELEON_DATA", str(folder))
patch.setenv("DBT_TARGET", "sqlite")
patch.setenv("PLATFORM_DATABASE_URL", f"sqlite:///{folder}/platform.db")
patch.setattr(destination, "DATA_DIR", folder)
destination.engine.cache_clear()
silver.build(list(silver.NCI_REFERENCES), as_of=date(2026, 1, 1))
found = reads.rows("cacu", "reference_master")
destination.engine().dispose()
destination.engine.cache_clear()
return found
@pytest.fixture(autouse=True)
def gold_says(monkeypatch):
rows = master() # built before any test changes the environment further
monkeypatch.setattr(ref.reading, "master", lambda facts: facts.get("master", rows))
monkeypatch.setattr(ref.reading, "unmet", _unmet)
monkeypatch.setattr(ref, "unmet", _unmet)
+28
View File
@@ -0,0 +1,28 @@
"""Initial or subsequent screening, decided in gold (macro cacu_detection)."""
import sqlite3
from pathlib import Path
from jinja2 import Environment
MACRO = Path(__file__).parents[1] / "Persistance/dbt/macros/cacu_detection.sql"
def test_detection_follows_prior_procedures_then_the_form_and_stays_unknown_without_either():
sql = Environment().from_string(MACRO.read_text()).module.cacu_detection("s", "f")
cases = { # form answer, first colposcopy, first treatment
"never": ("never", None, None, "initial"),
"screened": ("2_years", None, None, "subsequent"),
"past_colposcopy": ("never", "2025-01-01", None, "subsequent"),
"past_treatment": (None, None, "2025-01-01", "subsequent"),
"same_day": ("never", "2026-01-01", None, "initial"),
"unknown": (None, None, None, None),
}
con = sqlite3.connect(":memory:")
con.execute("create table s (person_id text, sample_date text, screening_history text)")
con.execute("create table f (person_id text, first_colposcopy text, first_treatment text)")
for person, (history, colposcopy, treatment, _) in cases.items():
con.execute("insert into s values (?, '2026-01-01', ?)", (person, history))
con.execute("insert into f values (?, ?, ?)", (person, colposcopy, treatment))
found = dict(con.execute(f"select s.person_id, {sql} from s join f using (person_id)"))
assert found == {person: case[-1] for person, case in cases.items()}
+100
View File
@@ -0,0 +1,100 @@
from datetime import date
from core.cacu.measures import MEASURES
from core.measures import Period, evaluate
from persistance import destination, silver
def test_real_gold_sample_model_feeds_both_diagnosis_intervals(tmp_path, monkeypatch):
monkeypatch.setenv("ISSSTELEON_DATA", str(tmp_path))
monkeypatch.setenv("PLATFORM_DATABASE_URL", f"sqlite:///{tmp_path / 'platform.db'}")
monkeypatch.setenv("DBT_TARGET", "sqlite")
monkeypatch.setattr(destination, "DATA_DIR", tmp_path)
destination.engine.cache_clear()
engine = destination.engine()
try:
with engine.begin() as con:
con.exec_driver_sql("create table silver.person (person_id text, birth_date date)")
con.exec_driver_sql("insert into silver.person values ('p', '1980-01-01')")
con.exec_driver_sql(
"create table silver.cervical_cytology (person_id text, sample_date date, "
"report_date date, result text, adequacy text, known_at text, report_known_at "
"text, screening_history text, hpv boolean, hpv_16 boolean, hpv_18 boolean, "
"glandular text, gynecologic_condition text)"
)
con.exec_driver_sql(
"insert into silver.cervical_cytology values ('p', '2026-01-01', '2026-01-05', "
"'NILM', null, null, null, null, null, null, null, null, null)"
)
con.exec_driver_sql(
"create table gold.cacu_events (person_id text, date date, type text, source_id "
"text, value_code text)"
)
con.exec_driver_sql(
"insert into gold.cacu_events values ('p', '2026-01-11', 'diagnosis', 'a', "
"null), ('p', '2026-01-11', 'note', 'a', 'N87'), ('p', '2026-02-11', "
"'diagnosis', 'b', null), ('p', '2026-02-11', 'note', 'b', 'C53')"
)
# one treatment before the diagnosis after the biopsy, and one after it
con.exec_driver_sql(
"insert into gold.cacu_events values ('p', '2026-01-20', 'treatment', 'c', "
"null), ('p', '2026-02-21', 'treatment', 'd', null)"
)
con.exec_driver_sql(
"create table gold.cacu_procedures (person_id text, type text, date date, "
"sample_date date, report_date date)"
)
con.exec_driver_sql(
"insert into gold.cacu_procedures values ('p', 'biopsy', '2026-01-20', "
"'2026-01-01', '2026-02-01')"
)
con.exec_driver_sql(
"create table gold.cacu_follow_up (person_id text, first_history date, "
"first_case date, first_treatment date, first_colposcopy date, "
"first_postcolposcopy_cytology date)"
)
con.exec_driver_sql(
"insert into gold.cacu_follow_up values ('p', null, null, null, null, null)"
)
silver.build(["cacu_samples"], as_of=date(2026, 12, 31))
with engine.connect() as con:
row = dict(con.exec_driver_sql("select * from gold.cacu_samples").mappings().one())
assert row["days_sample_precolposcopy_diagnosis"] == 10 # no colposcopy yet
with engine.begin() as con:
con.exec_driver_sql("update gold.cacu_follow_up set first_colposcopy = '2026-01-08'")
silver.build(["cacu_samples"], as_of=date(2026, 12, 31))
with engine.connect() as con:
later = dict(con.exec_driver_sql("select * from gold.cacu_samples").mappings().one())
assert later["precolposcopy_diagnosis_date"] is None # the diagnosis came after it
assert later["days_sample_diagnosis"] == 10
assert row["days_sample_diagnosis"] == 10
assert row["days_sample_biopsy_diagnosis"] == 41
assert str(row["diagnosis_treatment_date"]) == "2026-02-21"
assert row["days_diagnosis_treatment"] == 10
with engine.begin() as con: # treated on the very day of that diagnosis
con.exec_driver_sql(
"insert into gold.cacu_events values ('p', '2026-02-11', 'treatment', 'e', null)"
)
silver.build(["cacu_samples"], as_of=date(2026, 12, 31))
with engine.connect() as con:
same = dict(con.exec_driver_sql("select * from gold.cacu_samples").mappings().one())
assert same["days_diagnosis_treatment"] == 0
period = Period.parse("2026-S1")
result = evaluate(
MEASURES["CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA"],
[row],
period,
event_cutoff=date(2026, 12, 31),
)
assert result.score == 41
treatment = evaluate(
MEASURES["CACU_DIAS_DIAGNOSTICO_TRATAMIENTO"],
[row],
period,
event_cutoff=date(2026, 12, 31),
)
assert treatment.populations["measure-observation"] == 1
assert treatment.score == 10 # from 11 February, not from the 11 January diagnosis
finally:
engine.dispose()
destination.engine.cache_clear()
+85
View File
@@ -0,0 +1,85 @@
from datetime import date
from core.cacu.measures import MEASURES
from core.measures import Period, evaluate
def test_diagnosis_intervals_use_different_dates_and_require_biopsy():
rows = [
{
"sample_id": "a",
"sample_date": "2026-01-01",
"history": 0,
"diagnosis_date": "2026-01-11",
"days_sample_diagnosis": 10,
"precolposcopy_diagnosis_date": "2026-01-11",
"days_sample_precolposcopy_diagnosis": 10,
"biopsy_date": "2026-02-01",
"biopsy_diagnosis_date": "2026-02-11",
"days_sample_biopsy_diagnosis": 41,
},
{
"sample_id": "b",
"sample_date": "2026-01-01",
"history": 0,
"diagnosis_date": "2026-01-21",
"days_sample_diagnosis": 20,
"precolposcopy_diagnosis_date": "2026-01-21",
"days_sample_precolposcopy_diagnosis": 20,
"biopsy_date": None,
"biopsy_diagnosis_date": None,
"days_sample_biopsy_diagnosis": None,
},
]
period = Period.parse("2026-S1")
first = evaluate(
MEASURES["CACU_DIAS_TOMA_DIAGNOSTICO"], rows, period, event_cutoff=date(2026, 12, 31)
)
after = evaluate(
MEASURES["CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA"],
rows,
period,
event_cutoff=date(2026, 12, 31),
)
assert first.populations["measure-observation"] == 2
assert after.populations["measure-observation"] == 1
assert after.score == 41
def test_diagnosis_to_treatment_uses_post_biopsy_diagnosis_and_respects_cutoff():
rows = [
{
"sample_id": "a",
"sample_date": "2026-01-01",
"history": 0,
"diagnosis_date": "2026-01-11",
"biopsy_diagnosis_date": "2026-02-11",
"diagnosis_treatment_date": "2026-02-21",
"days_diagnosis_treatment": 10,
},
{
"sample_id": "b",
"sample_date": "2026-01-01",
"history": 0,
"diagnosis_date": "2026-01-21",
"biopsy_diagnosis_date": None,
"diagnosis_treatment_date": None,
"days_diagnosis_treatment": None,
},
{
"sample_id": "c",
"sample_date": "2026-01-01",
"history": 0,
"diagnosis_date": "2026-01-15",
"biopsy_diagnosis_date": "2026-02-11",
"diagnosis_treatment_date": None,
"days_diagnosis_treatment": None,
},
]
measure = MEASURES["CACU_DIAS_DIAGNOSTICO_TRATAMIENTO"]
period = Period.parse("2026-S1")
early = evaluate(measure, rows, period, event_cutoff=date(2026, 2, 16))
assert early.populations == {"initial-population": 0, "measure-observation": 0}
later = evaluate(measure, rows, period, event_cutoff=date(2026, 12, 31))
assert later.populations == {"initial-population": 2, "measure-observation": 1}
assert later.score == 10

Some files were not shown because too many files have changed in this diff Show More