Compare commits
105 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cfd90fe3a5 | |||
| 013cd3d99b | |||
| 0b69165c31 | |||
| 0b514feca8 | |||
| 1c41e21e03 | |||
| 1c3947e2f5 | |||
| b01adbb75f | |||
| 26ac614c9c | |||
| c66d9207e2 | |||
| 1e06f93ec6 | |||
| 914b5147c2 | |||
| 3743ea694e | |||
| 320b7f972b | |||
| 7422d48c84 | |||
| c56111d440 | |||
| 134244d2d0 | |||
| 6dc6a97ae4 | |||
| 60f550c6b2 | |||
| 162ad66716 | |||
| 17fb0f8bb2 | |||
| 07f1afedca | |||
| 995435da89 | |||
| 4debce6892 | |||
| 5f18e7d05a | |||
| b789f70a84 | |||
| ec7b6de4e7 | |||
| 28534c5290 | |||
| ce467e87e3 | |||
| 839bfcc781 | |||
| 1f1d32aa57 | |||
| 18b8b0a395 | |||
| 49b6725a02 | |||
| fc1fdf64d2 | |||
| 6a652466f2 | |||
| a0fe4fc51c | |||
| 0e88a11db8 | |||
| 7c74978f38 | |||
| 67cbb3ff31 | |||
| 101f14479f | |||
| 7dad5d0862 | |||
| 57d06b34f2 | |||
| ab3163c21c | |||
| d7a2af15a6 | |||
| 4a04f411c0 | |||
| a381d6dc7f | |||
| 1a3ee4a06c | |||
| 0989e6f063 | |||
| b9e73d5a5a | |||
| 06bd9cfc2e | |||
| 86177fa45e | |||
| dc0c493af4 | |||
| 8313623c63 | |||
| 152aa3cca3 | |||
| 6b39935d8e | |||
| e928eeae57 | |||
| 321552224d | |||
| 3f1deada2e | |||
| 8166dd2ee8 | |||
| 360d2f7ab0 | |||
| 9689c60168 | |||
| be9ab7c8df | |||
| cf1213e280 | |||
| 6d87071756 | |||
| 4366a9cb67 | |||
| fe767dae21 | |||
| 2d86d54fe5 | |||
| 4402b77ec7 | |||
| 0df069383f | |||
| a8b4b64873 | |||
| f3f21bb64b | |||
| 74b421d434 | |||
| 07c7a66e3e | |||
| 2b642a57b9 | |||
| cb9ca9d735 | |||
| 21885d6a10 | |||
| 56520a33c6 | |||
| 6a91ba67cf | |||
| 50decaf915 | |||
| 10d30d18c4 | |||
| 5c2c689d47 | |||
| eefefed966 | |||
| 7af7fd12db | |||
| 87977b4ca5 | |||
| 5fdb23a28e | |||
| ba99bbd311 | |||
| f7a5693455 | |||
| 8ec77fc4f8 | |||
| 1f144a5cec | |||
| 3f1925b775 | |||
| 650b3fdf7b | |||
| f01dcbbde5 | |||
| 9b4e18c345 | |||
| 697702d497 | |||
| 8fc3dda18a | |||
| 26cf87a49a | |||
| 4b363b9c97 | |||
| ab82a4c805 | |||
| 9a3f9f2813 | |||
| 65e153aae8 | |||
| ea316a6d59 | |||
| ea4b8ef235 | |||
| 752495bbc8 | |||
| 59de353672 | |||
| a67eaa0646 | |||
| 2144d60d06 |
+3
-3
@@ -1,9 +1,9 @@
|
||||
[submodule "WebApp"]
|
||||
path = WebApp
|
||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApp.git
|
||||
url = ../WebApp.git
|
||||
[submodule "WebApi"]
|
||||
path = WebApi
|
||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApi.git
|
||||
url = ../WebApi.git
|
||||
[submodule "models"]
|
||||
path = models
|
||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/models.git
|
||||
url = ../models.git
|
||||
|
||||
@@ -13,6 +13,11 @@ class CelulasEscamosas(str, Enum):
|
||||
LIEAG = "LIEAG"
|
||||
CIS = "CIS"
|
||||
|
||||
class CelulasGlandulares(str, Enum):
|
||||
"""Resultado de células glandulares (Bethesda): atípicas o adenocarcinoma."""
|
||||
AGC = "AGC"
|
||||
ADENOCARCINOMA = "ADENOCARCINOMA"
|
||||
|
||||
CELULAS_ESCAMOSAS_ALIAS: dict[str,str] = {
|
||||
# Long forms, as the hospital platform is expected to write them
|
||||
"LESIÓN INTRAEPITELIAL ESCAMOSA DE BAJO GRADO (DISPLASIA LEVE Y/O VPH)": "LIEBG",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from core.cacu.paciente.enums import SexoBiologico, SEXO_BIOLOGICO_ALIAS
|
||||
from core.cacu.citologia_cervical.enums import CelulasEscamosas, CELULAS_ESCAMOSAS_ALIAS, CITO_CALIDAD_ESPECIMEN_ALIAS, ResultadoVPH
|
||||
from core.cacu.citologia_cervical.enums import CelulasEscamosas, CelulasGlandulares, CELULAS_ESCAMOSAS_ALIAS, CITO_CALIDAD_ESPECIMEN_ALIAS, ResultadoVPH
|
||||
from core.cacu.biopsia_cervical.enums import GradoCIN, GRADO_CIN_ALIAS
|
||||
from core.cacu.nota_medica.enums import TipoNota, TIPO_NOTA_ALIAS, Especialidad, ESPECIALIDAD_ALIAS, Parentesco, PARENTESCO_ALIAS, Dependencia, DEPENDENCIA_ALIAS
|
||||
from core.cacu.ordenes_estudio.enums import TipoEstudio, TIPO_ESTUDIO_ALIAS
|
||||
|
||||
@@ -26,7 +26,11 @@ valores = [
|
||||
|
||||
[citologia.resultados.celulas_glandulares]
|
||||
etiqueta = "Células glandulares"
|
||||
tipo_valor = "texto"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "AGC", etiqueta = "Células glandulares atípicas (AGC)" },
|
||||
{ valor = "ADENOCARCINOMA", etiqueta = "Adenocarcinoma" },
|
||||
]
|
||||
|
||||
[citologia.resultados.carcinoma_invasor]
|
||||
etiqueta = "Carcinoma invasor"
|
||||
|
||||
@@ -298,10 +298,11 @@ etiqueta = "Grado histológico (Nottingham)"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Grado histológico", "Grado de Nottingham", "Grado Scarff-Bloom-Richardson", "SBR"]
|
||||
buscar_en_texto = true
|
||||
valores = [
|
||||
{ valor = "G1", etiqueta = "Grado 1", alias = ["1", "I", "Grado I", "Bien diferenciado"] },
|
||||
{ valor = "G2", etiqueta = "Grado 2", alias = ["2", "II", "Grado II", "Moderadamente diferenciado"] },
|
||||
{ valor = "G3", etiqueta = "Grado 3", alias = ["3", "III", "Grado III", "Poco diferenciado"] },
|
||||
{ valor = "G1", etiqueta = "Grado 1", alias = ["1", "I", "Grado I", "Bien diferenciado", "1 de Nottingham", "Nottingham 1"] },
|
||||
{ valor = "G2", etiqueta = "Grado 2", alias = ["2", "II", "Grado II", "Moderadamente diferenciado", "2 de Nottingham", "Nottingham 2"] },
|
||||
{ valor = "G3", etiqueta = "Grado 3", alias = ["3", "III", "Grado III", "Poco diferenciado", "3 de Nottingham", "Nottingham 3"] },
|
||||
]
|
||||
|
||||
[biopsia.resultados.receptor_estrogeno]
|
||||
@@ -343,7 +344,7 @@ etiquetas_fuente = ["Receptores de progesterona", "Receptor de progesterona", "R
|
||||
etiqueta = "HER2 (inmunohistoquímica)"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["HER2", "HER-2", "HER2/neu", "C-erbB-2"]
|
||||
etiquetas_fuente = ["HER2/neu (IHQ)", "HER2 (IHQ)", "HER2 IHQ", "HER2", "HER-2", "HER2/neu", "C-erbB-2"]
|
||||
valores = [
|
||||
{ valor = "H0", etiqueta = "0", alias = ["0", "Negativo (0)", "Score 0"] },
|
||||
{ valor = "H1", etiqueta = "1+", alias = ["1+", "Negativo (1+)", "Score 1+"] },
|
||||
@@ -356,7 +357,7 @@ etiqueta = "Ki-67"
|
||||
tipo_valor = "numero"
|
||||
unidad = "%"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Ki-67", "Ki67", "Índice de proliferación"]
|
||||
etiquetas_fuente = ["Índice de proliferación Ki-67", "Índice de proliferación Ki67", "Ki-67", "Ki67", "Índice de proliferación"]
|
||||
|
||||
# The confirmation by in situ hybridization of an equivocal HER2 (Apéndice Informativo B: negative under 4 copies
|
||||
# per nucleus or a HER2/CEP17 ratio under 1.8, positive over 6 or over 2.2).
|
||||
|
||||
+330
-25
@@ -196,13 +196,40 @@ etiqueta = "Diagnóstico"
|
||||
tipo_valor = "externo"
|
||||
sistema = "CIE-10"
|
||||
|
||||
# The EEG: what its analysis writes. On the recording (`toma`), the sleep, channels, duration, the five quality
|
||||
# criteria and each metric's measured value; on each electrode (`parte`, `codigo_fuente` the electrode), the metric's
|
||||
# z-score there, under the same result.
|
||||
# The EEG: what its analysis (the `tea` library) writes. On the recording (`toma`): the verdict, triage level, clean
|
||||
# fraction, sleep, channels, duration and line noise; each study-wide quality check (`calidad_<check>`, with
|
||||
# `_anormal`, `_decisivo` and its limit, `_bajo` or `_alto`); and each metric's value with, against its age baseline, its z
|
||||
# (`_z`), -1/0/+1 (`_fuera`), the curve's p5, median and p95 there and the registered label of the baseline that curve
|
||||
# belongs to (`_modelo`). On each bad channel (`parte`, `codigo_fuente` the electrode): the check that flagged it, with
|
||||
# the library's reason. On each electrode of a metric (`parte`, `codigo_fuente` the electrode): the metric's value and z
|
||||
# there, under the same results.
|
||||
[eeg]
|
||||
etiqueta = "Electroencefalograma"
|
||||
codigos_hospital = ["EEG"]
|
||||
|
||||
[eeg.resultados.valido]
|
||||
etiqueta = "EEG válido para el estudio"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.nivel]
|
||||
etiqueta = "Nivel de triaje"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.fraccion_limpia]
|
||||
etiqueta = "Fracción del registro limpia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "fracción"
|
||||
|
||||
[eeg.resultados.canales_malos]
|
||||
etiqueta = "Canales malos"
|
||||
tipo_valor = "numero"
|
||||
unidad = "canales"
|
||||
|
||||
[eeg.resultados.edad_meses]
|
||||
etiqueta = "Edad al estudio"
|
||||
tipo_valor = "numero"
|
||||
unidad = "meses"
|
||||
|
||||
[eeg.resultados.con_sueno]
|
||||
etiqueta = "Registro con sueño"
|
||||
tipo_valor = "booleano"
|
||||
@@ -217,55 +244,333 @@ etiqueta = "Duración del registro"
|
||||
tipo_valor = "numero"
|
||||
unidad = "min"
|
||||
|
||||
[eeg.resultados.calidad_amplitud]
|
||||
etiqueta = "Canales con amplitud extrema"
|
||||
tipo_valor = "numero"
|
||||
unidad = "canales"
|
||||
|
||||
[eeg.resultados.calidad_alta_frecuencia]
|
||||
etiqueta = "Ruido de alta frecuencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "canales"
|
||||
|
||||
[eeg.resultados.calidad_correlacion]
|
||||
etiqueta = "Baja correlación entre canales"
|
||||
tipo_valor = "numero"
|
||||
unidad = "canales"
|
||||
|
||||
[eeg.resultados.calidad_sin_senal]
|
||||
etiqueta = "Canales planos o sin señal"
|
||||
tipo_valor = "numero"
|
||||
unidad = "canales"
|
||||
|
||||
[eeg.resultados.calidad_linea]
|
||||
[eeg.resultados.ruido_linea]
|
||||
etiqueta = "Ruido de la línea eléctrica"
|
||||
tipo_valor = "numero"
|
||||
unidad = "dB"
|
||||
|
||||
[eeg.resultados.calidad_clean_windows]
|
||||
etiqueta = "Ventanas limpias"
|
||||
tipo_valor = "numero"
|
||||
unidad = "%"
|
||||
|
||||
[eeg.resultados.calidad_clean_windows_anormal]
|
||||
etiqueta = "Ventanas limpias: fuera de rango"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_clean_windows_decisivo]
|
||||
etiqueta = "Ventanas limpias: basta para invalidar el EEG"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_clean_windows_bajo]
|
||||
etiqueta = "Ventanas limpias: límite inferior"
|
||||
tipo_valor = "numero"
|
||||
unidad = "%"
|
||||
|
||||
[eeg.resultados.calidad_internal_coverage]
|
||||
etiqueta = "Cobertura interna"
|
||||
tipo_valor = "numero"
|
||||
unidad = "fracción"
|
||||
|
||||
[eeg.resultados.calidad_internal_coverage_anormal]
|
||||
etiqueta = "Cobertura interna: fuera de rango"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_internal_coverage_decisivo]
|
||||
etiqueta = "Cobertura interna: basta para invalidar el EEG"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_internal_coverage_bajo]
|
||||
etiqueta = "Cobertura interna: límite inferior"
|
||||
tipo_valor = "numero"
|
||||
unidad = "fracción"
|
||||
|
||||
[eeg.resultados.calidad_bad_scalp_triage]
|
||||
etiqueta = "Electrodos del cuero cabelludo inservibles"
|
||||
tipo_valor = "numero"
|
||||
unidad = "electrodos"
|
||||
|
||||
[eeg.resultados.calidad_bad_scalp_triage_anormal]
|
||||
etiqueta = "Electrodos del cuero cabelludo inservibles: fuera de rango"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_bad_scalp_triage_decisivo]
|
||||
etiqueta = "Electrodos del cuero cabelludo inservibles: basta para invalidar el EEG"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_bad_scalp_triage_alto]
|
||||
etiqueta = "Electrodos del cuero cabelludo inservibles: límite superior"
|
||||
tipo_valor = "numero"
|
||||
unidad = "electrodos"
|
||||
|
||||
[eeg.resultados.calidad_usable_scalp]
|
||||
etiqueta = "Electrodos del cuero cabelludo útiles"
|
||||
tipo_valor = "numero"
|
||||
unidad = "electrodos"
|
||||
|
||||
[eeg.resultados.calidad_usable_scalp_anormal]
|
||||
etiqueta = "Electrodos del cuero cabelludo útiles: fuera de rango"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_usable_scalp_decisivo]
|
||||
etiqueta = "Electrodos del cuero cabelludo útiles: basta para invalidar el EEG"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_usable_scalp_bajo]
|
||||
etiqueta = "Electrodos del cuero cabelludo útiles: límite inferior"
|
||||
tipo_valor = "numero"
|
||||
unidad = "electrodos"
|
||||
|
||||
[eeg.resultados.calidad_triage_level]
|
||||
etiqueta = "Nivel de triaje"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_triage_level_anormal]
|
||||
etiqueta = "Nivel de triaje: fuera de rango"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_triage_level_decisivo]
|
||||
etiqueta = "Nivel de triaje: basta para invalidar el EEG"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_line_noise]
|
||||
etiqueta = "Ruido de la línea eléctrica"
|
||||
tipo_valor = "numero"
|
||||
unidad = "dB"
|
||||
|
||||
[eeg.resultados.calidad_line_noise_anormal]
|
||||
etiqueta = "Ruido de la línea eléctrica: fuera de rango"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_line_noise_decisivo]
|
||||
etiqueta = "Ruido de la línea eléctrica: basta para invalidar el EEG"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_line_noise_alto]
|
||||
etiqueta = "Ruido de la línea eléctrica: límite superior"
|
||||
tipo_valor = "numero"
|
||||
unidad = "dB"
|
||||
|
||||
[eeg.resultados.calidad_file]
|
||||
etiqueta = "Archivo EDF"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_file_anormal]
|
||||
etiqueta = "Archivo EDF: fuera de rango"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_file_decisivo]
|
||||
etiqueta = "Archivo EDF: basta para invalidar el EEG"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.calidad_dead_channel]
|
||||
etiqueta = "Canal muerto"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_frozen]
|
||||
etiqueta = "Señal congelada"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_saturated]
|
||||
etiqueta = "Señal saturada"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_inf_values]
|
||||
etiqueta = "Valores infinitos"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_own_gaps]
|
||||
etiqueta = "Huecos propios"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_bridge]
|
||||
etiqueta = "Puente con otro electrodo"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_amplitude]
|
||||
etiqueta = "Amplitud anómala frente al cuero cabelludo"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_aux_amplitude]
|
||||
etiqueta = "Amplitud fuera de rango (canal auxiliar)"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_does_not_correlate]
|
||||
etiqueta = "Sin correlación con sus vecinos"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_intermittent_contact]
|
||||
etiqueta = "Contacto intermitente"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.calidad_intermittent_bursts]
|
||||
etiqueta = "Contacto intermitente por ráfagas"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.ritmo_posterior]
|
||||
etiqueta = "Ritmo posterior"
|
||||
tipo_valor = "numero"
|
||||
unidad = "Hz"
|
||||
|
||||
[eeg.resultados.ritmo_posterior_z]
|
||||
etiqueta = "Ritmo posterior: puntaje z"
|
||||
tipo_valor = "numero"
|
||||
unidad = "z"
|
||||
|
||||
[eeg.resultados.ritmo_posterior_fuera]
|
||||
etiqueta = "Ritmo posterior: fuera de la referencia (-1, 0, +1)"
|
||||
tipo_valor = "numero"
|
||||
|
||||
[eeg.resultados.ritmo_posterior_p5]
|
||||
etiqueta = "Ritmo posterior: percentil 5 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "Hz"
|
||||
|
||||
[eeg.resultados.ritmo_posterior_mediana]
|
||||
etiqueta = "Ritmo posterior: mediana de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "Hz"
|
||||
|
||||
[eeg.resultados.ritmo_posterior_p95]
|
||||
etiqueta = "Ritmo posterior: percentil 95 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "Hz"
|
||||
|
||||
[eeg.resultados.ritmo_posterior_modelo]
|
||||
etiqueta = "Ritmo posterior: modelo de la referencia"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.husos_sueno_n2]
|
||||
etiqueta = "Husos de sueño N2"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.husos_sueno_n2_z]
|
||||
etiqueta = "Husos de sueño N2: puntaje z"
|
||||
tipo_valor = "numero"
|
||||
unidad = "z"
|
||||
|
||||
[eeg.resultados.husos_sueno_n2_fuera]
|
||||
etiqueta = "Husos de sueño N2: fuera de la referencia (-1, 0, +1)"
|
||||
tipo_valor = "numero"
|
||||
|
||||
[eeg.resultados.husos_sueno_n2_p5]
|
||||
etiqueta = "Husos de sueño N2: percentil 5 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.husos_sueno_n2_mediana]
|
||||
etiqueta = "Husos de sueño N2: mediana de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.husos_sueno_n2_p95]
|
||||
etiqueta = "Husos de sueño N2: percentil 95 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.husos_sueno_n2_modelo]
|
||||
etiqueta = "Husos de sueño N2: modelo de la referencia"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.husos_sueno_n3]
|
||||
etiqueta = "Husos de sueño N3"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.husos_sueno_n3_z]
|
||||
etiqueta = "Husos de sueño N3: puntaje z"
|
||||
tipo_valor = "numero"
|
||||
unidad = "z"
|
||||
|
||||
[eeg.resultados.husos_sueno_n3_fuera]
|
||||
etiqueta = "Husos de sueño N3: fuera de la referencia (-1, 0, +1)"
|
||||
tipo_valor = "numero"
|
||||
|
||||
[eeg.resultados.husos_sueno_n3_p5]
|
||||
etiqueta = "Husos de sueño N3: percentil 5 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.husos_sueno_n3_mediana]
|
||||
etiqueta = "Husos de sueño N3: mediana de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.husos_sueno_n3_p95]
|
||||
etiqueta = "Husos de sueño N3: percentil 95 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.husos_sueno_n3_modelo]
|
||||
etiqueta = "Husos de sueño N3: modelo de la referencia"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.picos_paroxisticos]
|
||||
etiqueta = "Picos paroxísticos"
|
||||
tipo_valor = "numero"
|
||||
unidad = "picos/min"
|
||||
|
||||
[eeg.resultados.picos_paroxisticos_z]
|
||||
etiqueta = "Picos paroxísticos: puntaje z"
|
||||
tipo_valor = "numero"
|
||||
unidad = "z"
|
||||
|
||||
[eeg.resultados.picos_paroxisticos_fuera]
|
||||
etiqueta = "Picos paroxísticos: fuera de la referencia (-1, 0, +1)"
|
||||
tipo_valor = "numero"
|
||||
|
||||
[eeg.resultados.picos_paroxisticos_p5]
|
||||
etiqueta = "Picos paroxísticos: percentil 5 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "picos/min"
|
||||
|
||||
[eeg.resultados.picos_paroxisticos_mediana]
|
||||
etiqueta = "Picos paroxísticos: mediana de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "picos/min"
|
||||
|
||||
[eeg.resultados.picos_paroxisticos_p95]
|
||||
etiqueta = "Picos paroxísticos: percentil 95 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "picos/min"
|
||||
|
||||
[eeg.resultados.picos_paroxisticos_modelo]
|
||||
etiqueta = "Picos paroxísticos: modelo de la referencia"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[eeg.resultados.gradiente_anteroposterior]
|
||||
etiqueta = "Gradiente anteroposterior"
|
||||
tipo_valor = "numero"
|
||||
unidad = "razón posterior/anterior"
|
||||
unidad = "pendiente"
|
||||
|
||||
[eeg.resultados.gradiente_anteroposterior_z]
|
||||
etiqueta = "Gradiente anteroposterior: puntaje z"
|
||||
tipo_valor = "numero"
|
||||
unidad = "z"
|
||||
|
||||
[eeg.resultados.gradiente_anteroposterior_fuera]
|
||||
etiqueta = "Gradiente anteroposterior: fuera de la referencia (-1, 0, +1)"
|
||||
tipo_valor = "numero"
|
||||
|
||||
[eeg.resultados.gradiente_anteroposterior_p5]
|
||||
etiqueta = "Gradiente anteroposterior: percentil 5 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "pendiente"
|
||||
|
||||
[eeg.resultados.gradiente_anteroposterior_mediana]
|
||||
etiqueta = "Gradiente anteroposterior: mediana de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "pendiente"
|
||||
|
||||
[eeg.resultados.gradiente_anteroposterior_p95]
|
||||
etiqueta = "Gradiente anteroposterior: percentil 95 de la referencia"
|
||||
tipo_valor = "numero"
|
||||
unidad = "pendiente"
|
||||
|
||||
[eeg.resultados.gradiente_anteroposterior_modelo]
|
||||
etiqueta = "Gradiente anteroposterior: modelo de la referencia"
|
||||
tipo_valor = "texto"
|
||||
|
||||
# An order (procedure of class `orden`): its `estudio_id` is the study it asks for, from `codigos_hospital`.
|
||||
[orden]
|
||||
|
||||
@@ -99,7 +99,9 @@ class EvaluacionRiesgoBase(SQLModel):
|
||||
evaluacion_id: int | None = Field(default=None, primary_key=True)
|
||||
lote_id: int = Field(foreign_key="evaluacion_riesgo_lote.lote_id", index=True)
|
||||
pac_id: int = Field(foreign_key="persona.pac_id") # subject
|
||||
horizonte_anios: float # prediction.when: años desde la fecha índice; 0 = prevalente
|
||||
# El punto de decisión desde el que el modelo predice para esta paciente (lo define el modelo, no la cohorte).
|
||||
fecha_indice: date
|
||||
horizonte_anios: float # prediction.when: años desde `fecha_indice`; 0 = prevalente
|
||||
probabilidad: float # prediction.probabilityDecimal, de 0 a 1
|
||||
# Incertidumbre, si el modelo la da (solo con un Hessiano definido positivo). Nula si no.
|
||||
ic_bajo: float | None = None
|
||||
|
||||
@@ -54,6 +54,34 @@ class MetricaEeg(str, Enum):
|
||||
GRADIENTE_ANTEROPOSTERIOR = "GRADIENTE_ANTEROPOSTERIOR"
|
||||
|
||||
|
||||
class NivelRelacionAdos2(str, Enum):
|
||||
"""rel_nivel and rel_tipo in table relacion_ados2: what the model relates, an ADOS-2 item or a domain."""
|
||||
ITEM = "item"
|
||||
DOMINIO = "dominio"
|
||||
|
||||
|
||||
class CriterioEeg(str, Enum):
|
||||
"""cri_codigo in table eeg_criterio: the EEG analysis's check codes, channel reasons without their numbers."""
|
||||
ARCHIVO = "file"
|
||||
VENTANAS_LIMPIAS = "clean-windows"
|
||||
COBERTURA_INTERNA = "internal-coverage"
|
||||
CUERO_CABELLUDO_MALO = "bad-scalp-triage"
|
||||
CUERO_CABELLUDO_UTIL = "usable-scalp"
|
||||
NIVEL_TRIAJE = "triage-level"
|
||||
RUIDO_LINEA = "line-noise"
|
||||
CANAL_MUERTO = "dead-channel"
|
||||
CONGELADO = "frozen"
|
||||
SATURADO = "saturated"
|
||||
VALORES_INF = "inf-values"
|
||||
HUECOS_PROPIOS = "own-gaps"
|
||||
PUENTE = "bridge"
|
||||
AMPLITUD = "amplitude"
|
||||
AMPLITUD_AUXILIAR = "aux-amplitude"
|
||||
SIN_CORRELACION = "does-not-correlate"
|
||||
CONTACTO_INTERMITENTE = "intermittent-contact"
|
||||
CONTACTO_POR_RAFAGAS = "intermittent-bursts"
|
||||
|
||||
|
||||
# The electrodes of the 10-20 system an electrode value can name (mel_electrodo).
|
||||
ELECTRODOS_10_20 = (
|
||||
"Fp1", "Fp2", "F7", "F3", "Fz", "F4", "F8", "T3", "C3", "Cz", "C4", "T4",
|
||||
|
||||
+129
-8
@@ -1,14 +1,15 @@
|
||||
"""TEA staging tables (data dictionary: spec/tablas_TEA.md).
|
||||
|
||||
One table per kind of study: the M-CHAT, the ADOS-2, the neuropediatrics note and the EEG, with the patients and
|
||||
the orders. The EEG's quality criteria, channels, duration, sleep, metrics and electrode values are written by the
|
||||
EEG analysis from the stored EDF.
|
||||
the orders. The EEG's verdict, quality checks, channels, duration, sleep, metrics and electrode values are written
|
||||
by the EEG analysis (the `tea` library) from the stored EDF. The ADOS-2 association model's cohort odds ratios and
|
||||
per-patient z and probability land in relacion_ados2 and relacion_ados2_paciente.
|
||||
|
||||
Permissive storage: every domain field is optional so a load never rejects a row; booleans are INTEGER and enums
|
||||
TEXT. Coercion and validation happen in the import schemas (WebApi/webapi/imports/schemas/tea).
|
||||
"""
|
||||
import uuid
|
||||
from datetime import date
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
import sqlalchemy as sa
|
||||
@@ -25,6 +26,37 @@ ADOS2_ITEMS = (
|
||||
)
|
||||
|
||||
|
||||
# The ADOS-2 algorithm items by what they measure: one code per item, the same in every module, with its label,
|
||||
# domain and its column code in each module that scores it. A column code is not one item across modules (`sa_b5` is
|
||||
# gaze integration in the Toddler module, shared enjoyment in Module 1, showing in Module 2), so the association
|
||||
# model's outcomes (`relacion_ados2.rel_resultado`) carry these codes, or `CSS` for the total severity score.
|
||||
ADOS2_ITEM_MEANINGS = {
|
||||
"ados2_item_01": ("Vocalización espontánea dirigida a otros", "SA", {"TODDLER": "sa_a2", "MODULO_1": "sa_a2"}),
|
||||
"ados2_item_02": ("Señalar", "SA", {"TODDLER": "sa_a7", "MODULO_1": "sa_a7", "MODULO_2": "sa_a6"}),
|
||||
"ados2_item_03": ("Gestos", "SA", {"TODDLER": "sa_a8", "MODULO_1": "sa_a8", "MODULO_2": "sa_a7"}),
|
||||
"ados2_item_04": ("Contacto visual inusual", "SA", {"TODDLER": "sa_b1", "MODULO_1": "sa_b1", "MODULO_2": "sa_b1"}),
|
||||
"ados2_item_05": ("Expresiones faciales dirigidas a otros", "SA", {"TODDLER": "sa_b4", "MODULO_1": "sa_b3", "MODULO_2": "sa_b2"}),
|
||||
"ados2_item_06": ("Integración de la mirada con otras conductas", "SA", {"TODDLER": "sa_b5", "MODULO_1": "sa_b4"}),
|
||||
"ados2_item_07": ("Disfrute compartido en la interacción", "SA", {"TODDLER": "sa_b6", "MODULO_1": "sa_b5", "MODULO_2": "sa_b3"}),
|
||||
"ados2_item_08": ("Respuesta al nombre", "SA", {"TODDLER": "sa_b7"}),
|
||||
"ados2_item_09": ("Búsqueda de atención cuando se le ignora", "SA", {"TODDLER": "sa_b8"}),
|
||||
"ados2_item_10": ("Pedir", "SA", {"TODDLER": "sa_b9"}),
|
||||
"ados2_item_11": ("Mostrar", "SA", {"TODDLER": "sa_b12", "MODULO_1": "sa_b9", "MODULO_2": "sa_b5"}),
|
||||
"ados2_item_12": ("Iniciación espontánea de la atención conjunta", "SA", {"TODDLER": "sa_b13", "MODULO_1": "sa_b10", "MODULO_2": "sa_b6"}),
|
||||
"ados2_item_13": ("Respuesta a la atención conjunta", "SA", {"TODDLER": "sa_b14", "MODULO_1": "sa_b11"}),
|
||||
"ados2_item_14": ("Calidad de los acercamientos sociales", "SA", {"TODDLER": "sa_b15", "MODULO_1": "sa_b12", "MODULO_2": "sa_b8"}),
|
||||
"ados2_item_15": ("Cantidad de acercamientos sociales al cuidador", "SA", {"TODDLER": "sa_b16b"}),
|
||||
"ados2_item_16": ("Cantidad de comunicación social recíproca", "SA", {"MODULO_2": "sa_b11"}),
|
||||
"ados2_item_17": ("Calidad general de la relación", "SA", {"TODDLER": "sa_b18", "MODULO_2": "sa_b12"}),
|
||||
"ados2_item_18": ("Entonación de vocalizaciones o verbalizaciones", "RRB", {"TODDLER": "rrb_a3", "MODULO_1": "rrb_a3"}),
|
||||
"ados2_item_19": ("Uso estereotipado o idiosincrático de palabras", "RRB", {"MODULO_1": "rrb_a5", "MODULO_2": "rrb_a4"}),
|
||||
"ados2_item_20": ("Interés sensorial inusual", "RRB", {"TODDLER": "rrb_d1", "MODULO_1": "rrb_d1", "MODULO_2": "rrb_d1"}),
|
||||
"ados2_item_21": ("Manierismos de manos y dedos", "RRB", {"TODDLER": "rrb_d2", "MODULO_1": "rrb_d2", "MODULO_2": "rrb_d2"}),
|
||||
"ados2_item_22": ("Intereses repetitivos o conductas estereotipadas", "RRB", {"TODDLER": "rrb_d5", "MODULO_1": "rrb_d4", "MODULO_2": "rrb_d4"}),
|
||||
}
|
||||
ADOS2_CSS = "CSS"
|
||||
|
||||
|
||||
def _uuid() -> str:
|
||||
return str(uuid.uuid4())
|
||||
|
||||
@@ -49,6 +81,10 @@ def _date() -> Field:
|
||||
return Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
|
||||
|
||||
def _datetime() -> Field:
|
||||
return Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
|
||||
|
||||
class Pacientes(TeaModel, table=True):
|
||||
__tablename__ = "pacientes"
|
||||
|
||||
@@ -152,13 +188,37 @@ class Eeg(TeaModel, table=True):
|
||||
eeg_con_sueno: Optional[int] = _int()
|
||||
eeg_canales: Optional[int] = _int()
|
||||
eeg_duracion_min: Optional[float] = _float()
|
||||
# Quality criteria: channels flagged by each one, and the line noise. An EEG is bad when any criterion is.
|
||||
eeg_canales_amplitud: Optional[int] = _int()
|
||||
eeg_canales_alta_frecuencia: Optional[int] = _int()
|
||||
eeg_canales_correlacion: Optional[int] = _int()
|
||||
eeg_canales_sin_senal: Optional[int] = _int()
|
||||
eeg_ruido_linea_db: Optional[float] = _float()
|
||||
eeg_estudio: Optional[bytes] = Field(default=None, sa_column=sa.Column(FileBlob)) # the EDF
|
||||
# The analysis's verdict: 1 valid, 0 not valid, null not analysed yet. Its checks are rows of eeg_criterio.
|
||||
eeg_valido: Optional[int] = _int()
|
||||
eeg_nivel: Optional[str] = _text() # triage level: completo, sin_referencia_auricular, parcial, no_analizable
|
||||
eeg_fraccion_limpia: Optional[float] = _float()
|
||||
eeg_canales_malos: Optional[int] = _int()
|
||||
eeg_edad_meses: Optional[float] = _float() # the age the analysis compared the metrics at
|
||||
# What produced the analysis, so a new plan or module version analyses the EEG again.
|
||||
eeg_plan_hash: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(16)))
|
||||
eeg_versiones: Optional[str] = _text()
|
||||
eeg_analizado_en: Optional[datetime] = _datetime()
|
||||
eeg_error: Optional[str] = _text()
|
||||
|
||||
|
||||
class EegCriterio(TeaModel, table=True):
|
||||
"""One quality check the EEG analysis evaluated on an EEG: a study rule, or a bad channel with its electrode."""
|
||||
|
||||
__tablename__ = "eeg_criterio"
|
||||
|
||||
cri_id: Optional[str] = _id()
|
||||
cri_eeg_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(36), index=True))
|
||||
cri_codigo: Optional[str] = _text() # CriterioEeg
|
||||
cri_electrodo: Optional[str] = _text()
|
||||
cri_valor: Optional[float] = _float()
|
||||
cri_valor_texto: Optional[str] = _text()
|
||||
cri_unidad: Optional[str] = _text()
|
||||
cri_bajo: Optional[float] = _float() # out of range below this
|
||||
cri_alto: Optional[float] = _float() # out of range above this
|
||||
cri_decisivo: Optional[int] = _int() # this check alone can make the EEG not valid
|
||||
cri_anormal: Optional[int] = _int()
|
||||
|
||||
|
||||
class EegMetrica(TeaModel, table=True):
|
||||
@@ -170,6 +230,13 @@ class EegMetrica(TeaModel, table=True):
|
||||
met_eeg_id: Optional[str] = _text()
|
||||
met_codigo: Optional[str] = _text() # MetricaEeg
|
||||
met_valor: Optional[float] = _float()
|
||||
# Against the age baseline at eeg_edad_meses: z, -1/0/+1 below p5 / within / above p95, and the curve there.
|
||||
met_z: Optional[float] = _float()
|
||||
met_fuera: Optional[int] = _int()
|
||||
met_p5: Optional[float] = _float()
|
||||
met_mediana: Optional[float] = _float()
|
||||
met_p95: Optional[float] = _float()
|
||||
met_modelo: Optional[str] = _text() # the baseline's registered model version
|
||||
|
||||
|
||||
class EegMetricaElectrodo(TeaModel, table=True):
|
||||
@@ -181,3 +248,57 @@ class EegMetricaElectrodo(TeaModel, table=True):
|
||||
mel_met_id: Optional[str] = _text()
|
||||
mel_electrodo: Optional[str] = _text()
|
||||
mel_valor: Optional[float] = _float()
|
||||
mel_z: Optional[float] = _float()
|
||||
|
||||
|
||||
class EegMetricaZona(TeaModel, table=True):
|
||||
"""A metric's value over one scalp zone (the `tea` library's zones), with its z against the zone's baseline."""
|
||||
|
||||
__tablename__ = "eeg_metrica_zona"
|
||||
|
||||
mez_id: Optional[str] = _id()
|
||||
mez_met_id: Optional[str] = _text()
|
||||
mez_zona: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32)))
|
||||
mez_valor: Optional[float] = _float()
|
||||
mez_z: Optional[float] = _float()
|
||||
|
||||
|
||||
class RelacionAdos2(TeaModel, table=True):
|
||||
"""One association of an EEG alteration in a scalp zone with an ADOS-2 outcome, per fitted model version."""
|
||||
|
||||
__tablename__ = "relacion_ados2"
|
||||
__table_args__ = (
|
||||
sa.UniqueConstraint("rel_version", "rel_biomarcador", "rel_zona", "rel_resultado", name="uq_relacion_ados2"),
|
||||
)
|
||||
|
||||
rel_id: Optional[str] = _id()
|
||||
# Bounded: the natural key the import layer and the tea library merge model rows on is a unique index.
|
||||
rel_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32), index=True))
|
||||
rel_nivel: Optional[str] = _text() # NivelRelacionAdos2: the model's level
|
||||
rel_validado: Optional[int] = _int() # 1 validated by the domain expert, 0 pending
|
||||
rel_n_cohorte: Optional[int] = _int()
|
||||
rel_biomarcador: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32))) # MetricaEeg
|
||||
rel_zona: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32))) # scalp zone code from the tea library
|
||||
rel_tipo: Optional[str] = _text() # NivelRelacionAdos2: the level this association relates
|
||||
rel_resultado: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32))) # ADOS-2 item or domain code
|
||||
rel_evento: Optional[str] = _text() # the outcome event, e.g. "score >= 2"
|
||||
rel_or: Optional[float] = _float()
|
||||
rel_ic_inf: Optional[float] = _float()
|
||||
rel_ic_sup: Optional[float] = _float()
|
||||
rel_q: Optional[float] = _float()
|
||||
|
||||
|
||||
class RelacionAdos2Paciente(TeaModel, table=True):
|
||||
"""One patient's z and model probability for an association row: the EEG's metric z mapped through relacion_ados2."""
|
||||
|
||||
__tablename__ = "relacion_ados2_paciente"
|
||||
__table_args__ = (
|
||||
sa.UniqueConstraint("rap_rel_id", "rap_eeg_id", name="uq_relacion_ados2_paciente"),
|
||||
)
|
||||
|
||||
rap_id: Optional[str] = _id()
|
||||
rap_rel_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(36), index=True))
|
||||
rap_eeg_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(36), index=True))
|
||||
rap_valor_z: Optional[float] = _float()
|
||||
rap_probabilidad: Optional[float] = _float()
|
||||
rap_probabilidad_referencia: Optional[float] = _float()
|
||||
|
||||
+110
-15
@@ -1,12 +1,15 @@
|
||||
# Diccionario de datos y reglas de validación — Proyecto TEA
|
||||
|
||||
Este documento describe el staging del proyecto: una tabla por tipo de estudio (M-CHAT, ADOS-2, nota de
|
||||
neuropediatría y EEG), más los pacientes y las órdenes. Para cada tabla se listan sus variables, el tipo de dato,
|
||||
neuropediatría y EEG), más los pacientes y las órdenes, y las dos del modelo de asociación con el ADOS-2
|
||||
(`relacion_ados2` y `relacion_ados2_paciente`). Para cada tabla se listan sus variables, el tipo de dato,
|
||||
la unidad (cuando aplica) y la validación que cumple cada una al importarse. El almacenamiento es permisivo: todo
|
||||
campo es opcional y la validación ocurre en los esquemas de importación (`WebApi/webapi/imports/schemas/tea`).
|
||||
|
||||
Las columnas marcadas **(análisis del EEG)** las escribe el análisis del EEG a partir del EDF guardado: calidad,
|
||||
canales, duración, sueño, métricas y valores por electrodo.
|
||||
Las columnas marcadas **(análisis del EEG)** las escribe el análisis del EEG (la biblioteca `tea`) a partir del EDF
|
||||
guardado: veredicto, criterios de calidad, canales, duración, sueño, métricas y valores por electrodo y por zona. Las dos
|
||||
tablas de asociación con el ADOS-2 las escribe el modelo de asociación (también la biblioteca `tea`), y mientras
|
||||
este llega la API de importación carga renglones de desarrollo igual que el resto del staging.
|
||||
|
||||
---
|
||||
|
||||
@@ -88,19 +91,46 @@ Los subtotales por dominio y el total no se guardan: son sumas de los puntajes d
|
||||
| `eeg_con_sueno` | INTEGER | — | 0 o 1. **(análisis del EEG)** | — |
|
||||
| `eeg_canales` | INTEGER | canales | Entre 1 y 256. **(análisis del EEG)** | — |
|
||||
| `eeg_duracion_min` | FLOAT | minutos | Mayor que 0. **(análisis del EEG)** | — |
|
||||
| `eeg_canales_amplitud` | INTEGER | canales | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
|
||||
| `eeg_canales_alta_frecuencia` | INTEGER | canales | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
|
||||
| `eeg_canales_correlacion` | INTEGER | canales | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
|
||||
| `eeg_canales_sin_senal` | INTEGER | canales | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
|
||||
| `eeg_ruido_linea_db` | FLOAT | dB | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
|
||||
| `eeg_ruido_linea_db` | FLOAT | dB | Mayor o igual que 0: la mediana del ruido de la línea eléctrica en el cuero cabelludo. **(análisis del EEG)** | — |
|
||||
| `eeg_estudio` | BLOB (LONGBLOB en MySQL) | — | El archivo EDF. | — |
|
||||
| `eeg_valido` | INTEGER | — | 1 válido, 0 no válido; nulo: sin analizar. **(análisis del EEG)** | — |
|
||||
| `eeg_nivel` | TEXT | — | Nivel de triaje: `completo`, `sin_referencia_auricular`, `parcial` o `no_analizable`. **(análisis del EEG)** | — |
|
||||
| `eeg_fraccion_limpia` | FLOAT | fracción | Entre 0 y 1: la parte del registro en ventanas limpias. **(análisis del EEG)** | — |
|
||||
| `eeg_canales_malos` | INTEGER | canales | Mayor o igual que 0. **(análisis del EEG)** | — |
|
||||
| `eeg_edad_meses` | FLOAT | meses | La edad a la fecha del estudio con que se compararon las métricas; nula sin fecha de nacimiento. **(análisis del EEG)** | — |
|
||||
| `eeg_plan_hash` | VARCHAR(16) | — | El plan de preprocesamiento con que se analizó. **(análisis del EEG)** | — |
|
||||
| `eeg_versiones` | TEXT | — | Las versiones de los módulos del análisis (`nombre=versión;…`). **(análisis del EEG)** | — |
|
||||
| `eeg_analizado_en` | DATETIME | — | Cuándo se analizó. **(análisis del EEG)** | — |
|
||||
| `eeg_error` | TEXT | — | Por qué el análisis no terminó; nulo si terminó. **(análisis del EEG)** | — |
|
||||
|
||||
Un EEG es malo cuando cualquiera de sus criterios de calidad está fuera de su umbral; uno malo no tiene resultado y
|
||||
sus alteraciones no cuentan.
|
||||
Un EEG es válido cuando el análisis lo dice (`eeg_valido` = 1): ninguna regla decisiva de `eeg_criterio` fuera de su
|
||||
umbral y el registro dentro de las condiciones del plan de preprocesamiento. Uno no válido no tiene resultado y sus
|
||||
alteraciones no cuentan.
|
||||
|
||||
---
|
||||
|
||||
## 7. Tabla `eeg_metrica` **(análisis del EEG)**
|
||||
## 7. Tabla `eeg_criterio` **(análisis del EEG)**
|
||||
|
||||
Un renglón por cada regla de calidad que el análisis evaluó sobre un EEG: las del estudio completo y, para cada canal
|
||||
malo, el motivo con su electrodo.
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `cri_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `cri_eeg_id` | VARCHAR(36), indexado | — | — | → `eeg.eeg_id` |
|
||||
| `cri_codigo` | TEXT | — | Catálogo `CriterioEeg`: del estudio `file, clean-windows, internal-coverage, bad-scalp-triage, usable-scalp, triage-level, line-noise`; de un canal `dead-channel, frozen, saturated, inf-values, own-gaps, bridge, amplitude, aux-amplitude, does-not-correlate, intermittent-contact, intermittent-bursts`. | — |
|
||||
| `cri_electrodo` | TEXT | — | El canal del motivo; nulo en las reglas del estudio. | — |
|
||||
| `cri_valor` | FLOAT | `cri_unidad` | El valor medido, si es un número. | — |
|
||||
| `cri_valor_texto` | TEXT | — | El valor o el motivo, si es un texto (por ejemplo, el nivel de triaje). | — |
|
||||
| `cri_unidad` | TEXT | — | `%`, `fraction`, `electrodes` o `dB`. | — |
|
||||
| `cri_bajo` | FLOAT | `cri_unidad` | Fuera de rango por debajo de este valor. | — |
|
||||
| `cri_alto` | FLOAT | `cri_unidad` | Fuera de rango por encima de este valor. | — |
|
||||
| `cri_decisivo` | INTEGER | — | 0 o 1: la regla basta, por sí sola, para que el EEG no sea válido. | — |
|
||||
| `cri_anormal` | INTEGER | — | 0 o 1. | — |
|
||||
|
||||
---
|
||||
|
||||
## 8. Tabla `eeg_metrica` **(análisis del EEG)**
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
@@ -108,16 +138,81 @@ sus alteraciones no cuentan.
|
||||
| `met_eeg_id` | TEXT | — | — | → `eeg.eeg_id` |
|
||||
| `met_codigo` | TEXT | — | Catálogo `MetricaEeg`: `RITMO_POSTERIOR, HUSOS_SUENO_N2, HUSOS_SUENO_N3, PICOS_PAROXISTICOS, GRADIENTE_ANTEROPOSTERIOR`. | — |
|
||||
| `met_valor` | FLOAT | la de la métrica | Nulo: la métrica no se puede evaluar (por ejemplo, husos sin registro de sueño). | — |
|
||||
|
||||
Solo se guarda el valor medido: el puntaje z y el estado salen de los rangos de referencia por grupo de edad.
|
||||
| `met_z` | FLOAT | puntaje z | Contra la curva de referencia de la métrica a `eeg_edad_meses`; nulo si la edad no está cubierta. | — |
|
||||
| `met_fuera` | INTEGER | — | -1 debajo del percentil 5, 0 dentro, +1 arriba del percentil 95. | — |
|
||||
| `met_p5` | FLOAT | la de la métrica | El percentil 5 de la curva a esa edad. | — |
|
||||
| `met_mediana` | FLOAT | la de la métrica | La mediana de la curva a esa edad. | — |
|
||||
| `met_p95` | FLOAT | la de la métrica | El percentil 95 de la curva a esa edad. | — |
|
||||
| `met_modelo` | TEXT | — | La versión registrada de la curva de referencia. | — |
|
||||
|
||||
---
|
||||
|
||||
## 8. Tabla `eeg_metrica_electrodo` **(análisis del EEG)**
|
||||
## 9. Tabla `eeg_metrica_electrodo` **(análisis del EEG)**
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `mel_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `mel_met_id` | TEXT | — | — | → `eeg_metrica.met_id` |
|
||||
| `mel_electrodo` | TEXT | — | Un electrodo del sistema 10-20 (`Fp1` … `O2`). | — |
|
||||
| `mel_valor` | FLOAT | puntaje z | — | — |
|
||||
| `mel_valor` | FLOAT | la de la métrica | — | — |
|
||||
| `mel_z` | FLOAT | puntaje z | Contra la curva de referencia del electrodo a `eeg_edad_meses`. | — |
|
||||
|
||||
---
|
||||
|
||||
## 10. Tabla `eeg_metrica_zona` **(análisis del EEG)**
|
||||
|
||||
El valor de una métrica en una zona del cuero cabelludo y su z contra la curva de referencia de esa zona. Las zonas
|
||||
son las de la biblioteca `tea` (`tea.contracts.ZONES`): `frontal_izq` (Fp1, F3, F7), `frontal_der` (Fp2, F4, F8),
|
||||
`frontal_media` (Fz), `central` (C3, Cz, C4), `parietal` (P3, Pz, P4), `temporal_izq` (T3, T5), `temporal_der`
|
||||
(T4, T6) y `occipital` (O1, O2). Es lo que lee el modelo de asociación con el ADOS-2.
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `mez_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `mez_met_id` | TEXT | — | — | → `eeg_metrica.met_id` |
|
||||
| `mez_zona` | VARCHAR(32) | — | El código de la zona. | — |
|
||||
| `mez_valor` | FLOAT | la de la métrica por electrodo de la zona | — | — |
|
||||
| `mez_z` | FLOAT | puntaje z | Contra la curva de referencia de la zona a `eeg_edad_meses`. | — |
|
||||
|
||||
---
|
||||
|
||||
## 11. Tabla `relacion_ados2`
|
||||
|
||||
Un renglón por versión del modelo y asociación: la razón de momios, en la cohorte, de una alteración del EEG en una
|
||||
zona del cuero cabelludo contra el desenlace de un reactivo o dominio del ADOS-2. La llave natural
|
||||
(`rel_version`, `rel_biomarcador`, `rel_zona`, `rel_resultado`) es única: es con la que la API de importación y la
|
||||
biblioteca `tea` unen renglones al cargar una versión del modelo.
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `rel_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `rel_version` | VARCHAR(32), indexado | — | La versión del modelo ajustado. | — |
|
||||
| `rel_nivel` | TEXT | — | Catálogo `NivelRelacionAdos2`: `item, dominio`. El nivel del modelo. | — |
|
||||
| `rel_validado` | INTEGER | — | 0 o 1: validado por el experto de dominio. | — |
|
||||
| `rel_n_cohorte` | INTEGER | pacientes | Mayor que 0: el tamaño de la cohorte con que se ajustó el modelo. | — |
|
||||
| `rel_biomarcador` | VARCHAR(32) | — | Catálogo `MetricaEeg`: la métrica del EEG asociada. | — |
|
||||
| `rel_zona` | VARCHAR(32) | — | El código de la zona del cuero cabelludo, el de la biblioteca `tea` (los de `eeg_metrica_zona`), `posterior` para el ritmo posterior o `global` para el gradiente. | — |
|
||||
| `rel_tipo` | TEXT | — | Catálogo `NivelRelacionAdos2`: `item, dominio`. El nivel que relaciona esta asociación. | — |
|
||||
| `rel_resultado` | VARCHAR(32) | — | Un reactivo del ADOS-2 por lo que mide, el mismo en todos los módulos (`ados2_item_01` … `ados2_item_22`, `ADOS2_ITEM_MEANINGS`: un mismo código de reactivo es otro reactivo en otro módulo), o `CSS`, el puntaje de severidad calibrado total. | — |
|
||||
| `rel_evento` | TEXT | — | El evento de desenlace como umbral legible por máquina sobre el puntaje del desenlace: `>=1` (el puntaje de algoritmo del reactivo en el módulo del niño) o `>=8` (el CSS). | — |
|
||||
| `rel_or` | FLOAT | razón de momios | Mayor que 0. | — |
|
||||
| `rel_ic_inf` | FLOAT | razón de momios | El límite inferior del intervalo de confianza; menor o igual que `rel_ic_sup`. | — |
|
||||
| `rel_ic_sup` | FLOAT | razón de momios | El límite superior del intervalo de confianza. | — |
|
||||
| `rel_q` | FLOAT | — | Entre 0 y 1: el valor q del ajuste por comparaciones múltiples. | — |
|
||||
|
||||
---
|
||||
|
||||
## 12. Tabla `relacion_ados2_paciente`
|
||||
|
||||
Un renglón por EEG y renglón del modelo: el z del paciente para la asociación y la probabilidad que el modelo le
|
||||
asigna. La pareja (`rap_rel_id`, `rap_eeg_id`) es única. El desenlace observado no se guarda: se lee del ADOS-2 del
|
||||
paciente (`ados2`).
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `rap_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `rap_rel_id` | VARCHAR(36), indexado | — | — | → `relacion_ados2.rel_id` |
|
||||
| `rap_eeg_id` | VARCHAR(36), indexado | — | — | → `eeg.eeg_id` |
|
||||
| `rap_valor_z` | FLOAT | puntaje z | El z del paciente en la asociación. | — |
|
||||
| `rap_probabilidad` | FLOAT | probabilidad | Entre 0 y 1: la probabilidad que da el modelo. | — |
|
||||
| `rap_probabilidad_referencia` | FLOAT | probabilidad | Entre 0 y 1: la probabilidad de referencia. | — |
|
||||
|
||||
@@ -83,6 +83,10 @@ def test_tea_tables_registered():
|
||||
"eeg",
|
||||
"eeg_metrica",
|
||||
"eeg_metrica_electrodo",
|
||||
"eeg_metrica_zona",
|
||||
"eeg_criterio",
|
||||
"relacion_ados2",
|
||||
"relacion_ados2_paciente",
|
||||
# indicadores_kit CDM, built from staging by the webapi.orquestacion graph.
|
||||
*INDICADORES_KIT_CDM,
|
||||
}
|
||||
@@ -115,3 +119,14 @@ def test_cat_mapeo_keeps_its_rules_in_the_schema():
|
||||
assert {"ck_cat_mapeo_clase", "ck_cat_mapeo_destino", "ck_cat_mapeo_vigencia", "fk_cat_mapeo_valor",
|
||||
"uq_cat_mapeo"} <= names
|
||||
assert "ck_cat_sistema_fuente_vigencia" in {c.name for c in CatSistemaFuente.__table__.constraints}
|
||||
|
||||
|
||||
def test_relacion_ados2_keeps_its_natural_keys_in_the_schema():
|
||||
"""Pins down: the import merge and the `tea` library upsert one `relacion_ados2` row per
|
||||
(rel_version, rel_biomarcador, rel_zona, rel_resultado), and one `relacion_ados2_paciente` row per
|
||||
(rap_rel_id, rap_eeg_id). Fails if either unique constraint is dropped, which would let two imports of
|
||||
the same model row or two probabilities for the same EEG and association both land."""
|
||||
from core.tea.models import RelacionAdos2, RelacionAdos2Paciente
|
||||
|
||||
assert "uq_relacion_ados2" in {c.name for c in RelacionAdos2.__table__.constraints}
|
||||
assert "uq_relacion_ados2_paciente" in {c.name for c in RelacionAdos2Paciente.__table__.constraints}
|
||||
|
||||
@@ -12,6 +12,7 @@ rest of the platform: WebApi gives it the fields to look for and stores what it
|
||||
| Records | `segmentation.py`, `records.py` | Pages split into records (by patient key, by page count, whole document) and records of the same key merged; the most confident value wins and confident disagreements are kept as conflicts. |
|
||||
| Letterhead | `template.py` | Margin lines that repeat across different patients' documents are the issuer's, and fill nothing. |
|
||||
| Candidates | `nlp/extractors.py` | Every reading of every field, each with how it was found (`ExtractedValue.features`): `LabeledValueExtractor` (caption and value, in columns too), `PatternExtractor` (values with a known shape), `FreeTextMentionExtractor` (catalog terms in prose), `MeasurementExtractor` (a number with its unit after its concept). |
|
||||
| Score tables | `nlp/score_tables.py` | Finds the ADOS-2 table, infers its variant from the item captions, and reads the positioned scores. |
|
||||
| Context | `nlp/context.py` | Whether the report affirms, denies, supposes, quotes from history or from the clinical request each mention (ConText and NegEx), and which section it sits in. |
|
||||
| Choice | `nlp/ranking.py` | One value per field: the most confident (`HeuristicRanker`) or a ranker learned from corrections (`LearnedRanker`). |
|
||||
| Measurement | `nlp/evaluation.py` | Precision, recall and F1 per field against an answer key. |
|
||||
@@ -22,6 +23,11 @@ what a denied mention means for a presence field (`NEGATED_VALUES`), units (`UNI
|
||||
about (`SUBJECTS`), section headings and trigger phrases. A report format with a caption or a term the extractor
|
||||
doesn't know is fixed there, without code changes.
|
||||
|
||||
Score-table layouts live in `SCORE_TABLES` in `nlp/vocabulary.py`. The extractor uses headings and item coverage
|
||||
to locate the table, including a restricted-behavior block continued on the next page. Item captions determine
|
||||
the module. Printed totals and the stated module are confidence checks. Ambiguous item sets leave the fields
|
||||
empty and expose `modulo_ambiguo` on the extracted record.
|
||||
|
||||
## What the rules do
|
||||
|
||||
- **Assertions.** A mention preceded, within its clause, by a negation ("sin", "negativo para"), a hypothetical
|
||||
|
||||
@@ -93,6 +93,8 @@ class LabelIndex:
|
||||
label before them, without being read themselves."""
|
||||
|
||||
def __init__(self, lines: Sequence[SegmentLine], specs: Iterable[FieldSpec]):
|
||||
self.score_tables: dict[str, dict[str, ExtractedValue]] = {}
|
||||
self.flags: set[str] = set()
|
||||
self.lines = list(lines)
|
||||
self.folded = [line.folded for line in self.lines]
|
||||
self.hits: list[list[LabelHit]] = [_label_hits(line, tuple(specs)) for line in self.lines]
|
||||
@@ -671,11 +673,15 @@ class MeasurementExtractor(FieldExtractor):
|
||||
yield ExtractedValue(value, confidence, self.method, line.text[match.start() : match.end()], line.evidence(), features)
|
||||
|
||||
|
||||
from extraction.nlp.score_tables import ScoreTableExtractor
|
||||
|
||||
|
||||
DEFAULT_EXTRACTORS: tuple[FieldExtractor, ...] = (
|
||||
LabeledValueExtractor(),
|
||||
PatternExtractor(),
|
||||
FreeTextMentionExtractor(),
|
||||
MeasurementExtractor(),
|
||||
ScoreTableExtractor(),
|
||||
)
|
||||
|
||||
|
||||
@@ -690,13 +696,17 @@ class RecordExtractor:
|
||||
self.extractors = list(extractors)
|
||||
self.ranker = ranker or HeuristicRanker()
|
||||
|
||||
def candidates(self, lines: Sequence[SegmentLine]) -> dict[str, list[ExtractedValue]]:
|
||||
def candidates(
|
||||
self, lines: Sequence[SegmentLine], *, flags: set[str] | None = None
|
||||
) -> dict[str, list[ExtractedValue]]:
|
||||
index = LabelIndex(lines, self.specs)
|
||||
found: dict[str, list[ExtractedValue]] = {}
|
||||
for spec in self.specs:
|
||||
proposed = [candidate for extractor in self.extractors for candidate in extractor.candidates(spec, index)]
|
||||
if proposed:
|
||||
found[spec.name] = describe_candidates(proposed)
|
||||
if flags is not None:
|
||||
flags.update(index.flags)
|
||||
return found
|
||||
|
||||
def choose(self, candidates: dict[str, list[ExtractedValue]]) -> dict[str, ExtractedValue]:
|
||||
|
||||
@@ -97,4 +97,5 @@ class ExtractedValue:
|
||||
"line": self.evidence.line,
|
||||
"bbox": self.evidence.bbox,
|
||||
"assertion": self.features.get("assertion"),
|
||||
**{flag: True for flag in ("totales_no_cuadran", "modulo_no_coincide") if self.features.get(flag)},
|
||||
}
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
"""Read item scores from positioned rows in clinical tables."""
|
||||
import re
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass
|
||||
from functools import cached_property
|
||||
from itertools import groupby
|
||||
|
||||
from extraction.nlp.extractors import FieldExtractor, LabelIndex, SegmentLine, _folded_label, _fuzzy_hits
|
||||
from extraction.nlp.fields import Evidence, ExtractedValue, FieldSpec
|
||||
from extraction.nlp.text import fold
|
||||
from extraction.nlp.vocabulary import SCORE_TABLES
|
||||
|
||||
COLUMN_TOLERANCE = 0.025
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScoreTable:
|
||||
"""Captions, score syntax, and variant-specific column mappings."""
|
||||
|
||||
anchors: tuple[str, ...]
|
||||
continuation_anchors: tuple[str, ...]
|
||||
end_markers: tuple[str, ...]
|
||||
variants: dict[str, dict[str, str]]
|
||||
totals: dict[str, tuple[str, ...]]
|
||||
value_pattern: str
|
||||
missing_token: str
|
||||
metadata: dict[str, dict[str, str]]
|
||||
printed_metadata: dict[str, tuple[str, str]]
|
||||
unmapped_items: dict[str, dict[str, str]]
|
||||
aliases: dict[str, tuple[str, ...]]
|
||||
|
||||
@cached_property
|
||||
def total_groups(self) -> dict[str, tuple[str, ...]]:
|
||||
return {_folded_label(label): prefixes for label, prefixes in self.totals.items()}
|
||||
|
||||
@cached_property
|
||||
def captions(self) -> dict[str, dict[str, str]]:
|
||||
return {
|
||||
variant: {
|
||||
_folded_label(caption): name
|
||||
for label, name in fields.items()
|
||||
for caption in (label, *self.aliases.get(label, ()))
|
||||
}
|
||||
for variant, fields in self.variants.items()
|
||||
}
|
||||
|
||||
@cached_property
|
||||
def descriptions(self) -> frozenset[str]:
|
||||
return frozenset(label for captions in self.captions.values() for label in captions)
|
||||
|
||||
@cached_property
|
||||
def fields(self) -> frozenset[str]:
|
||||
items = {name for fields in self.variants.values() for name in fields.values()}
|
||||
return frozenset(items.union(*(fields.keys() for fields in self.metadata.values())))
|
||||
|
||||
def match(self, caption: str) -> frozenset[str]:
|
||||
if caption in self.descriptions:
|
||||
return frozenset((caption,))
|
||||
scores = {
|
||||
label: hit.score
|
||||
for label in self.descriptions
|
||||
for hit in _fuzzy_hits(caption, label, label)
|
||||
if hit.start == 0 and hit.end == len(caption)
|
||||
}
|
||||
best = max(scores.values(), default=0.0)
|
||||
return frozenset(label for label, score in scores.items() if score == best)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Row:
|
||||
caption: str
|
||||
token: str
|
||||
evidence: Evidence
|
||||
labels: frozenset[str]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Page:
|
||||
lines: list[SegmentLine]
|
||||
rows: list[_Row]
|
||||
anchored: bool
|
||||
restricted: bool
|
||||
ended: bool
|
||||
|
||||
|
||||
class ScoreTableExtractor(FieldExtractor):
|
||||
"""Propose scores from the item set that best explains a table."""
|
||||
|
||||
method = "tabla_puntajes"
|
||||
|
||||
def __init__(self):
|
||||
self.tables = {name: ScoreTable(**config) for name, config in SCORE_TABLES.items()}
|
||||
|
||||
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterator[ExtractedValue]:
|
||||
for name, table in self.tables.items():
|
||||
if spec.name not in table.fields:
|
||||
continue
|
||||
if name not in index.score_tables:
|
||||
values, flags = self._read(table, index.lines)
|
||||
index.score_tables[name] = values
|
||||
index.flags.update(flags)
|
||||
candidate = index.score_tables[name].get(spec.name)
|
||||
if candidate is not None:
|
||||
yield candidate
|
||||
|
||||
def _read(self, table: ScoreTable, lines: list[SegmentLine]) -> tuple[dict[str, ExtractedValue], set[str]]:
|
||||
pages = [_read_page(table, list(group)) for _, group in
|
||||
groupby(lines, key=lambda line: (line.document, line.page_number))]
|
||||
best = None
|
||||
ambiguous = False
|
||||
for position, page in enumerate(pages):
|
||||
following = pages[position + 1] if position + 1 < len(pages) else None
|
||||
rows = page.rows
|
||||
if (
|
||||
following and page.rows and not page.restricted and not page.ended
|
||||
and following.restricted and following.lines[0].document == page.lines[0].document
|
||||
and following.lines[0].page_number == page.lines[0].page_number + 1
|
||||
):
|
||||
rows = rows + following.rows
|
||||
if not any(row.labels for row in rows):
|
||||
continue
|
||||
ranked = sorted(
|
||||
((_coverage(table, variant, rows), variant) for variant in table.variants),
|
||||
reverse=True,
|
||||
)
|
||||
score, variant = ranked[0]
|
||||
tied = len(ranked) > 1 and score == ranked[1][0]
|
||||
if score < (0.5 if page.anchored else 0.75):
|
||||
ambiguous |= tied or score < 0.5
|
||||
continue
|
||||
priority = (score, page.anchored)
|
||||
if best is None or priority > best[0]:
|
||||
best = priority, variant, tied, page, rows
|
||||
if best is None:
|
||||
return {}, {"modulo_ambiguo"} if ambiguous else set()
|
||||
_, variant, tied, page, rows = best
|
||||
if tied:
|
||||
return {}, {"modulo_ambiguo"}
|
||||
return self._values(table, variant, page, rows)
|
||||
|
||||
def _values(
|
||||
self, table: ScoreTable, variant: str, page: _Page, rows: list[_Row]
|
||||
) -> tuple[dict[str, ExtractedValue], set[str]]:
|
||||
scores = {}
|
||||
subtotal_items = {}
|
||||
totals = {}
|
||||
features = {}
|
||||
for row in rows:
|
||||
if row.token == table.missing_token:
|
||||
continue
|
||||
value = int(row.token)
|
||||
if row.caption in table.total_groups:
|
||||
totals.setdefault(table.total_groups[row.caption], []).append(value)
|
||||
continue
|
||||
if field := _field_for(table, variant, row):
|
||||
scores.setdefault(field, (value, row.token, row.evidence))
|
||||
elif prefix := _unmapped_prefix(table, variant, row):
|
||||
subtotal_items[row.caption] = (prefix, value)
|
||||
expected = set(table.total_groups.values())
|
||||
totals_match = bool(totals) and expected == totals.keys()
|
||||
for prefixes, printed in totals.items():
|
||||
actual = sum(value for field, (value, _, _) in scores.items() if field.startswith(prefixes))
|
||||
actual += sum(value for prefix, value in subtotal_items.values() if prefix in prefixes)
|
||||
totals_match &= all(value == actual for value in printed)
|
||||
confidence = 0.95 if totals_match else 0.6
|
||||
if not totals_match:
|
||||
features["totales_no_cuadran"] = True
|
||||
evidence = next(row.evidence for row in rows if _field_for(table, variant, row))
|
||||
for field, value in table.metadata.get(variant, {}).items():
|
||||
if field in table.printed_metadata:
|
||||
pattern, format_value = table.printed_metadata[field]
|
||||
printed = next((match for line in page.lines if (match := re.search(pattern, line.folded))), None)
|
||||
if printed and format_value.format(printed[1]) != value:
|
||||
features["modulo_no_coincide"] = True
|
||||
scores[field] = (value, str(value), evidence)
|
||||
if features.get("modulo_no_coincide"):
|
||||
confidence *= 0.8
|
||||
return {
|
||||
field: ExtractedValue(value, confidence, self.method, raw, source, features)
|
||||
for field, (value, raw, source) in scores.items()
|
||||
}, set(features)
|
||||
|
||||
|
||||
def _field_for(table: ScoreTable, variant: str, row: _Row) -> str | None:
|
||||
captions = table.captions[variant]
|
||||
matches = {captions[label] for label in row.labels if label in captions}
|
||||
return matches.pop() if len(matches) == 1 else None
|
||||
|
||||
|
||||
def _unmapped_prefix(table: ScoreTable, variant: str, row: _Row) -> str | None:
|
||||
return next((prefix for label, prefix in table.unmapped_items.get(variant, {}).items()
|
||||
if _folded_label(label) in row.labels), None)
|
||||
|
||||
|
||||
def _coverage(table: ScoreTable, variant: str, rows: list[_Row]) -> float:
|
||||
matched = set()
|
||||
foreign = 0
|
||||
count = 0
|
||||
for row in rows:
|
||||
if row.caption in table.total_groups or _unmapped_prefix(table, variant, row):
|
||||
continue
|
||||
count += 1
|
||||
if field := _field_for(table, variant, row):
|
||||
matched.add(field)
|
||||
else:
|
||||
foreign += 1
|
||||
return len(matched) / len(set(table.variants[variant].values())) - foreign / max(count, 1)
|
||||
|
||||
|
||||
def _read_page(table: ScoreTable, lines: list[SegmentLine]) -> _Page:
|
||||
anchors = {_folded_label(label) for label in table.anchors}
|
||||
continuation = {_folded_label(label) for label in table.continuation_anchors}
|
||||
end = {_folded_label(label) for label in table.end_markers}
|
||||
headings = [_folded_label(line.text) for line in lines]
|
||||
start = next((i for i, label in enumerate(headings) if label in anchors - continuation), 0)
|
||||
cells = []
|
||||
ended = False
|
||||
for line, heading in zip(lines[start:], headings[start:]):
|
||||
words = line.line.words
|
||||
if len(words) >= 2:
|
||||
token = fold(words[-1].text)
|
||||
caption = _folded_label(" ".join(word.text for word in words[:-1]))
|
||||
if token == table.missing_token or re.fullmatch(table.value_pattern, token) or (
|
||||
token.isdecimal() and caption in table.total_groups
|
||||
):
|
||||
cells.append((line, words[-1].center, caption, token))
|
||||
if caption in end:
|
||||
ended = True
|
||||
break
|
||||
continue
|
||||
cells.append((line, None, heading, ""))
|
||||
if heading in end:
|
||||
ended = True
|
||||
break
|
||||
|
||||
positions = [x for _, x, _, _ in cells if x is not None]
|
||||
if not positions:
|
||||
return _Page(lines, [], bool(anchors.intersection(headings)), bool(continuation.intersection(headings)), ended)
|
||||
column = max(positions, key=lambda x: (sum(abs(x - other) <= COLUMN_TOLERANCE for other in positions), x))
|
||||
rows = []
|
||||
previous = None
|
||||
for line, x, caption, token in cells:
|
||||
if x is None or abs(x - column) > COLUMN_TOLERANCE:
|
||||
previous = line if x is None and caption not in anchors else None
|
||||
continue
|
||||
evidence = line.evidence()
|
||||
labels = table.match(caption) if caption not in table.total_groups else frozenset()
|
||||
if not labels and caption not in table.total_groups and previous is not None:
|
||||
joined = f"{_folded_label(previous.text)} {caption}"
|
||||
if joined_labels := table.match(joined):
|
||||
caption, labels = joined, joined_labels
|
||||
first, last = previous.line.bbox, line.line.bbox
|
||||
bbox = [min(first.x0, last.x0), first.y0, max(first.x1, last.x1), last.y1]
|
||||
evidence = Evidence(line.document, line.page_number, f"{previous.text} {line.text}",
|
||||
[round(position, 4) for position in bbox])
|
||||
rows.append(_Row(caption, token, evidence, labels))
|
||||
previous = None
|
||||
return _Page(lines, rows, bool(anchors.intersection(headings)), bool(continuation.intersection(headings)), ended)
|
||||
@@ -135,7 +135,7 @@ CLINICAL_TERMS: dict[str, dict[str, object]] = {
|
||||
|
||||
# Columns worth looking for anywhere in the narrative, not only after a caption.
|
||||
FREE_TEXT_FIELDS = frozenset(
|
||||
{"cit_vph_resultado", "cit_celulas_escamosas", "bx_cin_grado", "bx_grado_histologico", "mast_birads", "nm_cie_codigo"}
|
||||
{"cit_vph_resultado", "cit_celulas_escamosas", "cit_celulas_glandulares", "bx_cin_grado", "bx_grado_histologico", "mast_birads", "nm_cie_codigo"}
|
||||
)
|
||||
|
||||
# Shape of a valid value.
|
||||
@@ -178,6 +178,7 @@ def _caption_from_description(description: str) -> str:
|
||||
# What a report is about, per target table: a document that names none of
|
||||
# these is probably a different kind of report (a biopsy read as a cytology).
|
||||
SUBJECTS: dict[str, tuple[str, ...]] = {
|
||||
"ados2": ("ADOS", "escala de observación para el diagnóstico del autismo"),
|
||||
"citologiacervical": ("citología", "citológico", "papanicolaou", "papanicolau", "bethesda", "virus del papiloma", "vph", "hpv"),
|
||||
"biopsiacervical": ("biopsia", "histopatológico", "histopatología", "histológico", "cono cervical", "conización"),
|
||||
"mastografia": ("mastografía", "mamografía", "mastográfico", "bi-rads", "birads", "tomosíntesis"),
|
||||
@@ -294,7 +295,7 @@ def _context_vocabulary() -> None:
|
||||
"no se descarta", "dudoso", "dudosa", "impresiona", "a considerar", "vs",
|
||||
),
|
||||
})
|
||||
PSEUDO_TRIGGERS = ("sin embargo", "no obstante", "no solo", "no sólo", "sin cambios", "no se descarta")
|
||||
PSEUDO_TRIGGERS = ("sin embargo", "no obstante", "no solo", "no sólo", "sin cambios", "no se descarta", "no especial")
|
||||
CLAUSE_TERMINATORS = ("pero", "aunque", "excepto", "salvo", "sin embargo", "no obstante")
|
||||
POST_NEGATIONS = ("no", "negativo", "negativa", "ausente", "ausentes", "no se observa", "no detectado", "no detectada", "descartado", "descartada")
|
||||
POST_AFFIRMATIONS = ("si", "sí", "positivo", "positiva", "presente", "presentes", "detectado", "detectada")
|
||||
@@ -372,6 +373,15 @@ CLINICAL_TERMS["cit_celulas_escamosas"].update({
|
||||
"DISPLASIA LEVE": "LIEBG", "DISPLASIA MODERADA": "LIEAG", "DISPLASIA GRAVE": "LIEAG", "DISPLASIA SEVERA": "LIEAG",
|
||||
"CARCINOMA IN SITU": "CIS", "NILM": "NORMAL",
|
||||
})
|
||||
# Glandular cells in cytology: atypical glandular cells (AGC) and adenocarcinoma.
|
||||
# Adenocarcinoma in situ has no catalog value and is deliberately not listed.
|
||||
CLINICAL_TERMS["cit_celulas_glandulares"] = {
|
||||
"CELULAS GLANDULARES ATIPICAS": "AGC", "ATIPIA DE CELULAS GLANDULARES": "AGC",
|
||||
"ATIPIA EN CELULAS GLANDULARES": "AGC", "AGC": "AGC", "ACG": "AGC",
|
||||
"ADENOCARCINOMA": "ADENOCARCINOMA", "ADENOCARCINOMA ENDOCERVICAL": "ADENOCARCINOMA",
|
||||
"ADENOCARCINOMA ENDOMETRIAL": "ADENOCARCINOMA",
|
||||
}
|
||||
SEVERITY["cit_celulas_glandulares"] = ("AGC", "ADENOCARCINOMA")
|
||||
CLINICAL_TERMS["bx_cin_grado"].update({
|
||||
"NIC1": "LIEBG", "NIC2": "LIEAG", "NIC3": "LIEAG", "CIN1": "LIEBG", "CIN2": "LIEAG", "CIN3": "LIEAG",
|
||||
"LIEBG": "LIEBG", "LIEAG": "LIEAG", "LIE DE BAJO GRADO": "LIEBG", "LIE DE ALTO GRADO": "LIEAG",
|
||||
@@ -395,3 +405,119 @@ FREE_TEXT_FIELDS = FREE_TEXT_FIELDS | {
|
||||
"eeg_distribucion_anormalidad", "eeg_lentificacion", "eeg_crisis_registradas", "eeg_respuesta_fotoestimulacion",
|
||||
"eeg_conclusion_categoria", "eeg_calidad_tecnica",
|
||||
}
|
||||
|
||||
|
||||
SCORE_TABLES = {
|
||||
"ados2": {
|
||||
"anchors": (
|
||||
"Afectación Social (AS)",
|
||||
"CRR",
|
||||
"Comportamiento restringido y repetitivo",
|
||||
"Comportamiento restringido y repetitivo (CRR)",
|
||||
),
|
||||
"continuation_anchors": (
|
||||
"CRR",
|
||||
"Comportamiento restringido y repetitivo",
|
||||
"Comportamiento restringido y repetitivo (CRR)",
|
||||
),
|
||||
"end_markers": ("Puntuación total global (AS + CRR)", "Puntuación total global", "Total global"),
|
||||
"totals": {
|
||||
"Total de afectación social": ("ado_sa_",),
|
||||
"Puntaje total de comportamiento restringido y repetitivo (CRR)": ("ado_rrb_",),
|
||||
"Total de comportamiento restringido y repetitivo": ("ado_rrb_",),
|
||||
"Total CRR": ("ado_rrb_",),
|
||||
"Puntuación total global (AS + CRR)": ("ado_sa_", "ado_rrb_"),
|
||||
"Puntuación total global": ("ado_sa_", "ado_rrb_"),
|
||||
"Total global": ("ado_sa_", "ado_rrb_"),
|
||||
},
|
||||
"value_pattern": r"[0-3]",
|
||||
"missing_token": "S/D",
|
||||
"metadata": {
|
||||
"few_words": {"ado_modulo": "MODULO_1", "ado_algoritmo": "Pocas o ninguna palabra"},
|
||||
"some_words": {"ado_modulo": "MODULO_1", "ado_algoritmo": "Algunas palabras"},
|
||||
"module_two": {"ado_modulo": "MODULO_2"},
|
||||
"module_three": {"ado_modulo": "MODULO_3", "ado_algoritmo": "Módulo 3"},
|
||||
},
|
||||
"printed_metadata": {"ado_modulo": (r"\bMODULO[ _]+([123])\b", "MODULO_{}")},
|
||||
"unmapped_items": {
|
||||
"module_three": {"Gestos descriptivos, convencionales, instrumentales o informativos": "ado_sa_"},
|
||||
},
|
||||
"variants": {
|
||||
"few_words": {
|
||||
"Frecuencia de la vocalización espontánea dirigida a otros": "ado_sa_a2",
|
||||
"Gestos": "ado_sa_a8",
|
||||
"Contacto visual inusual": "ado_sa_b1",
|
||||
"Expresiones faciales dirigidas a otros": "ado_sa_b3",
|
||||
"Integración de la mirada y otras conductas durante las iniciaciones sociales": "ado_sa_b4",
|
||||
"Disfrute compartido durante la interacción": "ado_sa_b5",
|
||||
"Mostrar": "ado_sa_b9",
|
||||
"Iniciación espontánea de la atención conjunta": "ado_sa_b10",
|
||||
"Respuesta a la atención conjunta": "ado_sa_b11",
|
||||
"Características de las iniciaciones sociales": "ado_sa_b12",
|
||||
"Entonación de las vocalizaciones o verbalizaciones": "ado_rrb_a3",
|
||||
"Interés sensorial inusual en los materiales de juego o en las personas": "ado_rrb_d1",
|
||||
"Manierismos de manos y dedos y otros manierismos complejos": "ado_rrb_d2",
|
||||
"Intereses inusualmente repetitivos o comportamientos estereotipados": "ado_rrb_d4",
|
||||
},
|
||||
"some_words": {
|
||||
"Frecuencia de la vocalización espontánea dirigida a otros": "ado_sa_a2",
|
||||
"Señalar": "ado_sa_a7",
|
||||
"Gestos": "ado_sa_a8",
|
||||
"Contacto visual inusual": "ado_sa_b1",
|
||||
"Expresiones faciales dirigidas a otros": "ado_sa_b3",
|
||||
"Integración de la mirada y otras conductas durante las iniciaciones sociales": "ado_sa_b4",
|
||||
"Disfrute compartido durante la interacción": "ado_sa_b5",
|
||||
"Mostrar": "ado_sa_b9",
|
||||
"Iniciación espontánea de la atención conjunta": "ado_sa_b10",
|
||||
"Características de las iniciaciones sociales": "ado_sa_b12",
|
||||
"Uso estereotipado o idiosincrásico de palabras o frases": "ado_rrb_a5",
|
||||
"Interés sensorial inusual en los materiales de juego o en las personas": "ado_rrb_d1",
|
||||
"Manierismos de manos y dedos y otros manierismos complejos": "ado_rrb_d2",
|
||||
"Intereses inusualmente repetitivos o comportamientos estereotipados": "ado_rrb_d4",
|
||||
},
|
||||
"module_two": {
|
||||
"Señalar": "ado_sa_a6",
|
||||
"Gestos descriptivos, convencionales, instrumentales o informativos": "ado_sa_a7",
|
||||
"Contacto visual inusual": "ado_sa_b1",
|
||||
"Expresiones faciales dirigidas a otros": "ado_sa_b2",
|
||||
"Disfrute compartido durante la interacción": "ado_sa_b3",
|
||||
"Mostrar": "ado_sa_b5",
|
||||
"Iniciación espontánea de la atención conjunta": "ado_sa_b6",
|
||||
"Características de las iniciaciones sociales": "ado_sa_b8",
|
||||
"Cantidad de comunicación social recíproca": "ado_sa_b11",
|
||||
"Calidad general de la relación": "ado_sa_b12",
|
||||
"Uso estereotipado o idiosincrásico de palabras o frases": "ado_rrb_a4",
|
||||
"Interés sensorial inusual en los materiales de juego o en las personas": "ado_rrb_d1",
|
||||
"Manierismos de manos y dedos y otros manierismos complejos": "ado_rrb_d2",
|
||||
"Intereses inusualmente repetitivos o comportamientos estereotipados": "ado_rrb_d4",
|
||||
},
|
||||
"module_three": {
|
||||
"Narración de sucesos": "ado_sa_a7",
|
||||
"Conversación": "ado_sa_a8",
|
||||
"Contacto visual inusual": "ado_sa_b1",
|
||||
"Expresiones faciales dirigidas al examinador": "ado_sa_b2",
|
||||
"Disfrute compartido durante la interacción": "ado_sa_b4",
|
||||
"Características de las iniciaciones sociales": "ado_sa_b7",
|
||||
"Calidad de la respuesta social": "ado_sa_b9",
|
||||
"Cantidad de comunicación social recíproca": "ado_sa_b10",
|
||||
"Calidad general de la relación": "ado_sa_b11",
|
||||
"Uso estereotipado o idiosincrásico de palabras o frases": "ado_rrb_a4",
|
||||
"Interés sensorial inusual en los materiales de juego o en las personas": "ado_rrb_d1",
|
||||
"Manierismos de manos y dedos y otros manierismos complejos": "ado_rrb_d2",
|
||||
"Interés excesivo en temas u objetos inusuales o altamente específicos": "ado_rrb_d4",
|
||||
},
|
||||
},
|
||||
"aliases": {
|
||||
"Frecuencia de la vocalización espontánea dirigida a otros": ('Vocalización espontánea dirigida a otros',),
|
||||
"Integración de la mirada y otras conductas durante las iniciaciones sociales": ('Integración de la mirada con otras conductas', 'Integración de la mirada'),
|
||||
"Disfrute compartido durante la interacción": ('Disfrute compartido en la interacción', 'Disfrute compartido'),
|
||||
"Características de las iniciaciones sociales": ('Calidad de los acercamientos sociales',),
|
||||
"Entonación de las vocalizaciones o verbalizaciones": ('Entonación de vocalizaciones o verbalizaciones',),
|
||||
"Uso estereotipado o idiosincrásico de palabras o frases": ('Uso estereotipado o idiosincrásico de palabras',),
|
||||
"Interés sensorial inusual en los materiales de juego o en las personas": ('Interés sensorial inusual',),
|
||||
"Manierismos de manos y dedos y otros manierismos complejos": ('Manierismos de manos y dedos',),
|
||||
"Intereses inusualmente repetitivos o comportamientos estereotipados": ('Intereses repetitivos o conductas estereotipadas',),
|
||||
"Gestos descriptivos, convencionales, instrumentales o informativos": ('Gestos',),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -62,6 +62,8 @@ class ExtractedRecord:
|
||||
# record it merges into turns out to be on topic.
|
||||
withheld: dict[str, ExtractedValue] = field(default_factory=dict)
|
||||
|
||||
flags: set[str] = field(default_factory=set)
|
||||
|
||||
def row(self) -> dict[str, Any]:
|
||||
return {name: extracted.value for name, extracted in self.values.items()}
|
||||
|
||||
@@ -104,6 +106,7 @@ class RecordMerger:
|
||||
target.images.extend(record.images)
|
||||
target.conflicts.extend(record.conflicts)
|
||||
target.discovered.extend(record.discovered)
|
||||
target.flags.update(record.flags)
|
||||
for name, proposed in record.candidates.items():
|
||||
target.candidates.setdefault(name, []).extend(proposed)
|
||||
if record.on_topic is not None and target.on_topic is not True:
|
||||
@@ -221,7 +224,8 @@ class DocumentExtractor:
|
||||
"""`template`: normalized texts of margin lines to read nothing from
|
||||
(`extraction.template`)."""
|
||||
lines = [line for line in segment.lines() if not (template and in_margin(line.line) and normalized(line.line) in template)]
|
||||
candidates = self.fields.candidates(lines)
|
||||
flags: set[str] = set()
|
||||
candidates = self.fields.candidates(lines, flags=flags)
|
||||
on_topic = self._on_topic(lines)
|
||||
if on_topic is not None:
|
||||
factor = 1.0 if on_topic else OFF_TOPIC_FACTOR
|
||||
@@ -259,6 +263,7 @@ class DocumentExtractor:
|
||||
candidates=candidates,
|
||||
on_topic=on_topic,
|
||||
withheld=withheld,
|
||||
flags=flags,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ from datetime import date
|
||||
from extraction.document import BBox, Line
|
||||
from extraction.nlp import FieldKind, FieldSpec, RecordExtractor, SegmentLine
|
||||
from extraction.nlp.text import find_date, find_decimal, find_integer, fold
|
||||
from extraction.nlp.vocabulary import CLINICAL_TERMS, SEVERITY, labels_for
|
||||
|
||||
SEXO = FieldSpec("pac_sexo", FieldKind.CHOICE, labels=("sexo",), choices={"F": "Femenino", "FEMENINO": "Femenino", "M": "Masculino"})
|
||||
NACIMIENTO = FieldSpec("pac_fecha_nacimiento", FieldKind.DATE, labels=("fecha de nacimiento", "f. nac"))
|
||||
@@ -23,6 +24,14 @@ CIN = FieldSpec(
|
||||
scan_free_text=True,
|
||||
)
|
||||
OBSERVACIONES = FieldSpec("cit_observaciones", FieldKind.TEXT, labels=("observaciones",), multiline=True)
|
||||
GLANDULARES = FieldSpec(
|
||||
"cit_celulas_glandulares",
|
||||
FieldKind.CHOICE,
|
||||
labels=labels_for("cit_celulas_glandulares"),
|
||||
choices=CLINICAL_TERMS["cit_celulas_glandulares"],
|
||||
scan_free_text=True,
|
||||
severity=SEVERITY["cit_celulas_glandulares"],
|
||||
)
|
||||
|
||||
|
||||
def lines(*texts: str, confidence: float = 1.0) -> list[SegmentLine]:
|
||||
@@ -103,3 +112,15 @@ def test_low_ocr_confidence_lowers_value_confidence():
|
||||
clean = RecordExtractor([SEXO]).extract(lines("Sexo: F"))["pac_sexo"].confidence
|
||||
noisy = RecordExtractor([SEXO]).extract(lines("Sexo: F", confidence=0.6))["pac_sexo"].confidence
|
||||
assert noisy < clean
|
||||
|
||||
|
||||
def test_glandular_atypical_cells_wording_maps_to_agc():
|
||||
"""Pins down that a cytology line naming atypical glandular cells maps to the catalog value AGC, using the vocabulary's glandular CLINICAL_TERMS as the field's choices. Fails if those terms are missing from the vocabulary, not built into the field, or mapped to another value."""
|
||||
found = RecordExtractor([GLANDULARES]).extract(lines("Células glandulares: células glandulares atípicas"))
|
||||
assert found["cit_celulas_glandulares"].value == "AGC"
|
||||
|
||||
|
||||
def test_adenocarcinoma_endocervical_wording_maps_to_adenocarcinoma():
|
||||
"""Pins down that a cytology line naming endocervical adenocarcinoma maps to the catalog value ADENOCARCINOMA through the vocabulary's glandular CLINICAL_TERMS. Fails if the term is missing from the vocabulary or mapped to AGC or to nothing."""
|
||||
found = RecordExtractor([GLANDULARES]).extract(lines("Células glandulares: adenocarcinoma endocervical"))
|
||||
assert found["cit_celulas_glandulares"].value == "ADENOCARCINOMA"
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
"""Cover ADOS-2 page selection, score extraction, and review flags.
|
||||
|
||||
Fixtures: none. PDF helpers draw template captions and scores in memory.
|
||||
"""
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
from reportlab.pdfgen.canvas import Canvas
|
||||
|
||||
from extraction import DocumentExtractor, FieldKind, FieldSpec, read_document
|
||||
from extraction.nlp.score_tables import ScoreTableExtractor
|
||||
|
||||
ITEMS = {
|
||||
1: (
|
||||
("sa_a2", "Frecuencia de la vocalización espontánea dirigida a otros"),
|
||||
("sa_a8", "Gestos"),
|
||||
("sa_b1", "Contacto visual inusual"),
|
||||
("sa_b3", "Expresiones faciales dirigidas a otros"),
|
||||
("sa_b4", "Integración de la mirada y otras conductas durante las iniciaciones sociales"),
|
||||
("sa_b5", "Disfrute compartido durante la interacción"),
|
||||
("sa_b9", "Mostrar"),
|
||||
("sa_b10", "Iniciación espontánea de la atención conjunta"),
|
||||
("sa_b11", "Respuesta a la atención conjunta"),
|
||||
("sa_b12", "Características de las iniciaciones sociales"),
|
||||
("rrb_a3", "Entonación de las vocalizaciones o verbalizaciones"),
|
||||
("rrb_d1", "Interés sensorial inusual en los materiales de juego o en las personas"),
|
||||
("rrb_d2", "Manierismos de manos y dedos y otros manierismos complejos"),
|
||||
("rrb_d4", "Intereses inusualmente repetitivos o comportamientos estereotipados"),
|
||||
),
|
||||
2: (
|
||||
("sa_a2", "Frecuencia de la vocalización espontánea dirigida a otros"),
|
||||
("sa_a7", "Señalar"),
|
||||
("sa_a8", "Gestos"),
|
||||
("sa_b1", "Contacto visual inusual"),
|
||||
("sa_b3", "Expresiones faciales dirigidas a otros"),
|
||||
("sa_b4", "Integración de la mirada y otras conductas durante las iniciaciones sociales"),
|
||||
("sa_b5", "Disfrute compartido durante la interacción"),
|
||||
("sa_b9", "Mostrar"),
|
||||
("sa_b10", "Iniciación espontánea de la atención conjunta"),
|
||||
("sa_b12", "Características de las iniciaciones sociales"),
|
||||
("rrb_a5", "Uso estereotipado o idiosincrásico de palabras o frases"),
|
||||
("rrb_d1", "Interés sensorial inusual en los materiales de juego o en las personas"),
|
||||
("rrb_d2", "Manierismos de manos y dedos y otros manierismos complejos"),
|
||||
("rrb_d4", "Intereses inusualmente repetitivos o comportamientos estereotipados"),
|
||||
),
|
||||
3: (
|
||||
("sa_a6", "Señalar"),
|
||||
("sa_a7", "Gestos descriptivos, convencionales, instrumentales o informativos"),
|
||||
("sa_b1", "Contacto visual inusual"),
|
||||
("sa_b2", "Expresiones faciales dirigidas a otros"),
|
||||
("sa_b3", "Disfrute compartido durante la interacción"),
|
||||
("sa_b5", "Mostrar"),
|
||||
("sa_b6", "Iniciación espontánea de la atención conjunta"),
|
||||
("sa_b8", "Características de las iniciaciones sociales"),
|
||||
("sa_b11", "Cantidad de comunicación social recíproca"),
|
||||
("sa_b12", "Calidad general de la relación"),
|
||||
("rrb_a4", "Uso estereotipado o idiosincrásico de palabras o frases"),
|
||||
("rrb_d1", "Interés sensorial inusual en los materiales de juego o en las personas"),
|
||||
("rrb_d2", "Manierismos de manos y dedos y otros manierismos complejos"),
|
||||
("rrb_d4", "Intereses inusualmente repetitivos o comportamientos estereotipados"),
|
||||
),
|
||||
4: (
|
||||
("sa_a7", "Narración de sucesos"),
|
||||
("sa_a8", "Conversación"),
|
||||
("sa_a9", "Gestos descriptivos, convencionales, instrumentales o informativos"),
|
||||
("sa_b1", "Contacto visual inusual"),
|
||||
("sa_b2", "Expresiones faciales dirigidas al examinador"),
|
||||
("sa_b4", "Disfrute compartido durante la interacción"),
|
||||
("sa_b7", "Características de las iniciaciones sociales"),
|
||||
("sa_b9", "Calidad de la respuesta social"),
|
||||
("sa_b10", "Cantidad de comunicación social recíproca"),
|
||||
("sa_b11", "Calidad general de la relación"),
|
||||
("rrb_a4", "Uso estereotipado o idiosincrásico de palabras o frases"),
|
||||
("rrb_d1", "Interés sensorial inusual en los materiales de juego o en las personas"),
|
||||
("rrb_d2", "Manierismos de manos y dedos y otros manierismos complejos"),
|
||||
("rrb_d4", "Interés excesivo en temas u objetos inusuales o altamente específicos"),
|
||||
),
|
||||
}
|
||||
MODULES = ("MODULO_1", "MODULO_1", "MODULO_2", "MODULO_3")
|
||||
ALGORITHMS = ("Pocas o ninguna palabra", "Algunas palabras", None, "Módulo 3")
|
||||
SPECS = [
|
||||
FieldSpec(f"ado_{key}", FieldKind.INTEGER)
|
||||
for key in sorted({key for items in ITEMS.values() for key, _ in items} - {"sa_a9"})
|
||||
] + [FieldSpec("ado_modulo", FieldKind.CHOICE), FieldSpec("ado_algoritmo")]
|
||||
|
||||
PROSE = [("Durante el seguimiento se describió afectación social en el informe psicológico.", None)]
|
||||
|
||||
|
||||
def table(variant, *, title=None, missing=None, wrap=None, wrong_total=False):
|
||||
social = restricted = 0
|
||||
restricted_started = False
|
||||
rows = [
|
||||
(title, None),
|
||||
("Afectación Social (AS)", None),
|
||||
("Comunicación", None),
|
||||
] if title else [("Afectación Social (AS)", None), ("Comunicación", None)]
|
||||
expected = {}
|
||||
for position, (key, caption) in enumerate(ITEMS[variant]):
|
||||
if key.startswith("rrb_") and not restricted_started:
|
||||
restricted_started = True
|
||||
rows.extend([
|
||||
("TOTAL DE AFECTACIÓN SOCIAL", social),
|
||||
("Comportamiento restringido y repetitivo (CRR)", None),
|
||||
])
|
||||
value = position % 4
|
||||
if key == missing:
|
||||
value = "S/D"
|
||||
else:
|
||||
if key.startswith("sa_"):
|
||||
social += value
|
||||
else:
|
||||
restricted += value
|
||||
if key != "sa_a9":
|
||||
expected[f"ado_{key}"] = value
|
||||
if key == wrap:
|
||||
first, caption = caption.split(" espontánea", 1)
|
||||
rows.append((first, None))
|
||||
caption = "espontánea" + caption
|
||||
rows.append((caption, value))
|
||||
rows.extend([
|
||||
("PUNTAJE TOTAL DE COMPORTAMIENTO RESTRINGIDO Y REPETITIVO (CRR)", restricted),
|
||||
("PUNTUACIÓN TOTAL GLOBAL (AS + CRR)", social + restricted + wrong_total),
|
||||
])
|
||||
return rows, expected
|
||||
|
||||
|
||||
def extract(pages, specs=SPECS, **kwargs):
|
||||
buffer = BytesIO()
|
||||
canvas = Canvas(buffer, pagesize=(612, 792))
|
||||
for rows in pages:
|
||||
canvas.setFont("Helvetica", 9)
|
||||
for position, (caption, value) in enumerate(rows):
|
||||
y = 730 - position * 24
|
||||
canvas.drawString(72, y, caption)
|
||||
if value is not None:
|
||||
canvas.drawCentredString(512, y, str(value))
|
||||
canvas.showPage()
|
||||
canvas.save()
|
||||
document = read_document("evaluation.pdf", buffer.getvalue())
|
||||
[record] = DocumentExtractor(specs, **kwargs).extract([document])
|
||||
return record
|
||||
|
||||
|
||||
@pytest.mark.parametrize("variant", range(1, 5))
|
||||
def test_variants(variant):
|
||||
"""Pins down: all template captions map to their module-specific columns. Fails if any score or metadata differs."""
|
||||
rows, expected = table(variant)
|
||||
expected["ado_modulo"] = MODULES[variant - 1]
|
||||
if algorithm := ALGORITHMS[variant - 1]:
|
||||
expected["ado_algoritmo"] = algorithm
|
||||
record = extract([rows])
|
||||
assert record.row() == expected
|
||||
assert all(value.method == "tabla_puntajes" and value.confidence == 0.95 for value in record.values.values())
|
||||
assert not record.flags
|
||||
|
||||
|
||||
def test_table_inside_long_report():
|
||||
"""Pins down: positioned rows identify the table page. Fails if prose about social affect selects another page."""
|
||||
rows, expected = table(3)
|
||||
record = extract([PROSE, PROSE, PROSE, rows, PROSE, PROSE])
|
||||
assert record.row() == {**expected, "ado_modulo": "MODULO_2"}
|
||||
assert {value.evidence.page_number for value in record.values.values()} == {4}
|
||||
|
||||
|
||||
def test_inferred_module_disagrees_with_title():
|
||||
"""Pins down: a conflicting title only lowers confidence. Fails if the title selects the module."""
|
||||
rows, expected = table(3, title="ADOS-2, módulo 1")
|
||||
record = extract([rows])
|
||||
assert record.row() == {**expected, "ado_modulo": "MODULO_2"}
|
||||
assert 0 < record.confidence < 0.95
|
||||
assert "modulo_no_coincide" in record.flags
|
||||
|
||||
|
||||
def test_shared_items_are_ambiguous():
|
||||
"""Pins down: shared items expose an ambiguity flag. Fails if shared captions alone fill a field."""
|
||||
record = extract([[
|
||||
("Afectación Social (AS)", None),
|
||||
("Contacto visual inusual", 1),
|
||||
("Interés sensorial inusual", 2),
|
||||
("Manierismos de manos y dedos", 0),
|
||||
]])
|
||||
assert record.row() == {}
|
||||
assert record.flags == {"modulo_ambiguo"}
|
||||
|
||||
|
||||
def test_missing_score():
|
||||
"""Pins down: S/D counts for inference and leaves its column empty. Fails if it becomes a value."""
|
||||
rows, expected = table(1, missing="sa_b11")
|
||||
record = extract([rows])
|
||||
assert record.row() == {**expected, "ado_modulo": "MODULO_1", "ado_algoritmo": ALGORITHMS[0]}
|
||||
assert record.confidence == 0.95
|
||||
|
||||
|
||||
def test_wrapped_caption():
|
||||
"""Pins down: two caption lines share one score and evidence box. Fails if the item is lost or clipped."""
|
||||
rows, expected = table(1, wrap="sa_a2")
|
||||
value = extract([rows]).values["ado_sa_a2"]
|
||||
assert value.value == expected["ado_sa_a2"]
|
||||
assert value.evidence.line.startswith("Frecuencia de la vocalización espontánea")
|
||||
assert value.evidence.bbox[3] - value.evidence.bbox[1] > 24 / 792
|
||||
|
||||
|
||||
def test_totals_disagree():
|
||||
"""Pins down: a wrong total lowers confidence to 0.6. Fails if a score or its review feature is lost."""
|
||||
rows, expected = table(3, wrong_total=True)
|
||||
record = extract([rows])
|
||||
assert record.row() == {**expected, "ado_modulo": "MODULO_2"}
|
||||
assert record.confidence == 0.6
|
||||
assert record.values["ado_sa_a6"].to_dict()["totales_no_cuadran"] is True
|
||||
|
||||
|
||||
def test_report_without_table():
|
||||
"""Pins down: prose alone has no table or flags. Fails if it fills a score or signals ambiguity."""
|
||||
record = extract([PROSE])
|
||||
assert record.row() == {}
|
||||
assert not record.flags
|
||||
|
||||
|
||||
def test_unrelated_field():
|
||||
"""Pins down: the table extractor only serves registered specs. Fails if a CaCu field gets a candidate."""
|
||||
rows, _ = table(3)
|
||||
spec = FieldSpec("cit_calidad_especimen", labels=("Contacto visual inusual",))
|
||||
assert extract([rows], [spec], extractors=[ScoreTableExtractor()]).candidates == {}
|
||||
|
||||
|
||||
def test_continuation_page():
|
||||
"""Pins down: the next page completes the restricted behavior block. Fails if its scores or totals are lost."""
|
||||
rows, expected = table(3)
|
||||
split = next(index for index, (label, _) in enumerate(rows) if label.startswith("Comportamiento"))
|
||||
record = extract([rows[:split], rows[split:]])
|
||||
assert record.row() == {**expected, "ado_modulo": "MODULO_2"}
|
||||
assert record.values["ado_rrb_d4"].evidence.page_number == 2
|
||||
assert record.confidence == 0.95
|
||||
|
||||
|
||||
def test_renamed_headings():
|
||||
"""Pins down: high coverage is enough without the anchors. Fails if the headings become mandatory."""
|
||||
rows, expected = table(4)
|
||||
rows = [(label, value) for label, value in rows
|
||||
if label not in {"Afectación Social (AS)", "Comportamiento restringido y repetitivo (CRR)"}]
|
||||
assert extract([rows]).row() == {**expected, "ado_modulo": "MODULO_3", "ado_algoritmo": "Módulo 3"}
|
||||
@@ -0,0 +1,37 @@
|
||||
"""risk index date
|
||||
|
||||
Each risk keeps the index date the model scored the patient from (`evaluacion_riesgo.fecha_indice`): the model
|
||||
defines its decision point, which needn't be the cohort member's. Existing risks take their member's index date in
|
||||
the batch's build, the one their horizons were counted from; then the column is required.
|
||||
|
||||
Revision ID: a1d4e7c20b31
|
||||
Revises: c3d8f5a20b47
|
||||
Create Date: 2026-11-20 21:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'a1d4e7c20b31'
|
||||
down_revision = 'c3d8f5a20b47'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('fecha_indice', sa.Date(), nullable=True))
|
||||
op.execute(
|
||||
"UPDATE evaluacion_riesgo SET fecha_indice = (SELECT m.fecha_indice FROM cohorte_miembro m "
|
||||
"JOIN evaluacion_riesgo_lote l ON l.armado_id = m.armado_id "
|
||||
"WHERE l.lote_id = evaluacion_riesgo.lote_id AND m.pac_id = evaluacion_riesgo.pac_id)"
|
||||
)
|
||||
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
|
||||
batch_op.alter_column('fecha_indice', existing_type=sa.Date(), nullable=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
|
||||
batch_op.drop_column('fecha_indice')
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
"""cacu heads joined
|
||||
|
||||
The date of death (`pac_fecha_defuncion`, `fecha_defuncion`) and the index date of each risk
|
||||
(`evaluacion_riesgo.fecha_indice`) were added on separate lines from the same revision; this joins them so the chain
|
||||
has one head again. Nothing to change on any engine.
|
||||
|
||||
Revision ID: e5b8d2a47c19
|
||||
Revises: c3d8f5a20b47, a1d4e7c20b31
|
||||
Create Date: 2026-11-21 02:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'e5b8d2a47c19'
|
||||
down_revision = ('c3d8f5a20b47', 'a1d4e7c20b31')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
pass
|
||||
@@ -0,0 +1,37 @@
|
||||
"""risk index date
|
||||
|
||||
Each risk keeps the index date the model scored the patient from (`evaluacion_riesgo.fecha_indice`): the model
|
||||
defines its decision point, which needn't be the cohort member's. Existing risks take their member's index date in
|
||||
the batch's build, the one their horizons were counted from; then the column is required.
|
||||
|
||||
Revision ID: b2e5f8d31c42
|
||||
Revises: a9c4e2f17d38
|
||||
Create Date: 2026-11-20 21:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'b2e5f8d31c42'
|
||||
down_revision = 'a9c4e2f17d38'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('fecha_indice', sa.Date(), nullable=True))
|
||||
op.execute(
|
||||
"UPDATE evaluacion_riesgo SET fecha_indice = (SELECT m.fecha_indice FROM cohorte_miembro m "
|
||||
"JOIN evaluacion_riesgo_lote l ON l.armado_id = m.armado_id "
|
||||
"WHERE l.lote_id = evaluacion_riesgo.lote_id AND m.pac_id = evaluacion_riesgo.pac_id)"
|
||||
)
|
||||
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
|
||||
batch_op.alter_column('fecha_indice', existing_type=sa.Date(), nullable=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
|
||||
batch_op.drop_column('fecha_indice')
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
"""cama heads joined
|
||||
|
||||
The date of death (`pac_fecha_defuncion`, `fecha_defuncion`) and the index date of each risk
|
||||
(`evaluacion_riesgo.fecha_indice`) were added on separate lines from the same revision; this joins them so the chain
|
||||
has one head again. Nothing to change on any engine.
|
||||
|
||||
Revision ID: d4a7c1e93b58
|
||||
Revises: a9c4e2f17d38, b2e5f8d31c42
|
||||
Create Date: 2026-11-21 00:30:00.000000
|
||||
|
||||
"""
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'd4a7c1e93b58'
|
||||
down_revision = ('a9c4e2f17d38', 'b2e5f8d31c42')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
pass
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
"""cama recurrence heads joined
|
||||
|
||||
The structured biopsy results, the treatment and follow-up tables and the recurrence variables (`c7e2a5f9b413`) were
|
||||
added on a separate line from the risk index date (`d4a7c1e93b58`); this joins them so the chain has one head again.
|
||||
Nothing to change on any engine.
|
||||
|
||||
Revision ID: e3b8a6d29f71
|
||||
Revises: d4a7c1e93b58, c7e2a5f9b413
|
||||
Create Date: 2026-11-22 09:45:00.000000
|
||||
|
||||
"""
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'e3b8a6d29f71'
|
||||
down_revision = ('d4a7c1e93b58', 'c7e2a5f9b413')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
pass
|
||||
@@ -135,10 +135,20 @@ class CohortRepository(Repository):
|
||||
evaluation's latest version is `final`. One horizon per `horizonte_anios`, at its latest version, ascending;
|
||||
horizons whose latest version is `entered-in-error` are left out. `None` if no batch of the patient is
|
||||
confirmed."""
|
||||
found = self.current_risks(pac_id, limit=1)
|
||||
return found[0] if found else None
|
||||
|
||||
def current_risks(self, pac_id: int, limit: int | None = None) -> "list[PatientRisk]":
|
||||
"""The patient's current batch of each outcome (`desenlace`), as `current_risk` picks one, newest first: a
|
||||
CIN2+ model's and a cancer model's risks are both current. `limit` stops after that many outcomes."""
|
||||
e = self.cohortes.EvaluacionRiesgo
|
||||
found: dict[str | None, PatientRisk] = {}
|
||||
with self._session_factory() as sesion:
|
||||
batches = sesion.exec(select(e.lote_id).where(e.pac_id == pac_id).distinct().order_by(e.lote_id.desc())).all()
|
||||
for lote_id in batches:
|
||||
batch = sesion.get(self.cohortes.EvaluacionRiesgoLote, lote_id)
|
||||
if batch.desenlace in found:
|
||||
continue
|
||||
latest = _latest_versions(sesion, e, lote_id)
|
||||
if not sesion.exec(select(e.evaluacion_id).join(latest, _same_version(e, latest))
|
||||
.where(e.lote_id == lote_id, e.estado == FINAL).limit(1)).first():
|
||||
@@ -146,11 +156,55 @@ class CohortRepository(Repository):
|
||||
rows = sesion.exec(select(e).join(latest, _same_version(e, latest))
|
||||
.where(e.lote_id == lote_id, e.pac_id == pac_id, e.estado != ERROR)
|
||||
.order_by(e.horizonte_anios)).all()
|
||||
batch = sesion.get(self.cohortes.EvaluacionRiesgoLote, lote_id)
|
||||
return PatientRisk(lote_id, batch.modelo_nombre, batch.modelo_version, batch.evaluado_en, FINAL,
|
||||
[RiskHorizon(r.horizonte_anios, r.probabilidad, r.ic_bajo, r.ic_alto, r.estado)
|
||||
for r in rows])
|
||||
return None
|
||||
found[batch.desenlace] = PatientRisk(
|
||||
lote_id, batch.modelo_nombre, batch.modelo_version, batch.evaluado_en, FINAL,
|
||||
[RiskHorizon(r.horizonte_anios, r.probabilidad, r.ic_bajo, r.ic_alto, r.estado) for r in rows],
|
||||
rows[0].fecha_indice if rows else None, batch.desenlace)
|
||||
if limit is not None and len(found) >= limit:
|
||||
break
|
||||
return list(found.values())
|
||||
|
||||
def current_risks_by_patient(self) -> "dict[str | None, dict[int, list[RiskHorizon]]]":
|
||||
"""Every patient's current risks of each outcome at once, as `current_risks` would give them one by one: per
|
||||
outcome, per `pac_id`, the horizons of the newest confirmed batch of that outcome that scored her. For lists
|
||||
of many patients (the follow-up list), where a query per patient is too slow."""
|
||||
e = self.cohortes.EvaluacionRiesgo
|
||||
lote = self.cohortes.EvaluacionRiesgoLote
|
||||
found: dict[str | None, dict[int, list[RiskHorizon]]] = {}
|
||||
with self._session_factory() as sesion:
|
||||
for batch in sesion.exec(select(lote).order_by(lote.lote_id.desc())).all():
|
||||
latest = _latest_versions(sesion, e, batch.lote_id)
|
||||
if not sesion.exec(select(e.evaluacion_id).join(latest, _same_version(e, latest))
|
||||
.where(e.lote_id == batch.lote_id, e.estado == FINAL).limit(1)).first():
|
||||
continue
|
||||
de_este = found.setdefault(batch.desenlace, {})
|
||||
nuevos: dict[int, list[RiskHorizon]] = {}
|
||||
for r in sesion.exec(select(e).join(latest, _same_version(e, latest))
|
||||
.where(e.lote_id == batch.lote_id, e.estado != ERROR)
|
||||
.order_by(e.pac_id, e.horizonte_anios)).all():
|
||||
if r.pac_id not in de_este:
|
||||
nuevos.setdefault(r.pac_id, []).append(
|
||||
RiskHorizon(r.horizonte_anios, r.probabilidad, r.ic_bajo, r.ic_alto, r.estado))
|
||||
de_este.update(nuevos)
|
||||
return found
|
||||
|
||||
def current_batches(self) -> "list[PatientRisk]":
|
||||
"""The domain's current batch of each outcome, whoever it scored: the highest `lote_id` of the outcome with
|
||||
some evaluation's latest version `final`, newest first, with no horizons. What tells a patient a model of
|
||||
that outcome exists although it didn't score her."""
|
||||
found: dict[str | None, PatientRisk] = {}
|
||||
lote = self.cohortes.EvaluacionRiesgoLote
|
||||
e = self.cohortes.EvaluacionRiesgo
|
||||
with self._session_factory() as sesion:
|
||||
for batch in sesion.exec(select(lote).order_by(lote.lote_id.desc())).all():
|
||||
if batch.desenlace in found:
|
||||
continue
|
||||
latest = _latest_versions(sesion, e, batch.lote_id)
|
||||
if sesion.exec(select(e.evaluacion_id).join(latest, _same_version(e, latest))
|
||||
.where(e.lote_id == batch.lote_id, e.estado == FINAL).limit(1)).first():
|
||||
found[batch.desenlace] = PatientRisk(batch.lote_id, batch.modelo_nombre, batch.modelo_version,
|
||||
batch.evaluado_en, FINAL, [], None, batch.desenlace)
|
||||
return list(found.values())
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -197,6 +251,8 @@ class PatientRisk:
|
||||
evaluado_en: datetime
|
||||
estado_lote: str
|
||||
horizontes: list[RiskHorizon]
|
||||
fecha_indice: date | None = None # the model's index date for the patient, which the horizons count from
|
||||
desenlace: str | None = None # the batch's outcome (FHIR `RiskAssessment.prediction.outcome`)
|
||||
|
||||
|
||||
def _latest_versions(sesion: Session, e, lote_id: int):
|
||||
@@ -284,12 +340,14 @@ def save_batch_in(
|
||||
armado_id: int,
|
||||
procedencia: dict,
|
||||
desenlace: str,
|
||||
riesgos: list[tuple[int, float, float, float | None, float | None]],
|
||||
riesgos: list[tuple[int, date, float, float, float | None, float | None]],
|
||||
*,
|
||||
cohortes: TablasCohorte,
|
||||
ahora: datetime | None = None,
|
||||
) -> tuple[int, bool]:
|
||||
"""Guarda los riesgos `(pac_id, horizonte_anios, probabilidad, ic_bajo, ic_alto)`. Devuelve (`lote_id`, nuevo).
|
||||
"""Guarda los riesgos `(pac_id, fecha_indice, horizonte_anios, probabilidad, ic_bajo, ic_alto)`. Devuelve
|
||||
(`lote_id`, nuevo). `fecha_indice` es el punto de decisión del modelo para esa paciente: una por paciente en el
|
||||
lote, la misma en todos sus horizontes.
|
||||
|
||||
No copia nada de MLflow: guarda sus llaves (`PROVENANCE`). Puntuar lo mismo
|
||||
otra vez (mismo armado, modelo y riesgos) no duplica: la huella del lote ya está.
|
||||
@@ -302,8 +360,15 @@ def save_batch_in(
|
||||
ajenos = sorted({pac for pac, *_ in riesgos} - miembros)
|
||||
if ajenos:
|
||||
raise RiskOutsideCohort(f"No son miembros del armado {armado_id}: {ajenos[:10]}.")
|
||||
fechas: dict[int, set] = {}
|
||||
for pac, fecha, *_ in riesgos:
|
||||
if fecha is None:
|
||||
raise ValueError("Un riesgo sin `fecha_indice`: el modelo debe decir desde cuándo predice.")
|
||||
fechas.setdefault(pac, set()).add(fecha)
|
||||
if varias := sorted(pac for pac, f in fechas.items() if len(f) > 1):
|
||||
raise ValueError(f"Más de una `fecha_indice` por paciente en el lote: {len(varias)} pacientes.")
|
||||
huella = _json_sha({"armado_id": armado_id, "desenlace": desenlace, **{c: procedencia[c] for c in PROVENANCE},
|
||||
"riesgos": sorted(riesgos)})
|
||||
"riesgos": sorted((pac, str(f), h, p, bajo, alto) for pac, f, h, p, bajo, alto in riesgos)})
|
||||
lote = cohortes.EvaluacionRiesgoLote
|
||||
previo = sesion.exec(select(lote).where(lote.huella == huella)).first()
|
||||
if previo is not None:
|
||||
@@ -315,9 +380,10 @@ def save_batch_in(
|
||||
sesion.add(fila)
|
||||
sesion.flush()
|
||||
sesion.add_all(
|
||||
cohortes.EvaluacionRiesgo(lote_id=fila.lote_id, pac_id=pac, horizonte_anios=float(h), probabilidad=float(p),
|
||||
ic_bajo=bajo, ic_alto=alto, version=1, estado=PRELIMINAR, registrado_en=momento)
|
||||
for pac, h, p, bajo, alto in riesgos
|
||||
cohortes.EvaluacionRiesgo(lote_id=fila.lote_id, pac_id=pac, fecha_indice=fecha, horizonte_anios=float(h),
|
||||
probabilidad=float(p), ic_bajo=bajo, ic_alto=alto, version=1, estado=PRELIMINAR,
|
||||
registrado_en=momento)
|
||||
for pac, fecha, h, p, bajo, alto in riesgos
|
||||
)
|
||||
sesion.commit()
|
||||
except Exception:
|
||||
@@ -347,7 +413,8 @@ def change_state_in(
|
||||
momento = ahora or datetime.now(timezone.utc)
|
||||
try:
|
||||
sesion.add_all(
|
||||
e(lote_id=lote_id, pac_id=v.pac_id, horizonte_anios=v.horizonte_anios, probabilidad=v.probabilidad,
|
||||
e(lote_id=lote_id, pac_id=v.pac_id, fecha_indice=v.fecha_indice, horizonte_anios=v.horizonte_anios,
|
||||
probabilidad=v.probabilidad,
|
||||
ic_bajo=v.ic_bajo, ic_alto=v.ic_alto, version=v.version + 1, estado=estado, motivo=motivo,
|
||||
registrado_en=momento)
|
||||
for v in vigentes
|
||||
|
||||
@@ -34,11 +34,15 @@ from core.tea.models import (
|
||||
Ados2,
|
||||
Eeg,
|
||||
EegMetrica,
|
||||
EegCriterio,
|
||||
EegMetricaElectrodo,
|
||||
EegMetricaZona,
|
||||
EvaluacionNeuropediatrica,
|
||||
Mchat,
|
||||
OrdenesEstudio,
|
||||
Pacientes,
|
||||
RelacionAdos2,
|
||||
RelacionAdos2Paciente,
|
||||
)
|
||||
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
@@ -74,6 +78,10 @@ evaluacion_neuropediatrica_repository = Repository(get_tea_session, EvaluacionNe
|
||||
eeg_repository = Repository(get_tea_session, Eeg)
|
||||
eeg_metrica_repository = Repository(get_tea_session, EegMetrica)
|
||||
eeg_metrica_electrodo_repository = Repository(get_tea_session, EegMetricaElectrodo)
|
||||
eeg_metrica_zona_repository = Repository(get_tea_session, EegMetricaZona)
|
||||
eeg_criterio_repository = Repository(get_tea_session, EegCriterio)
|
||||
relacion_ados2_repository = Repository(get_tea_session, RelacionAdos2)
|
||||
relacion_ados2_paciente_repository = Repository(get_tea_session, RelacionAdos2Paciente)
|
||||
|
||||
# indicadores_kit (Core/docs/ADR-004). Se leen con get/list/count; lo que
|
||||
# se escribe va por métodos de subclases (persistance/edges, por capa).
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"""tea eeg analysis
|
||||
|
||||
What the EEG analysis writes from the stored EDF: its verdict, triage level, clean fraction, bad channels, the age it
|
||||
compared the metrics at and what produced it, on `eeg`; one row per quality check in `eeg_criterio`; each metric's
|
||||
z, -1/0/+1 against the age baseline and the baseline's p5/median/p95 there, on `eeg_metrica`; each electrode's z, on
|
||||
`eeg_metrica_electrodo`. Only additions: nothing existing changes.
|
||||
|
||||
Revision ID: 16bf0b0ee3e4
|
||||
Revises: b9e4d2c71a05
|
||||
Create Date: 2026-11-19 13:14:08.006494
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '16bf0b0ee3e4'
|
||||
down_revision = 'b9e4d2c71a05'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table('eeg_criterio',
|
||||
sa.Column('cri_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('cri_eeg_id', sa.String(length=36), nullable=True),
|
||||
sa.Column('cri_codigo', sa.Text(), nullable=True),
|
||||
sa.Column('cri_electrodo', sa.Text(), nullable=True),
|
||||
sa.Column('cri_valor', sa.Float(), nullable=True),
|
||||
sa.Column('cri_valor_texto', sa.Text(), nullable=True),
|
||||
sa.Column('cri_unidad', sa.Text(), nullable=True),
|
||||
sa.Column('cri_bajo', sa.Float(), nullable=True),
|
||||
sa.Column('cri_alto', sa.Float(), nullable=True),
|
||||
sa.Column('cri_decisivo', sa.Integer(), nullable=True),
|
||||
sa.Column('cri_anormal', sa.Integer(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('cri_id')
|
||||
)
|
||||
with op.batch_alter_table('eeg_criterio', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_eeg_criterio_cri_eeg_id'), ['cri_eeg_id'], unique=False)
|
||||
|
||||
with op.batch_alter_table('eeg', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('eeg_valido', sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column('eeg_nivel', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('eeg_fraccion_limpia', sa.Float(), nullable=True))
|
||||
batch_op.add_column(sa.Column('eeg_canales_malos', sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column('eeg_edad_meses', sa.Float(), nullable=True))
|
||||
batch_op.add_column(sa.Column('eeg_plan_hash', sa.String(length=16), nullable=True))
|
||||
batch_op.add_column(sa.Column('eeg_versiones', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('eeg_analizado_en', sa.DateTime(), nullable=True))
|
||||
batch_op.add_column(sa.Column('eeg_error', sa.Text(), nullable=True))
|
||||
|
||||
with op.batch_alter_table('eeg_metrica', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('met_z', sa.Float(), nullable=True))
|
||||
batch_op.add_column(sa.Column('met_fuera', sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column('met_p5', sa.Float(), nullable=True))
|
||||
batch_op.add_column(sa.Column('met_mediana', sa.Float(), nullable=True))
|
||||
batch_op.add_column(sa.Column('met_p95', sa.Float(), nullable=True))
|
||||
batch_op.add_column(sa.Column('met_modelo', sa.Text(), nullable=True))
|
||||
|
||||
with op.batch_alter_table('eeg_metrica_electrodo', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('mel_z', sa.Float(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('eeg_metrica_electrodo', schema=None) as batch_op:
|
||||
batch_op.drop_column('mel_z')
|
||||
|
||||
with op.batch_alter_table('eeg_metrica', schema=None) as batch_op:
|
||||
batch_op.drop_column('met_modelo')
|
||||
batch_op.drop_column('met_p95')
|
||||
batch_op.drop_column('met_mediana')
|
||||
batch_op.drop_column('met_p5')
|
||||
batch_op.drop_column('met_fuera')
|
||||
batch_op.drop_column('met_z')
|
||||
|
||||
with op.batch_alter_table('eeg', schema=None) as batch_op:
|
||||
batch_op.drop_column('eeg_error')
|
||||
batch_op.drop_column('eeg_analizado_en')
|
||||
batch_op.drop_column('eeg_versiones')
|
||||
batch_op.drop_column('eeg_plan_hash')
|
||||
batch_op.drop_column('eeg_edad_meses')
|
||||
batch_op.drop_column('eeg_canales_malos')
|
||||
batch_op.drop_column('eeg_fraccion_limpia')
|
||||
batch_op.drop_column('eeg_nivel')
|
||||
batch_op.drop_column('eeg_valido')
|
||||
|
||||
with op.batch_alter_table('eeg_criterio', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_eeg_criterio_cri_eeg_id'))
|
||||
|
||||
op.drop_table('eeg_criterio')
|
||||
@@ -0,0 +1,70 @@
|
||||
"""tea ados2 association
|
||||
|
||||
What the ADOS-2 association model writes: one row per model version and association in `relacion_ados2`, the cohort
|
||||
odds ratio of an EEG alteration in a scalp zone against an ADOS-2 item or domain outcome, with its confidence
|
||||
interval and q value; one row per EEG and association in `relacion_ados2_paciente`, the patient's z and the
|
||||
probability the model gives them (the observed outcome stays in `ados2`, never stored here). Only additions:
|
||||
nothing existing changes.
|
||||
|
||||
Revision ID: 41694156d3a1
|
||||
Revises: c4306f438b3a
|
||||
Create Date: 2026-11-21 01:49:39.884071
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '41694156d3a1'
|
||||
down_revision = 'c4306f438b3a'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table('relacion_ados2',
|
||||
sa.Column('rel_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('rel_version', sa.String(length=32), nullable=True),
|
||||
sa.Column('rel_nivel', sa.Text(), nullable=True),
|
||||
sa.Column('rel_validado', sa.Integer(), nullable=True),
|
||||
sa.Column('rel_n_cohorte', sa.Integer(), nullable=True),
|
||||
sa.Column('rel_biomarcador', sa.String(length=32), nullable=True),
|
||||
sa.Column('rel_zona', sa.String(length=32), nullable=True),
|
||||
sa.Column('rel_tipo', sa.Text(), nullable=True),
|
||||
sa.Column('rel_resultado', sa.String(length=32), nullable=True),
|
||||
sa.Column('rel_evento', sa.Text(), nullable=True),
|
||||
sa.Column('rel_or', sa.Float(), nullable=True),
|
||||
sa.Column('rel_ic_inf', sa.Float(), nullable=True),
|
||||
sa.Column('rel_ic_sup', sa.Float(), nullable=True),
|
||||
sa.Column('rel_q', sa.Float(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('rel_id'),
|
||||
sa.UniqueConstraint('rel_version', 'rel_biomarcador', 'rel_zona', 'rel_resultado', name='uq_relacion_ados2')
|
||||
)
|
||||
with op.batch_alter_table('relacion_ados2', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_relacion_ados2_rel_version'), ['rel_version'], unique=False)
|
||||
|
||||
op.create_table('relacion_ados2_paciente',
|
||||
sa.Column('rap_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('rap_rel_id', sa.String(length=36), nullable=True),
|
||||
sa.Column('rap_eeg_id', sa.String(length=36), nullable=True),
|
||||
sa.Column('rap_valor_z', sa.Float(), nullable=True),
|
||||
sa.Column('rap_probabilidad', sa.Float(), nullable=True),
|
||||
sa.Column('rap_probabilidad_referencia', sa.Float(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('rap_id'),
|
||||
sa.UniqueConstraint('rap_rel_id', 'rap_eeg_id', name='uq_relacion_ados2_paciente')
|
||||
)
|
||||
with op.batch_alter_table('relacion_ados2_paciente', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_relacion_ados2_paciente_rap_eeg_id'), ['rap_eeg_id'], unique=False)
|
||||
batch_op.create_index(batch_op.f('ix_relacion_ados2_paciente_rap_rel_id'), ['rap_rel_id'], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('relacion_ados2_paciente', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_relacion_ados2_paciente_rap_rel_id'))
|
||||
batch_op.drop_index(batch_op.f('ix_relacion_ados2_paciente_rap_eeg_id'))
|
||||
|
||||
op.drop_table('relacion_ados2_paciente')
|
||||
with op.batch_alter_table('relacion_ados2', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_relacion_ados2_rel_version'))
|
||||
|
||||
op.drop_table('relacion_ados2')
|
||||
@@ -0,0 +1,34 @@
|
||||
"""tea eeg metric zones
|
||||
|
||||
What the EEG analysis writes per scalp zone: one row per metric and zone in `eeg_metrica_zona`, the metric's value
|
||||
over the zone's electrodes and its z against the zone's baseline, which the ADOS-2 association model reads. Only
|
||||
additions: nothing existing changes.
|
||||
|
||||
Revision ID: 98dadd777ffd
|
||||
Revises: e8c2a5d47f13
|
||||
Create Date: 2026-11-21 18:40:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '98dadd777ffd'
|
||||
down_revision = 'e8c2a5d47f13'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table('eeg_metrica_zona',
|
||||
sa.Column('mez_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('mez_met_id', sa.Text(), nullable=True),
|
||||
sa.Column('mez_zona', sa.String(length=32), nullable=True),
|
||||
sa.Column('mez_valor', sa.Float(), nullable=True),
|
||||
sa.Column('mez_z', sa.Float(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('mez_id')
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table('eeg_metrica_zona')
|
||||
@@ -0,0 +1,37 @@
|
||||
"""risk index date
|
||||
|
||||
Each risk keeps the index date the model scored the patient from (`evaluacion_riesgo.fecha_indice`): the model
|
||||
defines its decision point, which needn't be the cohort member's. Existing risks take their member's index date in
|
||||
the batch's build, the one their horizons were counted from; then the column is required.
|
||||
|
||||
Revision ID: c3f6a9e42d53
|
||||
Revises: c4306f438b3a
|
||||
Create Date: 2026-11-20 21:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'c3f6a9e42d53'
|
||||
down_revision = 'c4306f438b3a'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('fecha_indice', sa.Date(), nullable=True))
|
||||
op.execute(
|
||||
"UPDATE evaluacion_riesgo SET fecha_indice = (SELECT m.fecha_indice FROM cohorte_miembro m "
|
||||
"JOIN evaluacion_riesgo_lote l ON l.armado_id = m.armado_id "
|
||||
"WHERE l.lote_id = evaluacion_riesgo.lote_id AND m.pac_id = evaluacion_riesgo.pac_id)"
|
||||
)
|
||||
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
|
||||
batch_op.alter_column('fecha_indice', existing_type=sa.Date(), nullable=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
|
||||
batch_op.drop_column('fecha_indice')
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
"""tea eeg criteria columns dropped
|
||||
|
||||
The EEG analysis writes each quality check as a row of `eeg_criterio`, so the four fixed criterion columns of `eeg`
|
||||
go. Downgrade brings them back empty: the counts they held aren't kept anywhere else.
|
||||
|
||||
Revision ID: c4306f438b3a
|
||||
Revises: 16bf0b0ee3e4
|
||||
Create Date: 2026-11-19 14:09:04.196709
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'c4306f438b3a'
|
||||
down_revision = '16bf0b0ee3e4'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
COLUMNS = ('eeg_canales_amplitud', 'eeg_canales_alta_frecuencia', 'eeg_canales_correlacion', 'eeg_canales_sin_senal')
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('eeg', schema=None) as batch_op:
|
||||
for column in COLUMNS:
|
||||
batch_op.drop_column(column)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('eeg', schema=None) as batch_op:
|
||||
for column in COLUMNS:
|
||||
batch_op.add_column(sa.Column(column, sa.Integer(), nullable=True))
|
||||
@@ -0,0 +1,24 @@
|
||||
"""tea heads joined
|
||||
|
||||
The risk's index date (`evaluacion_riesgo.fecha_indice`) and the ADOS-2 association columns were added on separate lines from
|
||||
the same revision; this joins them so the chain has one head again. Nothing to change on any engine.
|
||||
|
||||
Revision ID: e8c2a5d47f13
|
||||
Revises: 41694156d3a1, c3f6a9e42d53
|
||||
Create Date: 2026-11-21 14:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'e8c2a5d47f13'
|
||||
down_revision = ('41694156d3a1', 'c3f6a9e42d53')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
pass
|
||||
@@ -1,5 +1,5 @@
|
||||
"""What this module covers: the per-patient reads of `CohortRepository` behind the risk route: `membership` (the
|
||||
patient in the cohort's latest build, with its variables) and `current_risk` (the current batch and its horizons).
|
||||
patient in the cohort's latest build, with its variables) and `current_risk` (the current batch and its horizons), `current_risks` (the current batch of each outcome) and `current_batches` (the domain's, whoever they scored).
|
||||
|
||||
Fixtures: `repository`, an in-memory SQLite database with the CaCu tables: builds 1 and 2 of the surveillance cohort
|
||||
(patient 10 in both, patient 20 only in build 1), patient 10's variables in build 2, and batches written and confirmed
|
||||
@@ -46,6 +46,9 @@ def repository():
|
||||
return CohortRepository(lambda: Session(engine), TABLES)
|
||||
|
||||
|
||||
D = date(2026, 3, 15) # the model's index date for patient 10, not her member's (2025-01-02)
|
||||
|
||||
|
||||
def _batch(repository, version, risks, armado_id=2):
|
||||
return repository.save_batch(armado_id, {**PROVENANCE, "modelo_version": version}, "cin2_12m", risks)[0]
|
||||
|
||||
@@ -63,7 +66,7 @@ def test_membership_is_in_the_latest_build_with_its_variables(repository):
|
||||
def test_an_unconfirmed_batch_is_not_current(repository):
|
||||
"""Pins down: a batch with only preliminary evaluations isn't shown. Fails if a risk nobody confirmed reaches the
|
||||
patient's record."""
|
||||
_batch(repository, "1", [(10, 1.0, 0.2, None, None)])
|
||||
_batch(repository, "1", [(10, D, 1.0, 0.2, None, None)])
|
||||
|
||||
assert repository.current_risk(10) is None
|
||||
|
||||
@@ -72,20 +75,74 @@ def test_the_current_batch_is_the_newest_confirmed_one_with_its_horizons(reposit
|
||||
"""Pins down: among confirmed batches the newest wins, even when a newer unconfirmed one exists; its horizons come
|
||||
in ascending order with their latest state. Fails if the newest batch is taken regardless of its state, or the
|
||||
horizons come unordered."""
|
||||
first = _batch(repository, "1", [(10, 3.0, 0.3, None, None), (10, 1.0, 0.1, 0.05, 0.2)])
|
||||
first = _batch(repository, "1", [(10, D, 3.0, 0.3, None, None), (10, D, 1.0, 0.1, 0.05, 0.2)])
|
||||
repository.change_state(first, "final", "revisado")
|
||||
_batch(repository, "2", [(10, 1.0, 0.9, None, None)])
|
||||
_batch(repository, "2", [(10, D, 1.0, 0.9, None, None)])
|
||||
|
||||
risk = repository.current_risk(10)
|
||||
|
||||
assert (risk.lote_id, risk.modelo_version, risk.estado_lote) == (first, "1", "final")
|
||||
assert (risk.lote_id, risk.modelo_version, risk.estado_lote, risk.fecha_indice) == (first, "1", "final", D)
|
||||
assert risk.horizontes == [RiskHorizon(1.0, 0.1, 0.05, 0.2, "final"), RiskHorizon(3.0, 0.3, None, None, "final")]
|
||||
|
||||
|
||||
def test_each_outcome_has_its_own_current_batch(repository):
|
||||
"""Pins down: a CIN2+ batch and a newer cancer batch are both current, newest first, and a newer confirmed batch
|
||||
of an outcome replaces the older one of the same outcome only. Fails if the newest batch hides the other
|
||||
outcome's risk, or two batches of one outcome are shown."""
|
||||
def batch(version, outcome, p):
|
||||
lote = repository.save_batch(2, {**PROVENANCE, "modelo_version": version}, outcome,
|
||||
[(10, D, 1.0, p, None, None)])[0]
|
||||
repository.change_state(lote, "final", "revisado")
|
||||
return lote
|
||||
|
||||
old_cin2, cancer, cin2 = batch("1", "cin2", 0.1), batch("1", "cancer", 0.01), batch("2", "cin2", 0.2)
|
||||
|
||||
found = repository.current_risks(10)
|
||||
|
||||
assert [(r.lote_id, r.desenlace) for r in found] == [(cin2, "cin2"), (cancer, "cancer")] and old_cin2 < cancer
|
||||
assert repository.current_risk(10).lote_id == cin2
|
||||
|
||||
|
||||
def test_the_domain_knows_each_outcomes_current_batch_whoever_it_scored(repository):
|
||||
"""Pins down: the current batch of each outcome is found even for a patient it didn't score, so her record can say
|
||||
the model exists but doesn't estimate her; an unconfirmed batch isn't current. Fails if `current_batches` reads
|
||||
only one patient's batches or takes a batch nobody confirmed."""
|
||||
cin2 = repository.save_batch(1, {**PROVENANCE, "modelo_version": "1"}, "cin2", [(20, D, 1.0, 0.1, None, None)])[0]
|
||||
repository.change_state(cin2, "final", "revisado")
|
||||
repository.save_batch(1, {**PROVENANCE, "modelo_version": "2"}, "cancer", [(20, D, 1.0, 0.01, None, None)])
|
||||
|
||||
found = repository.current_batches()
|
||||
|
||||
assert [(r.lote_id, r.desenlace, r.horizontes) for r in found] == [(cin2, "cin2", [])]
|
||||
assert repository.current_risks(10) == []
|
||||
|
||||
|
||||
def test_every_patients_current_risks_at_once_match_one_by_one(repository):
|
||||
"""Pins down: `current_risks_by_patient` gives, per outcome, each patient's horizons of the newest confirmed batch
|
||||
that scored her, the same as `current_risks` patient by patient; an unconfirmed batch is left out. Fails if a
|
||||
newer batch that didn't score a patient hides her older one, or a pending batch reaches the follow-up list."""
|
||||
def batch(armado, version, outcome, rows, confirm=True):
|
||||
lote = repository.save_batch(armado, {**PROVENANCE, "modelo_version": version}, outcome, rows)[0]
|
||||
if confirm:
|
||||
repository.change_state(lote, "final", "revisado")
|
||||
return lote
|
||||
|
||||
batch(1, "1", "cin2", [(10, D, 1.0, 0.1, None, None), (20, D, 1.0, 0.2, None, None)])
|
||||
batch(2, "2", "cin2", [(10, D, 1.0, 0.3, 0.2, 0.4)])
|
||||
batch(2, "3", "cin2", [(10, D, 1.0, 0.9, None, None)], confirm=False)
|
||||
batch(1, "1", "cancer", [(20, D, 1.0, 0.01, None, None)])
|
||||
|
||||
found = repository.current_risks_by_patient()
|
||||
|
||||
assert {o: {p: [h.probabilidad for h in hs] for p, hs in by.items()} for o, by in found.items()} == {
|
||||
"cin2": {10: [0.3], 20: [0.2]}, "cancer": {20: [0.01]}}
|
||||
assert found["cin2"][10] == repository.current_risks(10)[0].horizontes
|
||||
|
||||
|
||||
def test_an_annulled_batch_is_no_longer_current(repository):
|
||||
"""Pins down: once a confirmed batch is marked `entered-in-error`, its latest versions aren't final and it stops
|
||||
being current. Fails if any version ever confirmed keeps a withdrawn risk on the record."""
|
||||
first = _batch(repository, "1", [(10, 1.0, 0.1, None, None)])
|
||||
first = _batch(repository, "1", [(10, D, 1.0, 0.1, None, None)])
|
||||
repository.change_state(first, "final", "revisado")
|
||||
repository.change_state(first, "entered-in-error", "modelo equivocado")
|
||||
|
||||
@@ -95,9 +152,9 @@ def test_an_annulled_batch_is_no_longer_current(repository):
|
||||
def test_pending_batches_are_the_ones_with_no_decision_yet(repository):
|
||||
"""Pins down: a batch stays pending until it's confirmed or voided, newest first, and dropping off the list is
|
||||
permanent either way. Fails if a confirmed or a voided batch is still listed, or the order is reversed."""
|
||||
first = _batch(repository, "1", [(10, 1.0, 0.1, None, None)])
|
||||
second = _batch(repository, "2", [(10, 1.0, 0.2, None, None)])
|
||||
third = _batch(repository, "3", [(10, 1.0, 0.3, None, None)])
|
||||
first = _batch(repository, "1", [(10, D, 1.0, 0.1, None, None)])
|
||||
second = _batch(repository, "2", [(10, D, 1.0, 0.2, None, None)])
|
||||
third = _batch(repository, "3", [(10, D, 1.0, 0.3, None, None)])
|
||||
repository.change_state(second, "final", "revisado")
|
||||
|
||||
pending = repository.pending_batches()
|
||||
@@ -108,3 +165,17 @@ def test_pending_batches_are_the_ones_with_no_decision_yet(repository):
|
||||
repository.change_state(third, "entered-in-error", "modelo equivocado")
|
||||
|
||||
assert [b.lote_id for b in repository.pending_batches()] == [first]
|
||||
|
||||
|
||||
def test_a_risk_needs_one_index_date_per_patient(repository):
|
||||
"""Pins down: each risk carries the model's index date for its patient, kept through a change of state, and a
|
||||
batch with no date or two dates for one patient is refused. Fails if the horizons could count from different dates
|
||||
or from none."""
|
||||
with pytest.raises(ValueError, match="sin `fecha_indice`"):
|
||||
_batch(repository, "1", [(10, None, 1.0, 0.1, None, None)])
|
||||
with pytest.raises(ValueError, match="Más de una"):
|
||||
_batch(repository, "1", [(10, D, 1.0, 0.1, None, None), (10, date(2026, 1, 1), 3.0, 0.3, None, None)])
|
||||
lote = _batch(repository, "1", [(10, D, 1.0, 0.1, None, None)])
|
||||
repository.change_state(lote, "final", "revisado")
|
||||
|
||||
assert repository.current_risk(10).fecha_indice == D
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"""What this module covers: the TEA Alembic chain in `persistance/tea/alembic`, applied through
|
||||
`alembic.command` to a throwaway SQLite file: the deployed schema has the ADOS-2 association tables with
|
||||
their natural keys, `eeg_metrica_zona` exists, downgrading each of those revisions removes exactly its tables,
|
||||
and the migrated schema never drifts from `core.tea.models`.
|
||||
|
||||
Fixtures: `url_tea` points `settings.tea_database_url` at a temp file and runs `upgrade head`, so a broken
|
||||
migration fails the suite instead of the tests silently building the schema with `create_all`; it restores
|
||||
the original URL and clears the cached engine afterwards (`persistance.db` caches engines per URL).
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
from sqlalchemy import create_engine, inspect
|
||||
|
||||
import persistance
|
||||
from persistance import db as persistance_db
|
||||
from persistance.settings import settings
|
||||
|
||||
|
||||
def _config() -> Config:
|
||||
ini = Path(persistance.__file__).parent / "tea" / "alembic.ini"
|
||||
return Config(str(ini))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def url_tea(tmp_path):
|
||||
"""A temp SQLite file whose schema the migrations built, stamped at `head`."""
|
||||
url_original = settings.tea_database_url
|
||||
url = f"sqlite:///{tmp_path / 'tea.db'}"
|
||||
settings.tea_database_url = url
|
||||
persistance_db.get_tea_engine.cache_clear()
|
||||
command.upgrade(_config(), "head")
|
||||
yield url
|
||||
persistance_db.get_tea_engine.cache_clear()
|
||||
settings.tea_database_url = url_original
|
||||
|
||||
|
||||
def test_association_tables_deployed_with_their_natural_keys(url_tea):
|
||||
"""Pins down: `relacion_ados2` exists with the unique (rel_version, rel_biomarcador, rel_zona,
|
||||
rel_resultado) that the import merge and the `tea` library upsert on, and `relacion_ados2_paciente`
|
||||
with one row per (rap_rel_id, rap_eeg_id). Fails if the migration creating the tables is dropped or
|
||||
loses a constraint."""
|
||||
inspector = inspect(create_engine(url_tea))
|
||||
assert {"relacion_ados2", "relacion_ados2_paciente"} <= set(inspector.get_table_names())
|
||||
|
||||
uniques = {tuple(c["column_names"]) for c in inspector.get_unique_constraints("relacion_ados2")}
|
||||
assert ("rel_version", "rel_biomarcador", "rel_zona", "rel_resultado") in uniques
|
||||
uniques_paciente = {tuple(c["column_names"])
|
||||
for c in inspector.get_unique_constraints("relacion_ados2_paciente")}
|
||||
assert ("rap_rel_id", "rap_eeg_id") in uniques_paciente
|
||||
|
||||
|
||||
def test_zone_revision_deploys_and_downgrades_only_its_table(url_tea):
|
||||
"""Pins down: `eeg_metrica_zona` exists at head with its columns, and downgrading to the revision before it (the
|
||||
join of the association and the risk index heads) removes it and nothing else. Fails if the zone revision is dropped, loses a column, or its downgrade touches
|
||||
another table."""
|
||||
inspector = inspect(create_engine(url_tea))
|
||||
assert {c["name"] for c in inspector.get_columns("eeg_metrica_zona")} == {
|
||||
"mez_id", "mez_met_id", "mez_zona", "mez_valor", "mez_z"}
|
||||
command.downgrade(_config(), "e8c2a5d47f13")
|
||||
names = set(inspect(create_engine(url_tea)).get_table_names())
|
||||
assert "eeg_metrica_zona" not in names
|
||||
assert {"relacion_ados2", "relacion_ados2_paciente", "eeg_metrica", "eeg_metrica_electrodo"} <= names
|
||||
|
||||
|
||||
def test_downgrade_of_the_association_revision_drops_only_the_association_tables(url_tea):
|
||||
"""Pins down: downgrading to the revision before the association removes `relacion_ados2` and
|
||||
`relacion_ados2_paciente` (and the later zone table) and nothing the hospital source loaded. Fails if the
|
||||
downgrade stops dropping them, or starts dropping other tables."""
|
||||
command.downgrade(_config(), "c4306f438b3a")
|
||||
names = set(inspect(create_engine(url_tea)).get_table_names())
|
||||
assert "relacion_ados2" not in names
|
||||
assert "relacion_ados2_paciente" not in names
|
||||
assert {"pacientes", "ordenes_estudio", "mchat", "ados2", "eeg", "eeg_metrica",
|
||||
"eeg_criterio", "eeg_metrica_electrodo"} <= names
|
||||
|
||||
|
||||
def test_migrated_schema_matches_the_models(url_tea):
|
||||
"""Pins down: `alembic check` sees no difference between the migrated schema and `core.tea.models`,
|
||||
so a model change can never land without its migration. Fails if the metadata and the chain drift."""
|
||||
command.check(_config())
|
||||
@@ -27,7 +27,21 @@ vars:
|
||||
# A note with one of these before the cytology leaves it out: the patient is already a case.
|
||||
cie_antecedente: ["D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539"]
|
||||
horizonte_toma_reporte_dias: 60
|
||||
horizonte_toma_diagnostico_dias: 180
|
||||
# The chained steps take longer than each one's own 60 days: from the sample to the diagnosis, 120, and to the first
|
||||
# treatment (below), 180.
|
||||
horizonte_toma_diagnostico_dias: 120
|
||||
# Provisional: how long after the sample, and after its diagnosis, a treatment still counts for the times to
|
||||
# treatment (models/cacu/gold/eventos/cacu_tomas_citologia.sql).
|
||||
horizonte_toma_tratamiento_dias: 180
|
||||
horizonte_diagnostico_tratamiento_dias: 60
|
||||
# Provisional: the windows of the screening route, in days: from the sample to the first colposcopy and to the
|
||||
# biopsy report, from the cytology result to the colposcopy, from the colposcopy to the biopsy report and from the
|
||||
# biopsy report to the diagnosis (models/cacu/gold/eventos/cacu_ruta_tamizaje.sql).
|
||||
horizonte_toma_colposcopia_dias: 60
|
||||
horizonte_toma_biopsia_dias: 60
|
||||
horizonte_resultado_colposcopia_dias: 60
|
||||
horizonte_colposcopia_biopsia_dias: 60
|
||||
horizonte_biopsia_diagnostico_dias: 60
|
||||
# ASCCP follow-up (the kit's cacu.seguimiento.*; provisional): what counts as a colposcopy and a treatment
|
||||
# (models/cacu/silver/cacu_procedimientos_inferidos.sql).
|
||||
seguimiento:
|
||||
@@ -53,24 +67,25 @@ vars:
|
||||
"C508", "C509"]
|
||||
cie_antecedente: ["D05", "D050", "D051", "D057", "D059", "C50", "C500", "C501", "C502", "C503", "C504", "C505",
|
||||
"C506", "C508", "C509"]
|
||||
# Each patient's clinical scenario (models/cama/silver/cama_procedimientos_inferidos.sql), a hierarchy: one with a
|
||||
# discharge note after her diagnosis is in post-treatment; else one with a malignant breast tumour's ICD-10 is in
|
||||
# control; else she is in screening. Each starts at its first evidence of a kind its list names, and the timeline
|
||||
# keeps the kind in `valor_codigo` and the level (1 to 3) in `valor_numerico`.
|
||||
# tamizaje BCSC and Barlow's risk. mastografia: her first mammogram before any diagnosis
|
||||
# control survival. cie: a note with one of `cie_tumor_maligno` (an in situ carcinoma isn't one), whoever
|
||||
# wrote it; biopsia: a report of one of `grados_malignos`
|
||||
# postratamiento recurrence. egreso: a note of one of `tipos_nota_egreso` with one of `cie_tumor_maligno` or on or
|
||||
# after her diagnosis; nota: a later note with one of `cie_tumor_maligno` by one of
|
||||
# `tratamiento_especialidades`
|
||||
# Each patient's clinical scenario (models/cama/silver/cama_procedimientos_inferidos.sql), one of two: a patient
|
||||
# is in post-treatment from her first evidence of a kind `postratamiento_evidencias` names, and under observation
|
||||
# ("en observación") otherwise. The timeline keeps that evidence as an `escenario_postratamiento` fact with its
|
||||
# kind in `valor_codigo`; being under observation has no fact.
|
||||
# egreso a note of one of `tipos_nota_egreso` with one of `cie_tumor_maligno`, or on or after her diagnosis
|
||||
# nota a note with one of `cie_tumor_maligno` by one of `tratamiento_especialidades`, after her diagnosis
|
||||
# tratamiento a treatment encounter of one of `tratamiento_estudios` (surgery, chemotherapy, radiotherapy) on or
|
||||
# after her diagnosis
|
||||
# Her diagnosis is her first evidence of a kind `diagnostico_evidencias` names. cie: a note with one of
|
||||
# `cie_tumor_maligno` (an in situ carcinoma isn't one), whoever wrote it; biopsia: a report of one of
|
||||
# `grados_malignos`.
|
||||
escenarios:
|
||||
tamizaje_evidencias: ["mastografia"]
|
||||
control_evidencias: ["cie"]
|
||||
cie_tumor_maligno: ["C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509"]
|
||||
grados_malignos: ["CARCINOMA_INVASOR"]
|
||||
postratamiento_evidencias: ["egreso"]
|
||||
postratamiento_evidencias: ["egreso", "tratamiento"]
|
||||
tipos_nota_egreso: ["EGRESO"]
|
||||
tratamiento_especialidades: ["CIRUGIA_ONCOLOGICA", "ONCOLOGIA_MEDICA"]
|
||||
tratamiento_estudios: ["cirugia", "quimioterapia", "radioterapia"]
|
||||
diagnostico_evidencias: ["cie", "biopsia"]
|
||||
cie_tumor_maligno: ["C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509"]
|
||||
grados_malignos: ["CARCINOMA_INVASOR"]
|
||||
especialidades_diagnostico: ["CIRUGIA_ONCOLOGICA"]
|
||||
horizonte_toma_diagnostico_dias: 180
|
||||
birads_gravedad: ["B1", "B2", "B3", "B0", "B4", "B4A", "B4B", "B4C", "B5", "B6"]
|
||||
@@ -93,9 +108,8 @@ vars:
|
||||
# TEA's rules (models/tea). The cohort: children whose first M-CHAT was at `edad_min_meses` to `edad_max_meses`
|
||||
# completed months (days / `dias_por_mes`, rounded to one decimal, then truncated); `ventanas`, the age groups of
|
||||
# that age. A confirmation is a neuropediatrics note with one of `cie_tea` (without the dot, compared exactly).
|
||||
# An EEG is bad when any quality criterion passes its threshold (`calidad`); a metric is altered when its z-score
|
||||
# against the reference of the child's age group at the EEG is at least `alteracion_z` away from 0.
|
||||
# The references, thresholds and `alteracion_z` are placeholders until the domain expert validates them.
|
||||
# Whether an EEG is valid, and whether a metric is altered (outside its age baseline's p5-p95), is the EEG
|
||||
# analysis's: the baselines are the trained models in production, which the domain expert validates.
|
||||
tea:
|
||||
edad_min_meses: 16
|
||||
edad_max_meses: 36
|
||||
@@ -105,31 +119,32 @@ vars:
|
||||
- {clave: "24_29", desde: 24, hasta: 29}
|
||||
- {clave: "30_36", desde: 30, hasta: 36}
|
||||
cie_tea: ["F840"]
|
||||
alteracion_z: 2
|
||||
calidad:
|
||||
canales_amplitud: 2
|
||||
canales_alta_frecuencia: 2
|
||||
canales_correlacion: 2
|
||||
canales_sin_senal: 2
|
||||
ruido_linea_db: 8
|
||||
# Reference range of each metric by age group at the EEG: (metric, group, min, max). The mean is the middle of
|
||||
# the range and the standard deviation a quarter of its width.
|
||||
referencias:
|
||||
- ["ritmo_posterior", "16_23", 4.5, 7.0]
|
||||
- ["ritmo_posterior", "24_29", 5.0, 7.5]
|
||||
- ["ritmo_posterior", "30_36", 5.5, 8.5]
|
||||
- ["husos_sueno_n2", "16_23", 2.5, 6.5]
|
||||
- ["husos_sueno_n2", "24_29", 2.25, 6.25]
|
||||
- ["husos_sueno_n2", "30_36", 2.0, 6.0]
|
||||
- ["husos_sueno_n3", "16_23", 0.75, 2.75]
|
||||
- ["husos_sueno_n3", "24_29", 0.5, 2.5]
|
||||
- ["husos_sueno_n3", "30_36", 0.5, 2.5]
|
||||
- ["picos_paroxisticos", "16_23", 0.0, 1.0]
|
||||
- ["picos_paroxisticos", "24_29", 0.0, 1.0]
|
||||
- ["picos_paroxisticos", "30_36", 0.0, 1.0]
|
||||
- ["gradiente_anteroposterior", "16_23", 2.0, 3.5]
|
||||
- ["gradiente_anteroposterior", "24_29", 1.75, 3.25]
|
||||
- ["gradiente_anteroposterior", "30_36", 1.5, 3.0]
|
||||
# The ADOS-2 items by what they measure (core.tea.models.ADOS2_ITEM_MEANINGS, a test keeps them equal): per
|
||||
# item meaning code, its column code in each module that scores it. The association model's item outcomes are
|
||||
# these codes (models/tea/gold/seguimiento/tea_paciente_relacion_ados2.sql).
|
||||
ados2_reactivos:
|
||||
ados2_item_01: {TODDLER: sa_a2, MODULO_1: sa_a2}
|
||||
ados2_item_02: {TODDLER: sa_a7, MODULO_1: sa_a7, MODULO_2: sa_a6}
|
||||
ados2_item_03: {TODDLER: sa_a8, MODULO_1: sa_a8, MODULO_2: sa_a7}
|
||||
ados2_item_04: {TODDLER: sa_b1, MODULO_1: sa_b1, MODULO_2: sa_b1}
|
||||
ados2_item_05: {TODDLER: sa_b4, MODULO_1: sa_b3, MODULO_2: sa_b2}
|
||||
ados2_item_06: {TODDLER: sa_b5, MODULO_1: sa_b4}
|
||||
ados2_item_07: {TODDLER: sa_b6, MODULO_1: sa_b5, MODULO_2: sa_b3}
|
||||
ados2_item_08: {TODDLER: sa_b7}
|
||||
ados2_item_09: {TODDLER: sa_b8}
|
||||
ados2_item_10: {TODDLER: sa_b9}
|
||||
ados2_item_11: {TODDLER: sa_b12, MODULO_1: sa_b9, MODULO_2: sa_b5}
|
||||
ados2_item_12: {TODDLER: sa_b13, MODULO_1: sa_b10, MODULO_2: sa_b6}
|
||||
ados2_item_13: {TODDLER: sa_b14, MODULO_1: sa_b11}
|
||||
ados2_item_14: {TODDLER: sa_b15, MODULO_1: sa_b12, MODULO_2: sa_b8}
|
||||
ados2_item_15: {TODDLER: sa_b16b}
|
||||
ados2_item_16: {MODULO_2: sa_b11}
|
||||
ados2_item_17: {TODDLER: sa_b18, MODULO_2: sa_b12}
|
||||
ados2_item_18: {TODDLER: rrb_a3, MODULO_1: rrb_a3}
|
||||
ados2_item_19: {MODULO_1: rrb_a5, MODULO_2: rrb_a4}
|
||||
ados2_item_20: {TODDLER: rrb_d1, MODULO_1: rrb_d1, MODULO_2: rrb_d1}
|
||||
ados2_item_21: {TODDLER: rrb_d2, MODULO_1: rrb_d2, MODULO_2: rrb_d2}
|
||||
ados2_item_22: {TODDLER: rrb_d5, MODULO_1: rrb_d4, MODULO_2: rrb_d4}
|
||||
# CaMa's survival cohort (models/cama/cohorts/survival): the surgeries that are its procedure of interest
|
||||
# (ESCISIONAL includes a lumpectomy). Provisional, to be decided with the domain expert.
|
||||
survival_cohort:
|
||||
@@ -137,15 +152,49 @@ vars:
|
||||
recruitment_end: "2027-01-01"
|
||||
cutoff: "2026-12-31"
|
||||
surgeries: ["ESCISIONAL", "SEGMENTECTOMIA", "MASTECTOMIA_TOTAL", "MASTECTOMIA_RADICAL_MODIFICADA"]
|
||||
# CaMa's total cohort (models/cama/cohorts/total): the cut-off of its index.
|
||||
total_cohort:
|
||||
cutoff: "2026-12-31"
|
||||
# The surveillance cohort's rules (models/cacu/cohorts/surveillance).
|
||||
# CaCu's recruitment window and cut-off, once: every CaCu cohort takes them (YAML merge key), so the post-colposcopy
|
||||
# and total cohorts (and the scenarios indexed in their pipelines) recruit as the surveillance cohort does.
|
||||
cacu_window: &cacu_window
|
||||
recruitment_start: "2018-01-01"
|
||||
recruitment_end: "2027-01-01"
|
||||
cutoff: "2026-12-31"
|
||||
surveillance_cohort:
|
||||
<<: *cacu_window
|
||||
event_grades: ["LIEAG", "CIS", "CARCINOMA"]
|
||||
# The post-colposcopy cohorts (models/cacu/cohorts/post_colposcopy, one per visit k; KPNC's post-colposcopy
|
||||
# tables, Cheung et al. 2020): indexed at the first colposcopy's result (k = 0) or at the k-th surveillance visit
|
||||
# after it, stratified by the result that referred the patient (within `referral_lookback_days` before the
|
||||
# colposcopy; provisional). `hysterectomy_cie`: provisional, ICD-10 Z90.7 is the absence of any genital organ.
|
||||
post_colposcopy_cohort:
|
||||
<<: *cacu_window
|
||||
event_grades: ["LIEAG", "CIS", "CARCINOMA"]
|
||||
referral_lookback_days: 365
|
||||
hysterectomy_cie: ["Z907"]
|
||||
# The total cohort (models/cacu/cohorts/total): every patient with an event up to the cut-off, with no rules, for
|
||||
# models that apply their own; its recruitment window is carried in its parameters for their index.
|
||||
total_cohort:
|
||||
<<: *cacu_window
|
||||
# CaMa's recruitment window and cut-off, once (YAML merge key), and its total cohort (models/cama/cohorts/total):
|
||||
# every patient with a clinical event up to the cut-off, with no rules, for the scenarios that index and filter in
|
||||
# their own pipeline. The window is the one the scenarios take for their index; the cut-off is where follow-up ends
|
||||
# (the end of the year; no member is followed past the day her build is read).
|
||||
cama_window: &cama_window
|
||||
recruitment_start: "2018-01-01"
|
||||
recruitment_end: "2027-01-01"
|
||||
cutoff: "2026-12-31"
|
||||
cama_total_cohort:
|
||||
<<: *cama_window
|
||||
# The post-treatment cohort (models/cacu/cohorts/post_treatment; KPNC's post-treatment tables): the first cytology
|
||||
# more than `index_after_days` after the first treatment, stratified by the biopsy before it (within
|
||||
# `pretreatment_lookback_days`).
|
||||
post_treatment_cohort:
|
||||
recruitment_start: "2024-01-01"
|
||||
recruitment_end: "2027-01-01"
|
||||
cutoff: "2026-12-31"
|
||||
event_grades: ["LIEAG", "CIS", "CARCINOMA"]
|
||||
index_after_days: 90
|
||||
pretreatment_lookback_days: 365
|
||||
# models/<project>/silver: what dbt derives from silver's procedimiento and observacion_clinica, compiled as
|
||||
# CTEs inside the models that use them (no objects in the database), except the timeline, a view.
|
||||
# models/<project>/gold/<family>: one view per indicator, a folder per family as in the kit.
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
{#
|
||||
The post-colposcopy cohorts, one per visit k (KPNC's post-colposcopy tables; Cheung et al. 2020,
|
||||
doi:10.1097/LGT.0000000000000528): k = 0 is the colposcopy's result (below CIN2), k ≥ 1 the k-th surveillance visit
|
||||
after it. Every cohort has the same rules; only the index changes. A new visit is a folder `visit_<k>` whose models
|
||||
call these macros with its k (see models/cacu/cohorts/post_colposcopy/README.md).
|
||||
Parameters: the `post_colposcopy_cohort` var.
|
||||
#}
|
||||
|
||||
{# The index of visit k: the colposcopy's result (k = 0) or visit k, if it falls in the recruitment window. #}
|
||||
{% macro cacu_post_colposcopy_index(k) -%}
|
||||
{%- set p = var('post_colposcopy_cohort') -%}
|
||||
{%- if k == 0 %}
|
||||
select pac_id, fecha_resultado as fecha_indice, fuente_tabla as indice_fuente_tabla, fuente_id as indice_fuente_id,
|
||||
fecha_colposcopia, fecha_resultado, ordenes_sin_resultado
|
||||
from {{ ref('cacu_post_colposcopy_episode') }}
|
||||
where fecha_resultado >= '{{ p.recruitment_start }}' and fecha_resultado < '{{ p.recruitment_end }}'
|
||||
{%- else %}
|
||||
select pac_id, fecha as fecha_indice, fuente_tabla as indice_fuente_tabla, fuente_id as indice_fuente_id,
|
||||
fecha_colposcopia, fecha_resultado, ordenes_sin_resultado
|
||||
from {{ ref('cacu_post_colposcopy_visits') }}
|
||||
where numero = {{ k }} and fecha >= '{{ p.recruitment_start }}' and fecha < '{{ p.recruitment_end }}'
|
||||
{%- endif %}
|
||||
{%- endmacro %}
|
||||
|
||||
|
||||
{# Every patient of the domain: where the cohort's attrition starts. #}
|
||||
{% macro cacu_post_colposcopy_population() -%}
|
||||
select pac_id from {{ source('silver', 'persona') }}
|
||||
{%- endmacro %}
|
||||
|
||||
|
||||
{#
|
||||
One exclusion rule over the cohort's index model `index` (a model name). Each reads only the index and the data.
|
||||
- biopsia_sin_resultado a biopsy ordered at the colposcopy has no report: its result is unknown
|
||||
- cin2_hasta_el_indice a biopsy with the outcome up to the index (the colposcopy found it, or it came before)
|
||||
- antecedente_cacu a note with a cervical cancer ICD-10 up to the index (`antecedente`)
|
||||
- histerectomia a note with an ICD-10 of `hysterectomy_cie` up to the index
|
||||
- tratamiento_previo treated up to the index: she belongs to the post-treatment cohort
|
||||
- sin_referencia no cytology or HPV result in the `referral_lookback_days` up to the colposcopy
|
||||
- sin_cotest the index sample lacks an HPV result or a cytology result (squamous or glandular)
|
||||
#}
|
||||
{% macro cacu_post_colposcopy_exclusion(rule, index) -%}
|
||||
{%- set p = var('post_colposcopy_cohort') -%}
|
||||
{%- if rule == 'biopsia_sin_resultado' %}
|
||||
select pac_id from {{ ref(index) }} where ordenes_sin_resultado > 0
|
||||
{%- elif rule in ('cin2_hasta_el_indice', 'antecedente_cacu', 'histerectomia', 'tratamiento_previo') %}
|
||||
select distinct c.pac_id
|
||||
from {{ ref(index) }} as c
|
||||
join {{ ref('cacu_linea_de_tiempo') }} as e on e.pac_id = c.pac_id
|
||||
where e.fecha <= c.fecha_indice
|
||||
{%- if rule == 'cin2_hasta_el_indice' %}
|
||||
and e.tipo = 'biopsia' and e.valor_codigo in ('{{ p.event_grades | join("', '") }}')
|
||||
{%- elif rule == 'antecedente_cacu' %}
|
||||
and e.tipo = 'antecedente'
|
||||
{%- elif rule == 'histerectomia' %}
|
||||
and e.tipo = 'nota_medica' and e.valor_codigo in ('{{ p.hysterectomy_cie | join("', '") }}')
|
||||
{%- else %}
|
||||
and e.tipo = 'tratamiento'
|
||||
{%- endif %}
|
||||
{%- elif rule == 'sin_referencia' %}
|
||||
select c.pac_id
|
||||
from {{ ref(index) }} as c
|
||||
join {{ source('silver', 'dim_fecha') }} as dc on dc.fecha = c.fecha_colposcopia
|
||||
where not exists (
|
||||
select 1
|
||||
from {{ ref('cacu_linea_de_tiempo') }} as e
|
||||
join {{ source('silver', 'dim_fecha') }} as de on de.fecha = e.fecha
|
||||
where e.pac_id = c.pac_id
|
||||
and e.tipo in ('bethesda', 'glandular', 'vph')
|
||||
and e.valor_codigo is not null
|
||||
and de.dia_num <= dc.dia_num
|
||||
and dc.dia_num - de.dia_num <= {{ p.referral_lookback_days }}
|
||||
)
|
||||
{%- elif rule == 'sin_cotest' %}
|
||||
select c.pac_id
|
||||
from {{ ref(index) }} as c
|
||||
where not exists (
|
||||
select 1 from {{ ref('cacu_linea_de_tiempo') }} as e
|
||||
where e.pac_id = c.pac_id and e.fuente_tabla = c.indice_fuente_tabla and e.fuente_id = c.indice_fuente_id
|
||||
and e.tipo = 'vph' and e.valor_codigo is not null and e.fecha <= '{{ p.cutoff }}'
|
||||
)
|
||||
or not exists (
|
||||
select 1 from {{ ref('cacu_linea_de_tiempo') }} as e
|
||||
where e.pac_id = c.pac_id and e.fuente_tabla = c.indice_fuente_tabla and e.fuente_id = c.indice_fuente_id
|
||||
and e.tipo in ('bethesda', 'glandular') and e.valor_codigo is not null and e.fecha <= '{{ p.cutoff }}'
|
||||
)
|
||||
{%- else %}
|
||||
{{ exceptions.raise_compiler_error("unknown post-colposcopy rule: " ~ rule) }}
|
||||
{%- endif %}
|
||||
{%- endmacro %}
|
||||
@@ -0,0 +1,30 @@
|
||||
{#
|
||||
The first event of a kind after each start, for the same patient: the building block of a time between two events.
|
||||
|
||||
`inicio`: a relation with one row per start, with columns `id`, `pac_id` and the date `fecha`.
|
||||
`linea`: the patient's timeline (`pac_id`, `fecha`, `conocida_en`, `tipo`).
|
||||
`tipo`: the timeline kind that ends the interval.
|
||||
`horizonte_dias`: the event must fall fewer days after the start.
|
||||
`estricto`: true leaves out an event on the start's own day, false counts it.
|
||||
|
||||
One row per start that has such an event: `inicio_id`, `fecha_fin` (its date) and `fin_conocido_en` (when it became
|
||||
known: the earliest load among the patient's events of that day). The days between are the difference of
|
||||
`dim_fecha.dia_num`, plain arithmetic that every engine runs. The caller joins on `inicio_id`; a start without a
|
||||
row has no event in its horizon.
|
||||
#}
|
||||
{% macro primer_evento_posterior(inicio, id, fecha, linea, tipo, horizonte_dias, estricto=true) -%}
|
||||
select p.inicio_id, p.fecha_fin, min(l.conocida_en) as fin_conocido_en
|
||||
from (
|
||||
select i.{{ id }} as inicio_id, min(l.fecha) as fecha_fin
|
||||
from {{ inicio }} i
|
||||
join {{ linea }} l
|
||||
on l.pac_id = i.pac_id and l.tipo = '{{ tipo }}' and l.fecha {{ '>' if estricto else '>=' }} i.{{ fecha }}
|
||||
join {{ source('silver', 'dim_fecha') }} dl on dl.fecha = l.fecha
|
||||
join {{ source('silver', 'dim_fecha') }} di on di.fecha = i.{{ fecha }}
|
||||
where dl.dia_num - di.dia_num < {{ horizonte_dias }}
|
||||
group by i.{{ id }}
|
||||
) p
|
||||
join {{ inicio }} i on i.{{ id }} = p.inicio_id
|
||||
join {{ linea }} l on l.pac_id = i.pac_id and l.tipo = '{{ tipo }}' and l.fecha = p.fecha_fin
|
||||
group by p.inicio_id, p.fecha_fin
|
||||
{%- endmacro %}
|
||||
@@ -31,9 +31,20 @@
|
||||
end
|
||||
{%- endmacro %}
|
||||
|
||||
{# A bounded number of the EEG's quality: within its threshold of `tea.calidad`. #}
|
||||
{% macro tea_criterio_bueno(columna, umbral) -%}
|
||||
({{ columna }} is not null and {{ columna }} <= {{ var('tea')['calidad'][umbral] }})
|
||||
{# The EEG's metrics and quality checks as the catalog names them: `eeg.<metric>`, `eeg.calidad_<check>`. The checks
|
||||
are the EEG analysis's: study-wide ones on the recording, channel ones on a `parte` per bad channel. #}
|
||||
{% macro tea_metricas() -%}
|
||||
{{ return(['ritmo_posterior', 'husos_sueno_n2', 'husos_sueno_n3', 'picos_paroxisticos', 'gradiente_anteroposterior']) }}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro tea_criterios_estudio() -%}
|
||||
{{ return(['clean_windows', 'internal_coverage', 'bad_scalp_triage', 'usable_scalp', 'triage_level', 'line_noise',
|
||||
'file']) }}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro tea_criterios_canal() -%}
|
||||
{{ return(['dead_channel', 'frozen', 'saturated', 'inf_values', 'own_gaps', 'bridge', 'amplitude', 'aux_amplitude',
|
||||
'does_not_correlate', 'intermittent_contact', 'intermittent_bursts']) }}
|
||||
{%- endmacro %}
|
||||
|
||||
{# The later of two values when both are known, else null: a step reached after the previous one is dated by the
|
||||
@@ -42,3 +53,19 @@
|
||||
case when ({{ previo }}) is null or ({{ propio }}) is null then null
|
||||
when ({{ propio }}) > ({{ previo }}) then ({{ propio }}) else ({{ previo }}) end
|
||||
{%- endmacro %}
|
||||
|
||||
{# The rows of `tea.ados2_reactivos` as a query: per item meaning code (`resultado`) and module (`modulo`, the
|
||||
`ados2.modulo` catalog codes), the item's code in silver (`reactivo`, `ados2.<column code>`). #}
|
||||
{% macro tea_ados2_reactivos_por_modulo() -%}
|
||||
{%- set filas = [] -%}
|
||||
{%- for resultado, modulos in var('tea')['ados2_reactivos'].items() -%}
|
||||
{%- for modulo, codigo in modulos.items() -%}
|
||||
{%- do filas.append((resultado, modulo, 'ados2.' ~ codigo)) -%}
|
||||
{%- endfor -%}
|
||||
{%- endfor -%}
|
||||
{%- for resultado, modulo, reactivo in filas %}
|
||||
{% if not loop.first %}union all {% endif -%}
|
||||
select {{ as_text("'" ~ resultado ~ "'") }} as resultado, {{ as_text("'" ~ modulo ~ "'") }} as modulo,
|
||||
{{ as_text("'" ~ reactivo ~ "'") }} as reactivo
|
||||
{%- endfor %}
|
||||
{%- endmacro %}
|
||||
|
||||
@@ -10,3 +10,21 @@
|
||||
('á','a'),('é','e'),('í','i'),('ó','o'),('ú','u'),('ü','u')] -%}
|
||||
upper({% for _ in pares %}replace({% endfor %}{{ columna }}{% for con, sin in pares %}, '{{ con }}', '{{ sin }}'){% endfor %})
|
||||
{%- endmacro %}
|
||||
|
||||
{# Texts joined into one, portable: `||` on SQLite and PostgreSQL, CONCAT on MySQL, + on SQL Server. A null part
|
||||
nulls the whole on SQL Server, where the join then simply doesn't match; the parts are never null there. #}
|
||||
{% macro concatena() -%}
|
||||
{{ return(adapter.dispatch('concatena', 'isssteleon')(varargs)) }}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro default__concatena(campos) -%}
|
||||
{{ campos | join(' || ') }}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro mysql__concatena(campos) -%}
|
||||
concat({{ campos | join(', ') }})
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro sqlserver__concatena(campos) -%}
|
||||
{{ campos | join(' + ') }}
|
||||
{%- endmacro %}
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
version: 2
|
||||
|
||||
# The post-colposcopy cohorts (KPNC's post-colposcopy tables; Cheung et al. 2020, doi:10.1097/LGT.0000000000000528):
|
||||
# one per visit k in `visit_<k>/`, read as the surveillance cohort's are (`models cohorts build` chains the
|
||||
# exclusions in `order`; each reads only the index date and the data). The two models here are shared by all of them
|
||||
# and belong to no cohort. Rules: macros/cacu_post_colposcopy.sql. Parameters: the `post_colposcopy_cohort` var.
|
||||
models:
|
||||
- name: cacu_post_colposcopy_episode
|
||||
description: >
|
||||
The patient's first colposcopy and when its result is known (the last report of the biopsies ordered that day,
|
||||
or the colposcopy's date with none ordered: provisionally taken as below CIN2), and how many of those orders
|
||||
have no report.
|
||||
config: {materialized: ephemeral}
|
||||
- name: cacu_post_colposcopy_visits
|
||||
description: >
|
||||
The surveillance visits (cytology samples) after the first colposcopy's result is known and before any later
|
||||
colposcopy, numbered from 1.
|
||||
config: {materialized: ephemeral}
|
||||
|
||||
unit_tests:
|
||||
- name: the_colposcopy_result_is_the_last_report_of_its_biopsies
|
||||
description: >
|
||||
Pins down: patient 1's result date is the later of the two reports of the biopsies ordered on her first
|
||||
colposcopy's day; the biopsy of her second colposcopy doesn't count. Patient 2 had no biopsy ordered, so her
|
||||
result date is the colposcopy's (provisionally below CIN2). Patient 3's order has no report, so it is counted
|
||||
as unknown. Fails if the episode takes a later colposcopy, a biopsy of another day, or stops counting the
|
||||
unreported orders.
|
||||
model: cacu_post_colposcopy_episode
|
||||
overrides:
|
||||
vars:
|
||||
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
|
||||
given:
|
||||
- input: ref('cacu_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-01-10' as fecha, 'colposcopia' as tipo, null as valor_codigo, 'n' as fuente_tabla, 'c1' as fuente_id
|
||||
union all select 1, '2025-01-10', 'orden_biopsia', null, 'b', 'o1'
|
||||
union all select 1, '2025-01-10', 'orden_biopsia', null, 'b', 'o2'
|
||||
union all select 1, '2025-01-20', 'biopsia', 'LIEBG', 'b', 'o1'
|
||||
union all select 1, '2025-01-31', 'biopsia', 'NEGATIVO', 'b', 'o2'
|
||||
union all select 1, '2025-06-01', 'colposcopia', null, 'n', 'c2'
|
||||
union all select 1, '2025-06-01', 'orden_biopsia', null, 'b', 'o3'
|
||||
union all select 1, '2025-06-20', 'biopsia', 'LIEBG', 'b', 'o3'
|
||||
union all select 2, '2025-03-01', 'colposcopia', null, 'n', 'c3'
|
||||
union all select 3, '2025-04-01', 'colposcopia', null, 'n', 'c4'
|
||||
union all select 3, '2025-04-01', 'orden_biopsia', null, 'b', 'o4'
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-01-10' as fecha_colposcopia, 'n' as fuente_tabla, 'c1' as fuente_id,
|
||||
'2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado
|
||||
union all select 2, '2025-03-01', 'n', 'c3', '2025-03-01', 0
|
||||
union all select 3, '2025-04-01', 'n', 'c4', '2025-04-01', 1
|
||||
|
||||
- name: visits_follow_the_result_and_stop_at_the_next_colposcopy
|
||||
description: >
|
||||
Pins down: patient 1's sample on the colposcopy's day and the one before her result date aren't visits; the
|
||||
two after it are visits 1 and 2; the one after her second colposcopy is not a visit. Fails if visits start
|
||||
before the result is known or continue after a re-referral to colposcopy.
|
||||
model: cacu_post_colposcopy_visits
|
||||
overrides:
|
||||
vars:
|
||||
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
|
||||
given:
|
||||
- input: ref('cacu_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-01-10' as fecha, 'colposcopia' as tipo, 'n' as fuente_tabla, 'c1' as fuente_id
|
||||
union all select 1, '2025-01-10', 'citologia', 'm', 'a'
|
||||
union all select 1, '2025-01-20', 'citologia', 'm', 'b'
|
||||
union all select 1, '2025-07-01', 'citologia', 'm', 'c'
|
||||
union all select 1, '2026-01-15', 'citologia', 'm', 'd'
|
||||
union all select 1, '2026-03-01', 'colposcopia', 'n', 'c2'
|
||||
union all select 1, '2026-09-01', 'citologia', 'm', 'e'
|
||||
- input: ref('cacu_post_colposcopy_episode')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-01-10' as fecha_colposcopia, 'n' as fuente_tabla, 'c1' as fuente_id,
|
||||
'2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-07-01' as fecha, 'm' as fuente_tabla, 'c' as fuente_id, '2025-01-10' as fecha_colposcopia,
|
||||
'2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado, 1 as numero
|
||||
union all select 1, '2026-01-15', 'm', 'd', '2025-01-10', '2025-01-31', 0, 2
|
||||
|
||||
- name: visit_1_index_is_the_first_visit_in_the_window
|
||||
description: >
|
||||
Pins down: patient 1's index is her visit 1; patient 2's visit 1 falls after the recruitment window, so she has
|
||||
no index even though her visit 2 would. Fails if the cohort of visit 1 takes another visit or ignores the window.
|
||||
model: cacu_post_colposcopy_v1_index_date
|
||||
overrides:
|
||||
vars:
|
||||
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
|
||||
given:
|
||||
- input: ref('cacu_post_colposcopy_visits')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-07-01' as fecha, 'm' as fuente_tabla, 'c' as fuente_id, '2025-01-10' as fecha_colposcopia,
|
||||
'2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado, 1 as numero
|
||||
union all select 1, '2025-12-01', 'm', 'd', '2025-01-10', '2025-01-31', 0, 2
|
||||
union all select 2, '2026-02-01', 'm', 'f', '2025-06-01', '2025-06-01', 0, 1
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-07-01' as fecha_indice, 'm' as indice_fuente_tabla, 'c' as indice_fuente_id,
|
||||
'2025-01-10' as fecha_colposcopia, '2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado
|
||||
|
||||
- name: visit_0_index_is_the_colposcopy_result
|
||||
description: >
|
||||
Pins down: the cohort of visit 0 is indexed at the date the colposcopy's result is known, in the window.
|
||||
Fails if it takes the colposcopy's date when a biopsy was reported later.
|
||||
model: cacu_post_colposcopy_v0_index_date
|
||||
overrides:
|
||||
vars:
|
||||
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
|
||||
given:
|
||||
- input: ref('cacu_post_colposcopy_episode')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-01-10' as fecha_colposcopia, 'n' as fuente_tabla, 'c1' as fuente_id,
|
||||
'2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado
|
||||
union all select 2, '2024-12-20', 'n', 'c2', '2024-12-30', 0
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-01-31' as fecha_indice, 'n' as indice_fuente_tabla, 'c1' as indice_fuente_id,
|
||||
'2025-01-10' as fecha_colposcopia, '2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado
|
||||
|
||||
- name: sin_cotest_needs_hpv_and_cytology_of_the_index_sample
|
||||
description: >
|
||||
Pins down: patient 1's index sample has an HPV and a Bethesda result, so she stays; patient 2's has only HPV and
|
||||
patient 3's only cytology, so both are flagged; patient 4's HPV belongs to another sample, so she is flagged.
|
||||
Fails if a result of another sample, or either result alone, counts as a cotest.
|
||||
model: cacu_post_colposcopy_v1_excl_sin_cotest
|
||||
overrides:
|
||||
vars:
|
||||
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
|
||||
given:
|
||||
- input: ref('cacu_post_colposcopy_v1_index_date')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-07-01' as fecha_indice, 'm' as indice_fuente_tabla, 'a' as indice_fuente_id
|
||||
union all select 2, '2025-07-01', 'm', 'b'
|
||||
union all select 3, '2025-07-01', 'm', 'c'
|
||||
union all select 4, '2025-07-01', 'm', 'd'
|
||||
- input: ref('cacu_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-07-10' as fecha, 'vph' as tipo, 'NEGATIVO' as valor_codigo, 'm' as fuente_tabla, 'a' as fuente_id
|
||||
union all select 1, '2025-07-12', 'bethesda', 'NORMAL', 'm', 'a'
|
||||
union all select 2, '2025-07-10', 'vph', 'POSITIVO', 'm', 'b'
|
||||
union all select 3, '2025-07-12', 'bethesda', 'ASC-US', 'm', 'c'
|
||||
union all select 4, '2025-07-12', 'bethesda', 'NORMAL', 'm', 'd'
|
||||
union all select 4, '2025-03-10', 'vph', 'POSITIVO', 'm', 'z'
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 2 as pac_id union all select 3 union all select 4
|
||||
|
||||
- name: cin2_counts_up_to_the_index_date
|
||||
description: >
|
||||
Pins down: a CIN2+ biopsy reported on the index date (visit 0: the colposcopy found it) excludes patient 1;
|
||||
patient 2's LIEAG comes after her index, so she stays. Fails if `cin2_hasta_el_indice` stops including the
|
||||
index date or reads biopsies after it.
|
||||
model: cacu_post_colposcopy_v0_excl_cin2_hasta_el_indice
|
||||
overrides:
|
||||
vars:
|
||||
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
|
||||
given:
|
||||
- input: ref('cacu_post_colposcopy_v0_index_date')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-01-31' as fecha_indice union all select 2, '2025-01-31'
|
||||
- input: ref('cacu_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-01-31' as fecha, 'biopsia' as tipo, 'LIEAG' as valor_codigo
|
||||
union all select 2, '2025-08-01', 'biopsia', 'LIEAG'
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id
|
||||
|
||||
- name: histerectomia_reads_the_configured_icd10
|
||||
description: >
|
||||
Pins down: patient 1's note with Z907 before her index excludes her; patient 2's note has another code and
|
||||
patient 3's Z907 comes after her index, so both stay. Fails if the rule ignores `hysterectomy_cie` or the date.
|
||||
model: cacu_post_colposcopy_v1_excl_histerectomia
|
||||
overrides:
|
||||
vars:
|
||||
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
|
||||
given:
|
||||
- input: ref('cacu_post_colposcopy_v1_index_date')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-07-01' as fecha_indice union all select 2, '2025-07-01' union all select 3, '2025-07-01'
|
||||
- input: ref('cacu_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2024-05-01' as fecha, 'nota_medica' as tipo, 'Z907' as valor_codigo
|
||||
union all select 2, '2024-05-01', 'nota_medica', 'N871'
|
||||
union all select 3, '2025-09-01', 'nota_medica', 'Z907'
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id
|
||||
|
||||
- name: sin_referencia_looks_back_from_the_colposcopy
|
||||
description: >
|
||||
Pins down: patient 1's HPV result 100 days before her colposcopy is her referral, so she stays. Patient 2's
|
||||
only result is 400 days before (past the lookback) and patient 3's is after the colposcopy, so both are
|
||||
flagged. Fails if the lookback, its direction or the result types change.
|
||||
model: cacu_post_colposcopy_v1_excl_sin_referencia
|
||||
overrides:
|
||||
vars:
|
||||
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
|
||||
given:
|
||||
- input: ref('cacu_post_colposcopy_v1_index_date')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-12-01' as fecha_colposcopia union all select 2, '2025-12-01'
|
||||
union all select 3, '2025-12-01'
|
||||
- input: ref('cacu_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-08-23' as fecha, 'vph' as tipo, 'POSITIVO' as valor_codigo
|
||||
union all select 2, '2024-10-27', 'bethesda', 'ASC-US'
|
||||
union all select 3, '2025-12-20', 'bethesda', 'LIEBG'
|
||||
- input: source('silver', 'dim_fecha')
|
||||
format: sql
|
||||
rows: |
|
||||
select '2025-12-01' as fecha, 400 as dia_num union all select '2025-08-23', 300
|
||||
union all select '2024-10-27', 0 union all select '2025-12-20', 419
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 2 as pac_id union all select 3
|
||||
@@ -0,0 +1,40 @@
|
||||
{#
|
||||
The patient's first colposcopy and when its result is known: one row per patient with a colposcopy up to the
|
||||
cut-off. Only the first one opens the post-colposcopy sequence (Cheung et al. 2020: referred to colposcopy for the
|
||||
first time). Its biopsies are the orders on the colposcopy's day (a reported biopsy shares its order's source row).
|
||||
|
||||
- `fecha_resultado`: the last report of those biopsies; with no biopsy ordered, the colposcopy's own date.
|
||||
PROVISIONAL: a colposcopy without a biopsy order is taken as below CIN2 (normal impression), which assumes the
|
||||
colposcopic impression misses no CIN2+.
|
||||
- `ordenes_sin_resultado`: orders of the episode with no report up to the cut-off (result unknown).
|
||||
#}
|
||||
{% set p = var('post_colposcopy_cohort') %}
|
||||
with eventos as (
|
||||
select pac_id, fecha, tipo, valor_codigo, fuente_tabla, fuente_id
|
||||
from {{ ref('cacu_linea_de_tiempo') }}
|
||||
where fecha <= '{{ p.cutoff }}'
|
||||
),
|
||||
colposcopias as (
|
||||
select pac_id, fecha, fuente_tabla, fuente_id,
|
||||
row_number() over (partition by pac_id order by fecha, fuente_tabla, fuente_id) as posicion
|
||||
from eventos
|
||||
where tipo = 'colposcopia'
|
||||
),
|
||||
primera as (
|
||||
select pac_id, fecha as fecha_colposcopia, fuente_tabla, fuente_id from colposcopias where posicion = 1
|
||||
),
|
||||
ordenes as (
|
||||
select o.pac_id, o.fuente_tabla, o.fuente_id, max(b.fecha) as fecha_reporte
|
||||
from eventos as o
|
||||
join primera as c on c.pac_id = o.pac_id and o.fecha = c.fecha_colposcopia
|
||||
left join eventos as b
|
||||
on b.tipo = 'biopsia' and b.pac_id = o.pac_id and b.fuente_tabla = o.fuente_tabla and b.fuente_id = o.fuente_id
|
||||
where o.tipo = 'orden_biopsia'
|
||||
group by o.pac_id, o.fuente_tabla, o.fuente_id
|
||||
)
|
||||
select
|
||||
c.pac_id, c.fecha_colposcopia, c.fuente_tabla, c.fuente_id,
|
||||
coalesce((select max(o.fecha_reporte) from ordenes as o where o.pac_id = c.pac_id), c.fecha_colposcopia)
|
||||
as fecha_resultado,
|
||||
(select count(*) from ordenes as o where o.pac_id = c.pac_id and o.fecha_reporte is null) as ordenes_sin_resultado
|
||||
from primera as c
|
||||
@@ -0,0 +1,31 @@
|
||||
{#
|
||||
The surveillance visits after the first colposcopy, numbered 1, 2, … per patient: every cytology sample (an HPV
|
||||
result shares its sample's source row) after the colposcopy's result is known and before any later colposcopy,
|
||||
which closes the sequence (a re-referral; Cheung et al. 2020 model only the first). The post-colposcopy cohort of
|
||||
visit k takes visit k as its index (`cacu_post_colposcopy_index`).
|
||||
#}
|
||||
{% set p = var('post_colposcopy_cohort') %}
|
||||
with eventos as (
|
||||
select pac_id, fecha, tipo, fuente_tabla, fuente_id
|
||||
from {{ ref('cacu_linea_de_tiempo') }}
|
||||
where fecha <= '{{ p.cutoff }}'
|
||||
),
|
||||
episodio as (
|
||||
select * from {{ ref('cacu_post_colposcopy_episode') }}
|
||||
),
|
||||
cierre as (
|
||||
select ep.pac_id, min(e.fecha) as fecha
|
||||
from episodio as ep
|
||||
join eventos as e on e.pac_id = ep.pac_id and e.tipo = 'colposcopia' and e.fecha > ep.fecha_resultado
|
||||
group by ep.pac_id
|
||||
)
|
||||
select
|
||||
t.pac_id, t.fecha, t.fuente_tabla, t.fuente_id,
|
||||
ep.fecha_colposcopia, ep.fecha_resultado, ep.ordenes_sin_resultado,
|
||||
row_number() over (partition by t.pac_id order by t.fecha, t.fuente_id) as numero
|
||||
from eventos as t
|
||||
join episodio as ep on ep.pac_id = t.pac_id
|
||||
left join cierre on cierre.pac_id = t.pac_id
|
||||
where t.tipo = 'citologia'
|
||||
and t.fecha > ep.fecha_resultado
|
||||
and (cierre.fecha is null or t.fecha < cierre.fecha)
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
version: 2
|
||||
|
||||
# Post-colposcopy cohort of visit 0 (macros/cacu_post_colposcopy.sql). Parameters: the `post_colposcopy_cohort` var.
|
||||
models:
|
||||
- name: cacu_post_colposcopy_v0_population
|
||||
description: Every patient of the domain.
|
||||
config:
|
||||
materialized: ephemeral
|
||||
meta:
|
||||
cohort: cacu/cohorte_post_colposcopia_visita_0
|
||||
kind: population
|
||||
# Changing a rule changes the cohort: bump `version` (stored with every build).
|
||||
version: "0.2.0"
|
||||
cutoff: "{{ var('post_colposcopy_cohort')['cutoff'] }}"
|
||||
parameters: "{{ var('post_colposcopy_cohort') | tojson }}"
|
||||
- name: cacu_post_colposcopy_v0_index_date
|
||||
description: "The colposcopy's result (below CIN2): the last report of the biopsies ordered at the patient's first colposcopy, or the colposcopy itself if none was ordered, if it falls in the recruitment window."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: index}}
|
||||
- name: cacu_post_colposcopy_v0_excl_biopsia_sin_resultado
|
||||
description: "A biopsy ordered at the colposcopy has no report up to the cut-off: the colposcopy's result is unknown."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: exclusion, name: biopsia_sin_resultado, order: 1}}
|
||||
- name: cacu_post_colposcopy_v0_excl_cin2_hasta_el_indice
|
||||
description: "A biopsy with the outcome up to the index date: the colposcopy found CIN2+, or it came before."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: exclusion, name: cin2_hasta_el_indice, order: 2}}
|
||||
- name: cacu_post_colposcopy_v0_excl_antecedente_cacu
|
||||
description: "A note with a cervical cancer ICD-10 (antecedente) up to the index date: a known history of CIN2+."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: exclusion, name: antecedente_cacu, order: 3}}
|
||||
- name: cacu_post_colposcopy_v0_excl_histerectomia
|
||||
description: "A note with an ICD-10 of hysterectomy_cie up to the index date (Cheung et al. 2020 exclude hysterectomy)."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: exclusion, name: histerectomia, order: 4}}
|
||||
- name: cacu_post_colposcopy_v0_excl_tratamiento_previo
|
||||
description: "Treated up to the index date: she belongs to the post-treatment cohort."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: exclusion, name: tratamiento_previo, order: 5}}
|
||||
- name: cacu_post_colposcopy_v0_excl_sin_referencia
|
||||
description: "No cytology or HPV result in the referral_lookback_days up to the colposcopy: the referral grade is unknown."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: exclusion, name: sin_referencia, order: 6}}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('antecedente_cacu', 'cacu_post_colposcopy_v0_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('biopsia_sin_resultado', 'cacu_post_colposcopy_v0_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('cin2_hasta_el_indice', 'cacu_post_colposcopy_v0_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('histerectomia', 'cacu_post_colposcopy_v0_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('sin_referencia', 'cacu_post_colposcopy_v0_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('tratamiento_previo', 'cacu_post_colposcopy_v0_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_index(0) }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_population() }}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
version: 2
|
||||
|
||||
# Post-colposcopy cohort of visit 1 (macros/cacu_post_colposcopy.sql). Parameters: the `post_colposcopy_cohort` var.
|
||||
models:
|
||||
- name: cacu_post_colposcopy_v1_population
|
||||
description: Every patient of the domain.
|
||||
config:
|
||||
materialized: ephemeral
|
||||
meta:
|
||||
cohort: cacu/cohorte_post_colposcopia_visita_1
|
||||
kind: population
|
||||
# Changing a rule changes the cohort: bump `version` (stored with every build).
|
||||
version: "0.2.0"
|
||||
cutoff: "{{ var('post_colposcopy_cohort')['cutoff'] }}"
|
||||
parameters: "{{ var('post_colposcopy_cohort') | tojson }}"
|
||||
- name: cacu_post_colposcopy_v1_index_date
|
||||
description: "The first surveillance visit (cytology sample) after the first colposcopy's result is known, before any later colposcopy, if it falls in the recruitment window."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: index}}
|
||||
- name: cacu_post_colposcopy_v1_excl_biopsia_sin_resultado
|
||||
description: "A biopsy ordered at the colposcopy has no report up to the cut-off: the colposcopy's result is unknown."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: biopsia_sin_resultado, order: 1}}
|
||||
- name: cacu_post_colposcopy_v1_excl_cin2_hasta_el_indice
|
||||
description: "A biopsy with the outcome up to the index date: the colposcopy found CIN2+, or it came before."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: cin2_hasta_el_indice, order: 2}}
|
||||
- name: cacu_post_colposcopy_v1_excl_antecedente_cacu
|
||||
description: "A note with a cervical cancer ICD-10 (antecedente) up to the index date: a known history of CIN2+."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: antecedente_cacu, order: 3}}
|
||||
- name: cacu_post_colposcopy_v1_excl_histerectomia
|
||||
description: "A note with an ICD-10 of hysterectomy_cie up to the index date (Cheung et al. 2020 exclude hysterectomy)."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: histerectomia, order: 4}}
|
||||
- name: cacu_post_colposcopy_v1_excl_tratamiento_previo
|
||||
description: "Treated up to the index date: she belongs to the post-treatment cohort."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: tratamiento_previo, order: 5}}
|
||||
- name: cacu_post_colposcopy_v1_excl_sin_referencia
|
||||
description: "No cytology or HPV result in the referral_lookback_days up to the colposcopy: the referral grade is unknown."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: sin_referencia, order: 6}}
|
||||
- name: cacu_post_colposcopy_v1_excl_sin_cotest
|
||||
description: "The index sample lacks an HPV result or a cytology result (squamous or glandular): KPNC's current result is a cotest."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: sin_cotest, order: 7}}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('antecedente_cacu', 'cacu_post_colposcopy_v1_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('biopsia_sin_resultado', 'cacu_post_colposcopy_v1_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('cin2_hasta_el_indice', 'cacu_post_colposcopy_v1_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('histerectomia', 'cacu_post_colposcopy_v1_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('sin_cotest', 'cacu_post_colposcopy_v1_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('sin_referencia', 'cacu_post_colposcopy_v1_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('tratamiento_previo', 'cacu_post_colposcopy_v1_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_index(1) }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_population() }}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
version: 2
|
||||
|
||||
# Post-colposcopy cohort of visit 2 (macros/cacu_post_colposcopy.sql). Parameters: the `post_colposcopy_cohort` var.
|
||||
models:
|
||||
- name: cacu_post_colposcopy_v2_population
|
||||
description: Every patient of the domain.
|
||||
config:
|
||||
materialized: ephemeral
|
||||
meta:
|
||||
cohort: cacu/cohorte_post_colposcopia_visita_2
|
||||
kind: population
|
||||
# Changing a rule changes the cohort: bump `version` (stored with every build).
|
||||
version: "0.2.0"
|
||||
cutoff: "{{ var('post_colposcopy_cohort')['cutoff'] }}"
|
||||
parameters: "{{ var('post_colposcopy_cohort') | tojson }}"
|
||||
- name: cacu_post_colposcopy_v2_index_date
|
||||
description: "The second surveillance visit after the first colposcopy's result is known, before any later colposcopy, if it falls in the recruitment window."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_2, kind: index}}
|
||||
- name: cacu_post_colposcopy_v2_excl_biopsia_sin_resultado
|
||||
description: "A biopsy ordered at the colposcopy has no report up to the cut-off: the colposcopy's result is unknown."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_2, kind: exclusion, name: biopsia_sin_resultado, order: 1}}
|
||||
- name: cacu_post_colposcopy_v2_excl_cin2_hasta_el_indice
|
||||
description: "A biopsy with the outcome up to the index date: the colposcopy found CIN2+, or it came before."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_2, kind: exclusion, name: cin2_hasta_el_indice, order: 2}}
|
||||
- name: cacu_post_colposcopy_v2_excl_antecedente_cacu
|
||||
description: "A note with a cervical cancer ICD-10 (antecedente) up to the index date: a known history of CIN2+."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_2, kind: exclusion, name: antecedente_cacu, order: 3}}
|
||||
- name: cacu_post_colposcopy_v2_excl_histerectomia
|
||||
description: "A note with an ICD-10 of hysterectomy_cie up to the index date (Cheung et al. 2020 exclude hysterectomy)."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_2, kind: exclusion, name: histerectomia, order: 4}}
|
||||
- name: cacu_post_colposcopy_v2_excl_tratamiento_previo
|
||||
description: "Treated up to the index date: she belongs to the post-treatment cohort."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_2, kind: exclusion, name: tratamiento_previo, order: 5}}
|
||||
- name: cacu_post_colposcopy_v2_excl_sin_referencia
|
||||
description: "No cytology or HPV result in the referral_lookback_days up to the colposcopy: the referral grade is unknown."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_2, kind: exclusion, name: sin_referencia, order: 6}}
|
||||
- name: cacu_post_colposcopy_v2_excl_sin_cotest
|
||||
description: "The index sample lacks an HPV result or a cytology result (squamous or glandular): KPNC's current result is a cotest."
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_2, kind: exclusion, name: sin_cotest, order: 7}}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('antecedente_cacu', 'cacu_post_colposcopy_v2_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('biopsia_sin_resultado', 'cacu_post_colposcopy_v2_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('cin2_hasta_el_indice', 'cacu_post_colposcopy_v2_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('histerectomia', 'cacu_post_colposcopy_v2_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('sin_cotest', 'cacu_post_colposcopy_v2_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('sin_referencia', 'cacu_post_colposcopy_v2_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_exclusion('tratamiento_previo', 'cacu_post_colposcopy_v2_index_date') }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_index(2) }}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{{ cacu_post_colposcopy_population() }}
|
||||
@@ -0,0 +1,84 @@
|
||||
version: 2
|
||||
|
||||
# The post-treatment cohort, one query per rule, read as the surveillance cohort's are. Parameters: the
|
||||
# `post_treatment_cohort` var in dbt_project.yml. A treatment is the timeline's inferred `tratamiento`
|
||||
# (cacu_procedimientos_inferidos).
|
||||
models:
|
||||
- name: cacu_post_treatment_all_patients
|
||||
description: Every patient of the domain.
|
||||
config:
|
||||
materialized: ephemeral
|
||||
meta:
|
||||
cohort: cacu/cohorte_post_tratamiento
|
||||
kind: population
|
||||
# Changing a rule changes the cohort: bump `version` (stored with every build).
|
||||
version: "0.1.0"
|
||||
cutoff: "{{ var('post_treatment_cohort')['cutoff'] }}"
|
||||
parameters: "{{ var('post_treatment_cohort') | tojson }}"
|
||||
- name: cacu_post_treatment_index_date
|
||||
description: >
|
||||
First cytology past the days after the patient's first treatment, if it falls in the recruitment window. Sets
|
||||
the index date; keeps the treatment's date.
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_tratamiento, kind: index}}
|
||||
- name: cacu_post_treatment_excl_no_pretreatment_biopsy
|
||||
description: No reported biopsy in the lookback up to the treatment, so the pre-treatment stratum is unknown.
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_tratamiento, kind: exclusion, name: no_pretreatment_biopsy, order: 1}}
|
||||
- name: cacu_post_treatment_excl_event_before_index
|
||||
description: Biopsy with the outcome between the treatment and the index date, a lesion found before the first post-treatment test.
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_tratamiento, kind: exclusion, name: event_before_index, order: 2}}
|
||||
- name: cacu_post_treatment_excl_no_index_result
|
||||
description: The index cytology has neither a cytology nor an HPV result, so there are no predictors.
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_tratamiento, kind: exclusion, name: no_index_result, order: 3}}
|
||||
|
||||
unit_tests:
|
||||
- name: post_treatment_index_is_the_first_cytology_past_the_days_after_treatment
|
||||
description: >
|
||||
Pins down: patient 1's cytology 60 days after her treatment is too early; the one at 180 days is her index, with
|
||||
her first treatment's date. Patient 2 was never treated. Fails if the index stops waiting `index_after_days` or
|
||||
takes a later treatment.
|
||||
model: cacu_post_treatment_index_date
|
||||
overrides:
|
||||
vars:
|
||||
post_treatment_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], index_after_days: 90, pretreatment_lookback_days: 365}
|
||||
given:
|
||||
- input: ref('cacu_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, 'tratamiento' as tipo, '2025-01-01' as fecha, 't' as fuente_tabla, 'x1' as fuente_id
|
||||
union all select 1, 'tratamiento', '2025-02-01', 't', 'x2'
|
||||
union all select 1, 'citologia', '2025-03-02', 't', 'a'
|
||||
union all select 1, 'citologia', '2025-06-30', 't', 'b'
|
||||
union all select 2, 'citologia', '2025-06-30', 't', 'c'
|
||||
- input: source('silver', 'dim_fecha')
|
||||
format: sql
|
||||
rows: |
|
||||
select '2025-01-01' as fecha, 0 as dia_num union all select '2025-02-01', 31
|
||||
union all select '2025-03-02', 60 union all select '2025-06-30', 180
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-06-30' as fecha_indice, 't' as indice_fuente_tabla, 'b' as indice_fuente_id,
|
||||
'2025-01-01' as fecha_tratamiento
|
||||
- name: event_before_index_is_between_treatment_and_index
|
||||
description: >
|
||||
Pins down: patient 1's CIN2+ biopsy between her treatment and her index is flagged. Patient 2's is before the
|
||||
treatment (the one treated) and patient 3's on the index date, so neither is. Fails if the interval's ends change.
|
||||
model: cacu_post_treatment_excl_event_before_index
|
||||
overrides:
|
||||
vars:
|
||||
post_treatment_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], index_after_days: 90, pretreatment_lookback_days: 365}
|
||||
given:
|
||||
- input: ref('cacu_post_treatment_index_date')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-01-01' as fecha_tratamiento, '2025-07-01' as fecha_indice
|
||||
union all select 2, '2025-01-01', '2025-07-01' union all select 3, '2025-01-01', '2025-07-01'
|
||||
- input: ref('cacu_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, 'biopsia' as tipo, '2025-03-01' as fecha, 'LIEAG' as valor_codigo
|
||||
union all select 2, 'biopsia', '2024-12-01', 'LIEAG'
|
||||
union all select 3, 'biopsia', '2025-07-01', 'LIEAG'
|
||||
expect:
|
||||
rows:
|
||||
- {pac_id: 1}
|
||||
@@ -0,0 +1,3 @@
|
||||
{# Every patient of the domain: where the cohort's attrition starts. #}
|
||||
select pac_id
|
||||
from {{ source('silver', 'persona') }}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
{# Candidates with a biopsy showing the outcome after their treatment and before their index date: a persistent or
|
||||
recurrent lesion found before the first post-treatment test. #}
|
||||
{% set p = var('post_treatment_cohort') %}
|
||||
select distinct c.pac_id
|
||||
from {{ ref('cacu_post_treatment_index_date') }} as c
|
||||
join {{ ref('cacu_linea_de_tiempo') }} as e on e.pac_id = c.pac_id
|
||||
where e.tipo = 'biopsia'
|
||||
and e.fecha > c.fecha_tratamiento
|
||||
and e.fecha < c.fecha_indice
|
||||
and e.valor_codigo in ('{{ p.event_grades | join("', '") }}')
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
{# Candidates whose index cytology has neither a cytology result (squamous or glandular) nor an HPV result. #}
|
||||
{% set p = var('post_treatment_cohort') %}
|
||||
select c.pac_id
|
||||
from {{ ref('cacu_post_treatment_index_date') }} as c
|
||||
where not exists (
|
||||
select 1
|
||||
from {{ ref('cacu_linea_de_tiempo') }} as e
|
||||
where e.pac_id = c.pac_id
|
||||
and e.tipo in ('bethesda', 'glandular', 'vph')
|
||||
and e.fuente_tabla = c.indice_fuente_tabla
|
||||
and e.fuente_id = c.indice_fuente_id
|
||||
and e.fecha <= '{{ p.cutoff }}'
|
||||
and e.valor_codigo is not null
|
||||
)
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
{#
|
||||
Candidates with no reported biopsy in the `pretreatment_lookback_days` up to their treatment: the biopsy before
|
||||
treatment, which sets the stratum, is unknown.
|
||||
#}
|
||||
{% set p = var('post_treatment_cohort') %}
|
||||
select c.pac_id
|
||||
from {{ ref('cacu_post_treatment_index_date') }} as c
|
||||
join {{ source('silver', 'dim_fecha') }} as dt on dt.fecha = c.fecha_tratamiento
|
||||
where not exists (
|
||||
select 1
|
||||
from {{ ref('cacu_linea_de_tiempo') }} as e
|
||||
join {{ source('silver', 'dim_fecha') }} as de on de.fecha = e.fecha
|
||||
where e.pac_id = c.pac_id
|
||||
and e.tipo = 'biopsia'
|
||||
and e.valor_codigo is not null
|
||||
and de.dia_num <= dt.dia_num
|
||||
and dt.dia_num - de.dia_num <= {{ p.pretreatment_lookback_days }}
|
||||
)
|
||||
@@ -0,0 +1,27 @@
|
||||
{#
|
||||
The first cytology more than `index_after_days` after the patient's first treatment, up to the cut-off, if it falls
|
||||
in the recruitment window. Sets the index date and keeps the treatment's date for the rules. Days are differences
|
||||
of `dim_fecha.dia_num`.
|
||||
#}
|
||||
{% set p = var('post_treatment_cohort') %}
|
||||
with treatment as (
|
||||
select pac_id, min(fecha) as fecha
|
||||
from {{ ref('cacu_linea_de_tiempo') }}
|
||||
where tipo = 'tratamiento' and fecha <= '{{ p.cutoff }}'
|
||||
group by pac_id
|
||||
),
|
||||
cytologies as (
|
||||
select
|
||||
l.pac_id, l.fecha, l.fuente_tabla, l.fuente_id, t.fecha as fecha_tratamiento,
|
||||
row_number() over (partition by l.pac_id order by l.fecha, l.fuente_id) as position
|
||||
from {{ ref('cacu_linea_de_tiempo') }} as l
|
||||
join treatment as t on t.pac_id = l.pac_id
|
||||
join {{ source('silver', 'dim_fecha') }} as dl on dl.fecha = l.fecha
|
||||
join {{ source('silver', 'dim_fecha') }} as dt on dt.fecha = t.fecha
|
||||
where l.tipo = 'citologia' and l.fecha <= '{{ p.cutoff }}'
|
||||
and dl.dia_num - dt.dia_num > {{ p.index_after_days }}
|
||||
)
|
||||
select pac_id, fecha as fecha_indice, fuente_tabla as indice_fuente_tabla, fuente_id as indice_fuente_id,
|
||||
fecha_tratamiento
|
||||
from cytologies
|
||||
where position = 1 and fecha >= '{{ p.recruitment_start }}' and fecha < '{{ p.recruitment_end }}'
|
||||
@@ -13,6 +13,8 @@ models:
|
||||
meta:
|
||||
cohort: cacu/cohorte_vigilancia
|
||||
kind: population
|
||||
# Changing a rule changes the cohort: bump `version` (stored with every build).
|
||||
version: "0.2.0"
|
||||
cutoff: "{{ var('surveillance_cohort')['cutoff'] }}"
|
||||
parameters: "{{ var('surveillance_cohort') | tojson }}"
|
||||
- name: cacu_surveillance_index_date
|
||||
@@ -24,6 +26,9 @@ models:
|
||||
- name: cacu_surveillance_excl_no_index_result
|
||||
description: The index cytology has neither a cytology nor an HPV result, so there are no predictors.
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_vigilancia, kind: exclusion, name: no_index_result, order: 2}}
|
||||
- name: cacu_surveillance_variables
|
||||
description: The index sample's Bethesda (`pap_0`) and HPV (`hpv_0`) results, stored with each build.
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_vigilancia, kind: variables}}
|
||||
|
||||
unit_tests:
|
||||
- name: prior_event_flags_an_earlier_biopsy_with_the_outcome
|
||||
@@ -53,9 +58,10 @@ unit_tests:
|
||||
- {pac_id: 1}
|
||||
- name: no_index_result_ignores_results_of_other_cytologies
|
||||
description: >
|
||||
Pins down: patient 1 has a result on its index cytology and patient 2 has an HPV result there, so neither is
|
||||
flagged. Patient 3's only result belongs to another cytology and patient 4's has no value, so both are. Fails if the
|
||||
rule stops matching the index cytology or counts an empty result.
|
||||
Pins down: patient 1 has a result on its index cytology, patient 2 an HPV result there and patient 5 only a
|
||||
glandular one (AGC), so none is flagged. Patient 3's only result belongs to another cytology and patient 4's has
|
||||
no value, so both are. Fails if the rule stops matching the index cytology, counts an empty result or ignores
|
||||
the glandular result.
|
||||
model: cacu_surveillance_excl_no_index_result
|
||||
overrides:
|
||||
vars:
|
||||
@@ -66,7 +72,7 @@ unit_tests:
|
||||
rows: |
|
||||
select 1 as pac_id, 'citologiacervical' as indice_fuente_tabla, 'a' as indice_fuente_id
|
||||
union all select 2, 'citologiacervical', 'b' union all select 3, 'citologiacervical', 'c'
|
||||
union all select 4, 'citologiacervical', 'd'
|
||||
union all select 4, 'citologiacervical', 'd' union all select 5, 'citologiacervical', 'e'
|
||||
- input: ref('cacu_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
@@ -74,6 +80,7 @@ unit_tests:
|
||||
union all select 2, 'vph', 'citologiacervical', 'b', '2025-01-01', 'POSITIVO'
|
||||
union all select 3, 'bethesda', 'citologiacervical', 'other', '2025-01-01', 'NORMAL'
|
||||
union all select 4, 'bethesda', 'citologiacervical', 'd', '2025-01-01', null
|
||||
union all select 5, 'glandular', 'citologiacervical', 'e', '2025-01-01', 'AGC'
|
||||
expect:
|
||||
rows:
|
||||
- {pac_id: 3}
|
||||
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
{# Candidates whose index cytology has neither a cytology result nor an HPV result. #}
|
||||
{# Candidates whose index cytology has neither a cytology result (squamous or glandular) nor an HPV result. #}
|
||||
{% set p = var('surveillance_cohort') %}
|
||||
select c.pac_id
|
||||
from {{ ref('cacu_surveillance_index_date') }} as c
|
||||
@@ -6,7 +6,7 @@ where not exists (
|
||||
select 1
|
||||
from {{ ref('cacu_linea_de_tiempo') }} as e
|
||||
where e.pac_id = c.pac_id
|
||||
and e.tipo in ('bethesda', 'vph')
|
||||
and e.tipo in ('bethesda', 'glandular', 'vph')
|
||||
and e.fuente_tabla = c.indice_fuente_tabla
|
||||
and e.fuente_id = c.indice_fuente_id
|
||||
and e.fecha <= '{{ p.cutoff }}'
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
{#
|
||||
The variables the build stores for each patient with an index (long: one row per variable), from her index sample:
|
||||
`pap_0` (squamous Bethesda) and `hpv_0` (HPV). The WebApp's patient record shows them. The interval coding (`c`,
|
||||
`l`, `r`) is the model's (`cin2_pim`), not a cohort rule.
|
||||
#}
|
||||
{% set p = var('surveillance_cohort') %}
|
||||
select c.pac_id,
|
||||
case e.tipo when 'bethesda' then 'pap_0' else 'hpv_0' end as variable,
|
||||
min(e.valor_codigo) as valor_codigo,
|
||||
cast(null as {{ dbt.type_float() }}) as valor_numerico
|
||||
from {{ ref('cacu_surveillance_index_date') }} as c
|
||||
join {{ ref('cacu_linea_de_tiempo') }} as e
|
||||
on e.pac_id = c.pac_id and e.fuente_tabla = c.indice_fuente_tabla and e.fuente_id = c.indice_fuente_id
|
||||
where e.tipo in ('bethesda', 'vph') and e.valor_codigo is not null and e.fecha <= '{{ p.cutoff }}'
|
||||
group by c.pac_id, e.tipo
|
||||
@@ -0,0 +1,44 @@
|
||||
version: 2
|
||||
|
||||
# The total cohort: every patient with an event up to the cut-off, at her first event, with no rules. For models
|
||||
# whose cohort rules are too involved for SQL: they read this cohort and the timeline and apply their own rules,
|
||||
# which then belong to the model (and its tests), not to a cohort. Parameters: the `total_cohort` var.
|
||||
models:
|
||||
- name: cacu_total_population
|
||||
description: Every patient of the domain.
|
||||
config:
|
||||
materialized: ephemeral
|
||||
meta:
|
||||
cohort: cacu/cohorte_total
|
||||
kind: population
|
||||
# Changing a rule changes the cohort: bump `version` (stored with every build).
|
||||
version: "0.1.0"
|
||||
cutoff: "{{ var('total_cohort')['cutoff'] }}"
|
||||
parameters: "{{ var('total_cohort') | tojson }}"
|
||||
- name: cacu_total_index_date
|
||||
description: The patient's first clinical event in the timeline up to the cut-off (not her birth or death). Sets the index date.
|
||||
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_total, kind: index}}
|
||||
|
||||
unit_tests:
|
||||
- name: total_index_is_the_first_event_up_to_the_cutoff
|
||||
description: >
|
||||
Pins down: patient 1's index is her earliest clinical event, whatever its type, and her birth, which is earlier,
|
||||
does not set it; patient 2's only clinical event is after the cut-off, so she has no index, whatever her birth.
|
||||
Fails if the index takes a later event, one type only, a persona event, or ignores the cut-off.
|
||||
model: cacu_total_index_date
|
||||
overrides:
|
||||
vars:
|
||||
total_cohort: {cutoff: "2026-12-31"}
|
||||
given:
|
||||
- input: ref('cacu_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2025-05-01' as fecha, 'citologia' as tipo, 't' as fuente_tabla, 'b' as fuente_id
|
||||
union all select 1, '2024-02-01', 'nota_medica', 'n', 'a'
|
||||
union all select 1, '1970-05-01', 'nacimiento', 'persona', '1'
|
||||
union all select 2, '2027-03-01', 'citologia', 't', 'c'
|
||||
union all select 2, '1960-01-01', 'nacimiento', 'persona', '2'
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2024-02-01' as fecha_indice, 'n' as indice_fuente_tabla, 'a' as indice_fuente_id
|
||||
@@ -0,0 +1,16 @@
|
||||
{#
|
||||
Every patient with at least one clinical event in the timeline up to the cut-off, indexed at her first one (the
|
||||
earliest, ties broken by source). Her birth and death come from `persona` and are not clinical events, so they never
|
||||
set the index. No recruitment window and no exclusions: a model whose rules can't be written as SQL
|
||||
starts from this cohort and applies them in its own pipeline, over the timeline.
|
||||
#}
|
||||
{% set p = var('total_cohort') %}
|
||||
with eventos as (
|
||||
select pac_id, fecha, fuente_tabla, fuente_id,
|
||||
row_number() over (partition by pac_id order by fecha, fuente_tabla, fuente_id) as posicion
|
||||
from {{ ref('cacu_linea_de_tiempo') }}
|
||||
where fecha <= '{{ p.cutoff }}' and fuente_tabla <> 'persona'
|
||||
)
|
||||
select pac_id, fecha as fecha_indice, fuente_tabla as indice_fuente_tabla, fuente_id as indice_fuente_id
|
||||
from eventos
|
||||
where posicion = 1
|
||||
@@ -0,0 +1,2 @@
|
||||
{# Every patient of the domain: where the cohort's attrition starts. #}
|
||||
select pac_id from {{ source('silver', 'persona') }}
|
||||
@@ -0,0 +1,38 @@
|
||||
-- Una fila por procedimiento de reporte VPH vinculado a su toma.
|
||||
with observaciones as (
|
||||
select o.procedimiento_id,
|
||||
max(case when resultado_id = 'vph.resultado' then coalesce(valor_id, valor_fuente) end) as resultado,
|
||||
max(case when resultado_id = 'vph.genotipo_16' then valor_numerico end) as g16,
|
||||
max(case when resultado_id = 'vph.genotipo_18' then valor_numerico end) as g18,
|
||||
max(k.inicio) as observaciones_conocidas_en
|
||||
from {{ source('silver', 'observacion_clinica') }} o
|
||||
join {{ source('silver', 'carga') }} k on k.carga_id = o.carga_id
|
||||
where resultado_id in ('vph.resultado', 'vph.genotipo_16', 'vph.genotipo_18')
|
||||
group by o.procedimiento_id
|
||||
)
|
||||
select r.procedimiento_id, t.pac_id, t.fecha as fecha_toma, r.fecha as fecha_reporte,
|
||||
kt.inicio as toma_conocida_en,
|
||||
case when o.observaciones_conocidas_en > kr.inicio then o.observaciones_conocidas_en
|
||||
else kr.inicio end as reporte_conocido_en,
|
||||
case
|
||||
when o.g16 not in (0, 1) or o.g18 not in (0, 1) then 'INCONSISTENTE'
|
||||
when o.resultado = 'NEGATIVO' and (o.g16 = 1 or o.g18 = 1) then 'INCONSISTENTE'
|
||||
when o.resultado = 'NEGATIVO' then 'NEGATIVO'
|
||||
when o.resultado = 'INDETERMINADO' and (o.g16 = 1 or o.g18 = 1) then 'INCONSISTENTE'
|
||||
when o.resultado = 'INDETERMINADO' then 'INDETERMINADO'
|
||||
when o.resultado = 'POSITIVO' and o.g16 = 1 and o.g18 = 1 then 'POSITIVO_16_18'
|
||||
when o.resultado = 'POSITIVO' and o.g16 = 1 and o.g18 = 0 then 'POSITIVO_16'
|
||||
when o.resultado = 'POSITIVO' and o.g16 = 0 and o.g18 = 1 then 'POSITIVO_18'
|
||||
when o.resultado = 'POSITIVO' and o.g16 = 0 and o.g18 = 0 then 'POSITIVO_SIN_16_18'
|
||||
when o.resultado = 'POSITIVO' then 'POSITIVO_INCOMPLETO'
|
||||
else 'INCONSISTENTE'
|
||||
end as categoria
|
||||
from {{ source('silver', 'procedimiento') }} r
|
||||
join {{ source('silver', 'procedimiento') }} t
|
||||
on r.padre_id = t.procedimiento_id and r.pac_id = t.pac_id
|
||||
join {{ source('silver', 'carga') }} kt on kt.carga_id = t.carga_id
|
||||
join {{ source('silver', 'carga') }} kr on kr.carga_id = r.carga_id
|
||||
left join observaciones o on o.procedimiento_id = r.procedimiento_id
|
||||
where r.estudio_id = 'vph' and r.clase = 'reporte'
|
||||
and t.estudio_id = 'citologia' and t.clase = 'toma'
|
||||
and t.fecha is not null and r.fecha is not null and r.fecha >= t.fecha
|
||||
@@ -0,0 +1,65 @@
|
||||
version: 2
|
||||
models:
|
||||
- name: cacu_reportes_vph
|
||||
description: "Reportes VPH vinculados a una toma. Clasificación provisional."
|
||||
config:
|
||||
materialized: view
|
||||
semantic_models:
|
||||
- name: cacu_reportes_vph
|
||||
model: ref('cacu_reportes_vph')
|
||||
defaults:
|
||||
agg_time_dimension: fecha_toma
|
||||
entities:
|
||||
- {name: reporte_vph, type: primary, expr: procedimiento_id}
|
||||
dimensions:
|
||||
- name: fecha_toma
|
||||
type: time
|
||||
type_params: {time_granularity: day}
|
||||
- name: fecha_reporte
|
||||
type: time
|
||||
type_params: {time_granularity: day}
|
||||
- name: toma_conocida_en
|
||||
type: time
|
||||
type_params: {time_granularity: day}
|
||||
- name: reporte_conocido_en
|
||||
type: time
|
||||
type_params: {time_granularity: day}
|
||||
- {name: categoria, type: categorical}
|
||||
measures:
|
||||
- {name: reportes_vph, agg: count_distinct, expr: procedimiento_id}
|
||||
metrics:
|
||||
- name: cacu_vph_genotipo
|
||||
label: "Resultados de VPH por genotipo"
|
||||
description: "Distribución provisional por reporte VPH vinculado a toma, asignado al periodo de la toma."
|
||||
type: simple
|
||||
type_params: {measure: reportes_vph}
|
||||
config:
|
||||
meta:
|
||||
measure_url: cacu/CACU_VPH_GENOTIPO
|
||||
version: 0.1.0
|
||||
scoring: composition
|
||||
basis: examen
|
||||
grupo: TOTAL
|
||||
contrato: C2
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c2_donas]
|
||||
poblaciones_fhir: [measure-observation]
|
||||
conocida_en: [toma_conocida_en]
|
||||
categoria:
|
||||
valor: categoria
|
||||
sin_dato: INCONSISTENTE
|
||||
elige: ultimo_valido
|
||||
valido: "{% raw %}{{ Dimension('reporte_vph__categoria') }} is not null{% endraw %}"
|
||||
admite: "{% raw %}{{ Dimension('reporte_vph__categoria') }} is not null{% endraw %}"
|
||||
fechada_en: [fecha_reporte]
|
||||
conocida_en: [reporte_conocido_en]
|
||||
orden: [fecha_reporte]
|
||||
etiquetas:
|
||||
NEGATIVO: {etiqueta: "Negativo", color: "#9DBFE3"}
|
||||
POSITIVO_16: {etiqueta: "Positivo 16 exclusivamente", color: "#2F6DB3"}
|
||||
POSITIVO_18: {etiqueta: "Positivo 18 exclusivamente", color: "#E8C28E"}
|
||||
POSITIVO_16_18: {etiqueta: "Positivo 16 y 18", color: "#D98E4A"}
|
||||
POSITIVO_SIN_16_18: {etiqueta: "Positivo sin detección de 16/18", color: "#B55A1F"}
|
||||
POSITIVO_INCOMPLETO: {etiqueta: "Positivo con genotipificación incompleta", color: "#7A2E0E"}
|
||||
INDETERMINADO: {etiqueta: "Indeterminado", color: "#A0A0A0"}
|
||||
INCONSISTENTE: {etiqueta: "No clasificable o inconsistente", color: "#C9CDD2"}
|
||||
@@ -1,5 +1,7 @@
|
||||
-- One row per member of the surveillance cohort build that the current batch of risk estimates scored, with her
|
||||
-- index date and the probability of her estimate in force, null if she has none. The current batch is the latest one
|
||||
-- One row per member of the surveillance cohort build that the current batch of risk estimates scored, with the
|
||||
-- index date of her estimate (`evaluacion_riesgo.fecha_indice`: the model's decision point, which dates the period)
|
||||
-- and the probability of her estimate in force, null if she has none. A member the batch never scored keeps her
|
||||
-- member's index date, so she still falls in a period as no data. The current batch is the latest one
|
||||
-- of the cohort with some estimate in force; an estimate is in force when its latest version, at the horizon
|
||||
-- `riesgos_horizonte_banda`, is `final` (a later `entered-in-error` version voids it). When a member and an estimate
|
||||
-- became known: the build's and the estimate's registration.
|
||||
@@ -8,6 +10,7 @@ with recientes as (
|
||||
select
|
||||
e.lote_id,
|
||||
e.pac_id,
|
||||
e.fecha_indice,
|
||||
e.probabilidad,
|
||||
e.estado,
|
||||
e.registrado_en,
|
||||
@@ -20,6 +23,11 @@ vigentes as (
|
||||
select lote_id, pac_id, probabilidad, registrado_en from recientes where lugar = 1 and estado = 'final'
|
||||
),
|
||||
|
||||
-- the index date of each scored member's estimate, whatever its state (a voided one still dates her)
|
||||
fechas as (
|
||||
select lote_id, pac_id, max(fecha_indice) as fecha_indice from recientes group by lote_id, pac_id
|
||||
),
|
||||
|
||||
lote_vigente as (
|
||||
select max(l.lote_id) as lote_id
|
||||
from {{ source('oro', 'evaluacion_riesgo_lote') }} l
|
||||
@@ -30,7 +38,7 @@ lote_vigente as (
|
||||
|
||||
select
|
||||
m.pac_id,
|
||||
m.fecha_indice,
|
||||
coalesce(f.fecha_indice, m.fecha_indice) as fecha_indice,
|
||||
a.armado_en as miembro_conocido_en,
|
||||
v.probabilidad,
|
||||
v.registrado_en as evaluacion_conocida_en
|
||||
@@ -39,3 +47,4 @@ join {{ source('oro', 'evaluacion_riesgo_lote') }} l on l.lote_id = lv.lote_id
|
||||
join {{ source('oro', 'cohorte_armado') }} a on a.armado_id = l.armado_id
|
||||
join {{ source('oro', 'cohorte_miembro') }} m on m.armado_id = l.armado_id
|
||||
left join vigentes v on v.lote_id = lv.lote_id and v.pac_id = m.pac_id
|
||||
left join fechas f on f.lote_id = lv.lote_id and f.pac_id = m.pac_id
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
-- One row per cytology taken, followed along the screening route: the first colposcopy after the sample, the first
|
||||
-- biopsy report the sample led to, and the three steps between consecutive events. The sample's own day, whether a
|
||||
-- cervical cancer note came before it and when the sample and its result became known come from
|
||||
-- `cacu_tomas_citologia`. Every event is the first of its kind after its start, within its horizon, with when it
|
||||
-- became known; a step is the days between two of those events. Days are differences of `dim_fecha.dia_num`.
|
||||
-- colposcopia first `colposcopia` after the sample (`horizonte_toma_colposcopia_dias`)
|
||||
-- biopsia first biopsy report of the sample (`horizonte_toma_biopsia_dias`)
|
||||
-- colposcopia_resultado first `colposcopia` from the cytology result on (`horizonte_resultado_colposcopia_dias`)
|
||||
-- diagnostico_biopsia first `diagnostico` after the biopsy report (`horizonte_biopsia_diagnostico_dias`)
|
||||
-- The step from the colposcopy to the biopsy report counts when the report falls within
|
||||
-- `horizonte_colposcopia_biopsia_dias` of that colposcopy.
|
||||
|
||||
with colposcopia as (
|
||||
{{ primer_evento_posterior(ref('cacu_citologias'), 'procedimiento_id', 'fecha_toma', ref('cacu_linea_de_tiempo'),
|
||||
'colposcopia', var('horizonte_toma_colposcopia_dias')) }}
|
||||
),
|
||||
|
||||
desde_resultado as (
|
||||
select procedimiento_id, pac_id, fecha_reporte as fecha
|
||||
from {{ ref('cacu_citologias') }}
|
||||
where fecha_reporte is not null
|
||||
),
|
||||
|
||||
colposcopia_resultado as (
|
||||
{{ primer_evento_posterior('desde_resultado', 'procedimiento_id', 'fecha', ref('cacu_linea_de_tiempo'),
|
||||
'colposcopia', var('horizonte_resultado_colposcopia_dias'), estricto=false) }}
|
||||
),
|
||||
|
||||
-- The biopsy is linked to its sample, not to the patient: the first report of each sample.
|
||||
primera_biopsia as (
|
||||
select b.toma_id, min(b.fecha_reporte) as fecha
|
||||
from {{ ref('cacu_biopsias') }} b
|
||||
join {{ ref('cacu_citologias') }} c on c.procedimiento_id = b.toma_id
|
||||
join {{ source('silver', 'dim_fecha') }} db on db.fecha = b.fecha_reporte
|
||||
join {{ source('silver', 'dim_fecha') }} dt on dt.fecha = c.fecha_toma
|
||||
where b.fecha_reporte > c.fecha_toma
|
||||
and db.dia_num - dt.dia_num < {{ var('horizonte_toma_biopsia_dias') }}
|
||||
group by b.toma_id
|
||||
),
|
||||
|
||||
biopsia as (
|
||||
select p.toma_id as inicio_id, p.fecha as fecha_fin, min(k.inicio) as fin_conocido_en
|
||||
from primera_biopsia p
|
||||
join {{ ref('cacu_biopsias') }} b on b.toma_id = p.toma_id and b.fecha_reporte = p.fecha
|
||||
join {{ source('silver', 'carga') }} k on k.carga_id = b.reporte_carga_id
|
||||
group by p.toma_id, p.fecha
|
||||
),
|
||||
|
||||
desde_biopsia as (
|
||||
select c.procedimiento_id, c.pac_id, bx.fecha_fin as fecha
|
||||
from {{ ref('cacu_citologias') }} c
|
||||
join biopsia bx on bx.inicio_id = c.procedimiento_id
|
||||
),
|
||||
|
||||
diagnostico_biopsia as (
|
||||
{{ primer_evento_posterior('desde_biopsia', 'procedimiento_id', 'fecha', ref('cacu_linea_de_tiempo'),
|
||||
'diagnostico', var('horizonte_biopsia_diagnostico_dias')) }}
|
||||
)
|
||||
|
||||
select
|
||||
t.procedimiento_id,
|
||||
t.fuente_id,
|
||||
t.pac_id,
|
||||
t.fecha_toma,
|
||||
t.toma_conocida_en,
|
||||
t.resultado_conocido_en,
|
||||
t.toma_dia,
|
||||
t.con_antecedente,
|
||||
dia_reporte.dia_num as reporte_dia,
|
||||
col.fecha_fin as fecha_colposcopia,
|
||||
col.fin_conocido_en as colposcopia_conocida_en,
|
||||
dia_colposcopia.dia_num - t.toma_dia as dias_toma_colposcopia,
|
||||
bx.fecha_fin as fecha_biopsia,
|
||||
bx.fin_conocido_en as biopsia_conocida_en,
|
||||
dia_biopsia.dia_num as biopsia_dia,
|
||||
dia_biopsia.dia_num - t.toma_dia as dias_toma_biopsia,
|
||||
cr.fecha_fin as fecha_colposcopia_resultado,
|
||||
cr.fin_conocido_en as colposcopia_resultado_conocida_en,
|
||||
dia_colposcopia_resultado.dia_num as colposcopia_resultado_dia,
|
||||
dia_colposcopia_resultado.dia_num - dia_reporte.dia_num as dias_resultado_colposcopia,
|
||||
case
|
||||
when dia_biopsia.dia_num - dia_colposcopia_resultado.dia_num >= 0
|
||||
and dia_biopsia.dia_num - dia_colposcopia_resultado.dia_num < {{ var('horizonte_colposcopia_biopsia_dias') }}
|
||||
then dia_biopsia.dia_num - dia_colposcopia_resultado.dia_num
|
||||
end as dias_colposcopia_biopsia,
|
||||
db.fecha_fin as fecha_diagnostico_biopsia,
|
||||
db.fin_conocido_en as diagnostico_biopsia_conocido_en,
|
||||
dia_diagnostico_biopsia.dia_num - dia_biopsia.dia_num as dias_biopsia_diagnostico
|
||||
from {{ ref('cacu_tomas_citologia') }} t
|
||||
join {{ ref('cacu_citologias') }} c on c.procedimiento_id = t.procedimiento_id
|
||||
left join {{ source('silver', 'dim_fecha') }} dia_reporte
|
||||
on dia_reporte.fecha = c.fecha_reporte
|
||||
left join colposcopia col
|
||||
on col.inicio_id = t.procedimiento_id
|
||||
left join {{ source('silver', 'dim_fecha') }} dia_colposcopia
|
||||
on dia_colposcopia.fecha = col.fecha_fin
|
||||
left join biopsia bx
|
||||
on bx.inicio_id = t.procedimiento_id
|
||||
left join {{ source('silver', 'dim_fecha') }} dia_biopsia
|
||||
on dia_biopsia.fecha = bx.fecha_fin
|
||||
left join colposcopia_resultado cr
|
||||
on cr.inicio_id = t.procedimiento_id
|
||||
left join {{ source('silver', 'dim_fecha') }} dia_colposcopia_resultado
|
||||
on dia_colposcopia_resultado.fecha = cr.fecha_fin
|
||||
left join diagnostico_biopsia db
|
||||
on db.inicio_id = t.procedimiento_id
|
||||
left join {{ source('silver', 'dim_fecha') }} dia_diagnostico_biopsia
|
||||
on dia_diagnostico_biopsia.fecha = db.fecha_fin
|
||||
@@ -0,0 +1,233 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_ruta_tamizaje
|
||||
description: "Citologías tomadas, una fila por toma, con la primera colposcopía, el primer reporte de biopsia y los tramos entre eventos consecutivos de la ruta."
|
||||
config:
|
||||
materialized: view
|
||||
|
||||
semantic_models:
|
||||
- name: cacu_ruta_tamizaje
|
||||
description: "Cytologies taken, one row each, followed along the screening route: what the times between its consecutive events count over."
|
||||
model: ref('cacu_ruta_tamizaje')
|
||||
defaults:
|
||||
agg_time_dimension: fecha_toma
|
||||
entities:
|
||||
- name: toma_ruta
|
||||
type: primary
|
||||
expr: procedimiento_id
|
||||
- name: paciente
|
||||
type: foreign
|
||||
expr: pac_id
|
||||
dimensions:
|
||||
- name: fecha_toma
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: toma_conocida_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: resultado_conocido_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: fecha_colposcopia
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: colposcopia_conocida_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: fecha_biopsia
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: biopsia_conocida_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: fecha_colposcopia_resultado
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: colposcopia_resultado_conocida_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: fecha_diagnostico_biopsia
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: diagnostico_biopsia_conocido_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: toma_dia
|
||||
type: categorical
|
||||
- name: reporte_dia
|
||||
type: categorical
|
||||
- name: con_antecedente
|
||||
type: categorical
|
||||
- name: dias_toma_colposcopia
|
||||
type: categorical
|
||||
- name: biopsia_dia
|
||||
type: categorical
|
||||
- name: dias_toma_biopsia
|
||||
type: categorical
|
||||
- name: colposcopia_resultado_dia
|
||||
type: categorical
|
||||
- name: dias_resultado_colposcopia
|
||||
type: categorical
|
||||
- name: dias_colposcopia_biopsia
|
||||
type: categorical
|
||||
- name: dias_biopsia_diagnostico
|
||||
type: categorical
|
||||
measures:
|
||||
- name: citologias_en_ruta
|
||||
description: "Distinct samples (the source's cytology id): the unit of the times along the route."
|
||||
agg: count_distinct
|
||||
expr: fuente_id
|
||||
|
||||
metrics:
|
||||
- name: cacu_dias_toma_colposcopia
|
||||
label: "Tiempo de toma de muestra a colposcopía"
|
||||
description: >-
|
||||
Días naturales de la toma de cada citología del periodo a la primera colposcopía posterior, dentro del horizonte y a la fecha de corte. La colposcopía se infiere de notas, órdenes y biopsias: su fecha es la de la consulta que ocurrió. Se excluyen las citologías de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: citologias_en_ruta
|
||||
filter: "{{ Dimension('toma_ruta__con_antecedente') }} = 0"
|
||||
config:
|
||||
meta:
|
||||
measure_url: cacu/CACU_DIAS_TOMA_COLPOSCOPIA
|
||||
version: 0.1.0
|
||||
scoring: continuous-variable
|
||||
basis: examen
|
||||
grupo: TOTAL
|
||||
contrato: C3r
|
||||
improvement_notation: decrease
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c3r_caja]
|
||||
poblaciones_fhir: [initial-population]
|
||||
conocida_en: [toma_conocida_en]
|
||||
observacion:
|
||||
valor: dias_toma_colposcopia
|
||||
fechada_en: [fecha_colposcopia]
|
||||
conocida_en: [colposcopia_conocida_en]
|
||||
horizonte:
|
||||
dias: "{{ var('horizonte_toma_colposcopia_dias') }}"
|
||||
dia_inicio: toma_dia
|
||||
- name: cacu_dias_toma_biopsia
|
||||
label: "Tiempo de toma de muestra a resultado de biopsia"
|
||||
description: >-
|
||||
Días naturales de la toma de cada citología del periodo al primer reporte de la biopsia que esa citología originó, dentro del horizonte y a la fecha de corte. Se excluyen las citologías de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: citologias_en_ruta
|
||||
filter: "{{ Dimension('toma_ruta__con_antecedente') }} = 0"
|
||||
config:
|
||||
meta:
|
||||
measure_url: cacu/CACU_DIAS_TOMA_BIOPSIA
|
||||
version: 0.1.0
|
||||
scoring: continuous-variable
|
||||
basis: examen
|
||||
grupo: TOTAL
|
||||
contrato: C3r
|
||||
improvement_notation: decrease
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c3r_caja]
|
||||
poblaciones_fhir: [initial-population]
|
||||
conocida_en: [toma_conocida_en]
|
||||
observacion:
|
||||
valor: dias_toma_biopsia
|
||||
fechada_en: [fecha_biopsia]
|
||||
conocida_en: [biopsia_conocida_en]
|
||||
horizonte:
|
||||
dias: "{{ var('horizonte_toma_biopsia_dias') }}"
|
||||
dia_inicio: toma_dia
|
||||
- name: cacu_dias_resultado_colposcopia
|
||||
label: "Tiempo del resultado de citología a la colposcopía"
|
||||
description: >-
|
||||
Días naturales del resultado de cada citología del periodo a la primera colposcopía desde ese día, dentro del horizonte y a la fecha de corte. Solo entran las citologías con resultado. Se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: citologias_en_ruta
|
||||
filter: "{{ Dimension('toma_ruta__con_antecedente') }} = 0 and {{ Dimension('toma_ruta__reporte_dia') }} is not null"
|
||||
config:
|
||||
meta:
|
||||
measure_url: cacu/CACU_DIAS_RESULTADO_COLPOSCOPIA
|
||||
version: 0.1.0
|
||||
scoring: continuous-variable
|
||||
basis: examen
|
||||
grupo: TOTAL
|
||||
contrato: C3r
|
||||
improvement_notation: decrease
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c3r_caja]
|
||||
poblaciones_fhir: [initial-population]
|
||||
conocida_en: [toma_conocida_en, resultado_conocido_en]
|
||||
observacion:
|
||||
valor: dias_resultado_colposcopia
|
||||
fechada_en: [fecha_colposcopia_resultado]
|
||||
conocida_en: [colposcopia_resultado_conocida_en]
|
||||
horizonte:
|
||||
dias: "{{ var('horizonte_resultado_colposcopia_dias') }}"
|
||||
dia_inicio: reporte_dia
|
||||
- name: cacu_dias_colposcopia_biopsia
|
||||
label: "Tiempo de la colposcopía al resultado de biopsia"
|
||||
description: >-
|
||||
Días naturales de la colposcopía posterior al resultado de cada citología del periodo al primer reporte de la biopsia que esa citología originó, dentro del horizonte y a la fecha de corte. Solo entran las citologías con colposcopía. Se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: citologias_en_ruta
|
||||
filter: "{{ Dimension('toma_ruta__con_antecedente') }} = 0 and {{ Dimension('toma_ruta__colposcopia_resultado_dia') }} is not null"
|
||||
config:
|
||||
meta:
|
||||
measure_url: cacu/CACU_DIAS_COLPOSCOPIA_BIOPSIA
|
||||
version: 0.1.0
|
||||
scoring: continuous-variable
|
||||
basis: examen
|
||||
grupo: TOTAL
|
||||
contrato: C3r
|
||||
improvement_notation: decrease
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c3r_caja]
|
||||
poblaciones_fhir: [initial-population]
|
||||
conocida_en: [toma_conocida_en, resultado_conocido_en, colposcopia_resultado_conocida_en]
|
||||
observacion:
|
||||
valor: dias_colposcopia_biopsia
|
||||
fechada_en: [fecha_biopsia]
|
||||
conocida_en: [biopsia_conocida_en]
|
||||
horizonte:
|
||||
dias: "{{ var('horizonte_colposcopia_biopsia_dias') }}"
|
||||
dia_inicio: colposcopia_resultado_dia
|
||||
- name: cacu_dias_biopsia_diagnostico
|
||||
label: "Tiempo del resultado de biopsia al diagnóstico"
|
||||
description: >-
|
||||
Días naturales del primer reporte de biopsia de cada citología del periodo a la primera nota médica de diagnóstico posterior, dentro del horizonte y a la fecha de corte. Solo entran las citologías con biopsia reportada. Se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: citologias_en_ruta
|
||||
filter: "{{ Dimension('toma_ruta__con_antecedente') }} = 0 and {{ Dimension('toma_ruta__biopsia_dia') }} is not null"
|
||||
config:
|
||||
meta:
|
||||
measure_url: cacu/CACU_DIAS_BIOPSIA_DIAGNOSTICO
|
||||
version: 0.1.0
|
||||
scoring: continuous-variable
|
||||
basis: examen
|
||||
grupo: TOTAL
|
||||
contrato: C3r
|
||||
improvement_notation: decrease
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c3r_caja]
|
||||
poblaciones_fhir: [initial-population]
|
||||
conocida_en: [toma_conocida_en, biopsia_conocida_en]
|
||||
observacion:
|
||||
valor: dias_biopsia_diagnostico
|
||||
fechada_en: [fecha_diagnostico_biopsia]
|
||||
conocida_en: [diagnostico_biopsia_conocido_en]
|
||||
horizonte:
|
||||
dias: "{{ var('horizonte_biopsia_diagnostico_dias') }}"
|
||||
dia_inicio: biopsia_dia
|
||||
@@ -146,6 +146,7 @@ metrics:
|
||||
grupo: TOTAL
|
||||
contrato: C2
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c2_donas, fig_c2_barras]
|
||||
poblaciones_fhir: [measure-observation]
|
||||
conocida_en: [toma_conocida_en]
|
||||
parametros:
|
||||
@@ -172,6 +173,23 @@ metrics:
|
||||
conocida_en: [biopsia_conocida_en]
|
||||
orden: [biopsia_gravedad, biopsia_fecha_reporte, biopsia_fuente_id]
|
||||
sin_seguimiento: SIN_BIOPSIA
|
||||
# The captions and colours of `cacu.catalogos.biopsia`, least to most severe (WebApi's reference parameters,
|
||||
# provisional), then the two kept apart: no biopsy reported at the cut-off, and one reported without a grade.
|
||||
# Groups (provisional): ANORMAL is `deteccion_grados` (dbt var and parameter `cacu.deteccion_grados`), the other
|
||||
# grades NO_ANORMAL; «Sin biopsia aún» is in no group and «Sin dato» in its own.
|
||||
etiquetas:
|
||||
NORMAL: {etiqueta: "Normal", color: "#9DBFE3", grupo: NO_ANORMAL}
|
||||
LIEBG: {etiqueta: "LIEBG (CIN 1)", color: "#E8C28E", grupo: NO_ANORMAL}
|
||||
LIEAG: {etiqueta: "LIEAG (CIN 2 y 3)", color: "#D98E4A", grupo: ANORMAL}
|
||||
CIS: {etiqueta: "Carcinoma in situ", color: "#B55A1F", grupo: ANORMAL}
|
||||
CARCINOMA: {etiqueta: "Carcinoma invasor", color: "#7A2E0E", grupo: ANORMAL}
|
||||
SIN_BIOPSIA: {etiqueta: "Sin biopsia aún", color: "#C9CDD2"}
|
||||
SIN_DATO: {etiqueta: "Biopsia sin grado", color: "#C9CDD2", grupo: SIN_DATO}
|
||||
# The groups' captions; the no-data group is named as its category.
|
||||
grupos:
|
||||
NO_ANORMAL: "Menor que LIEAG"
|
||||
ANORMAL: "LIEAG o más"
|
||||
SIN_DATO: "Biopsia sin grado"
|
||||
estratos:
|
||||
# The result of that same sample.
|
||||
citologia_alto_grado:
|
||||
|
||||
@@ -3,27 +3,29 @@
|
||||
-- was known (`toma_conocida_en`) and when its result was (`resultado_conocido_en`, null without a result). The birth
|
||||
-- date is the patient's, for strata by age. From her timeline: the first note that resolves the sample (a
|
||||
-- `diagnostico` after it, within `horizonte_toma_diagnostico_dias`), with its days and when it was known, and whether
|
||||
-- a cervical cancer note (`antecedente`) came before the sample.
|
||||
-- a cervical cancer note (`antecedente`) came before the sample. The first `tratamiento` after the sample, within
|
||||
-- `horizonte_toma_tratamiento_dias`, and the first one after that diagnosis, within
|
||||
-- `horizonte_diagnostico_tratamiento_dias`, each with its days and when it was known.
|
||||
|
||||
with resuelve as (
|
||||
select c.procedimiento_id, min(l.fecha) as fecha_diagnostico
|
||||
from {{ ref('cacu_citologias') }} c
|
||||
join {{ ref('cacu_linea_de_tiempo') }} l
|
||||
on l.pac_id = c.pac_id and l.tipo = 'diagnostico' and l.fecha > c.fecha_toma
|
||||
join {{ source('silver', 'dim_fecha') }} dl on dl.fecha = l.fecha
|
||||
join {{ source('silver', 'dim_fecha') }} dt on dt.fecha = c.fecha_toma
|
||||
where dl.dia_num - dt.dia_num < {{ var('horizonte_toma_diagnostico_dias') }}
|
||||
group by c.procedimiento_id
|
||||
with diagnostico as (
|
||||
{{ primer_evento_posterior(ref('cacu_citologias'), 'procedimiento_id', 'fecha_toma', ref('cacu_linea_de_tiempo'),
|
||||
'diagnostico', var('horizonte_toma_diagnostico_dias')) }}
|
||||
),
|
||||
|
||||
-- When the first resolving note became known: the earliest load among her notes of that day.
|
||||
diagnostico as (
|
||||
select r.procedimiento_id, r.fecha_diagnostico, min(l.conocida_en) as diagnostico_conocido_en
|
||||
from resuelve r
|
||||
join {{ ref('cacu_citologias') }} c on c.procedimiento_id = r.procedimiento_id
|
||||
join {{ ref('cacu_linea_de_tiempo') }} l
|
||||
on l.pac_id = c.pac_id and l.tipo = 'diagnostico' and l.fecha = r.fecha_diagnostico
|
||||
group by r.procedimiento_id, r.fecha_diagnostico
|
||||
tratamiento as (
|
||||
{{ primer_evento_posterior(ref('cacu_citologias'), 'procedimiento_id', 'fecha_toma', ref('cacu_linea_de_tiempo'),
|
||||
'tratamiento', var('horizonte_toma_tratamiento_dias')) }}
|
||||
),
|
||||
|
||||
desde_diagnostico as (
|
||||
select c.procedimiento_id, c.pac_id, dx.fecha_fin as fecha
|
||||
from {{ ref('cacu_citologias') }} c
|
||||
join diagnostico dx on dx.inicio_id = c.procedimiento_id
|
||||
),
|
||||
|
||||
tratamiento_del_diagnostico as (
|
||||
{{ primer_evento_posterior('desde_diagnostico', 'procedimiento_id', 'fecha', ref('cacu_linea_de_tiempo'),
|
||||
'tratamiento', var('horizonte_diagnostico_tratamiento_dias')) }}
|
||||
),
|
||||
|
||||
primer_antecedente as (
|
||||
@@ -47,9 +49,16 @@ select
|
||||
persona.fecha_nacimiento,
|
||||
dia_toma.dia_num as toma_dia,
|
||||
dia_reporte.dia_num - dia_toma.dia_num as dias_toma_reporte,
|
||||
dx.fecha_diagnostico,
|
||||
dx.diagnostico_conocido_en,
|
||||
dx.fecha_fin as fecha_diagnostico,
|
||||
dx.fin_conocido_en as diagnostico_conocido_en,
|
||||
dia_diagnostico.dia_num - dia_toma.dia_num as dias_toma_diagnostico,
|
||||
tx.fecha_fin as fecha_tratamiento,
|
||||
tx.fin_conocido_en as tratamiento_conocido_en,
|
||||
dia_tratamiento.dia_num - dia_toma.dia_num as dias_toma_tratamiento,
|
||||
dia_diagnostico.dia_num as diagnostico_dia,
|
||||
td.fecha_fin as fecha_tratamiento_diagnostico,
|
||||
td.fin_conocido_en as tratamiento_diagnostico_conocido_en,
|
||||
dia_tratamiento_dx.dia_num - dia_diagnostico.dia_num as dias_diagnostico_tratamiento,
|
||||
case when antecedente.fecha < c.fecha_toma then 1 else 0 end as con_antecedente
|
||||
from {{ ref('cacu_citologias') }} c
|
||||
join {{ source('silver', 'persona') }} persona
|
||||
@@ -64,8 +73,16 @@ left join {{ source('silver', 'dim_fecha') }} dia_toma
|
||||
left join {{ source('silver', 'dim_fecha') }} dia_reporte
|
||||
on dia_reporte.fecha = c.fecha_reporte
|
||||
left join diagnostico dx
|
||||
on dx.procedimiento_id = c.procedimiento_id
|
||||
on dx.inicio_id = c.procedimiento_id
|
||||
left join {{ source('silver', 'dim_fecha') }} dia_diagnostico
|
||||
on dia_diagnostico.fecha = dx.fecha_diagnostico
|
||||
on dia_diagnostico.fecha = dx.fecha_fin
|
||||
left join tratamiento tx
|
||||
on tx.inicio_id = c.procedimiento_id
|
||||
left join {{ source('silver', 'dim_fecha') }} dia_tratamiento
|
||||
on dia_tratamiento.fecha = tx.fecha_fin
|
||||
left join tratamiento_del_diagnostico td
|
||||
on td.inicio_id = c.procedimiento_id
|
||||
left join {{ source('silver', 'dim_fecha') }} dia_tratamiento_dx
|
||||
on dia_tratamiento_dx.fecha = td.fecha_fin
|
||||
left join primer_antecedente antecedente
|
||||
on antecedente.pac_id = c.pac_id
|
||||
|
||||
@@ -60,6 +60,28 @@ semantic_models:
|
||||
time_granularity: day
|
||||
- name: dias_toma_diagnostico
|
||||
type: categorical
|
||||
- name: fecha_tratamiento
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: tratamiento_conocido_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: dias_toma_tratamiento
|
||||
type: categorical
|
||||
- name: diagnostico_dia
|
||||
type: categorical
|
||||
- name: fecha_tratamiento_diagnostico
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: tratamiento_diagnostico_conocido_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: dias_diagnostico_tratamiento
|
||||
type: categorical
|
||||
- name: con_antecedente
|
||||
type: categorical
|
||||
measures:
|
||||
@@ -131,6 +153,7 @@ metrics:
|
||||
grupo: TOTAL
|
||||
contrato: C2
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c2_donas, fig_c2_barras]
|
||||
poblaciones_fhir: [measure-observation]
|
||||
conocida_en: [toma_conocida_en]
|
||||
parametros:
|
||||
@@ -148,6 +171,23 @@ metrics:
|
||||
fechada_en: [fecha_reporte]
|
||||
conocida_en: [resultado_conocido_en]
|
||||
orden: [fecha_toma, fuente_id]
|
||||
# The captions and colours of `cacu.catalogos.citologia` and `cacu.catalogos.sin_dato` (WebApi's
|
||||
# reference parameters, provisional), in their order, from least to most severe. Groups (provisional): ANORMAL
|
||||
# is `citologia_anomala` (dbt var and parameter `cacu.citologia_anomala`), the rest is NO_ANORMAL, and «Sin dato»
|
||||
# is a group of its own.
|
||||
etiquetas:
|
||||
NORMAL: {etiqueta: "Normal", color: "#9DBFE3", grupo: NO_ANORMAL}
|
||||
ASC-US: {etiqueta: "ASC-US", color: "#2F6DB3", grupo: ANORMAL}
|
||||
LIEBG: {etiqueta: "LIEBG", color: "#E8C28E", grupo: ANORMAL}
|
||||
ASC-H: {etiqueta: "ASC-H", color: "#D98E4A", grupo: ANORMAL}
|
||||
LIEAG: {etiqueta: "LIEAG", color: "#B55A1F", grupo: ANORMAL}
|
||||
CIS: {etiqueta: "Carcinoma in situ", color: "#7A2E0E", grupo: ANORMAL}
|
||||
SIN_DATO: {etiqueta: "Sin dato", color: "#C9CDD2", grupo: SIN_DATO}
|
||||
# The groups' captions; the no-data group is named as its category.
|
||||
grupos:
|
||||
NO_ANORMAL: "Sin anomalía"
|
||||
ANORMAL: "Anormal"
|
||||
SIN_DATO: "Sin dato"
|
||||
estratos:
|
||||
grupo_edad:
|
||||
tipo: edad_al_inicio_del_periodo
|
||||
@@ -166,6 +206,14 @@ metrics:
|
||||
# takes her out.
|
||||
- {valor: PRE_COLPOSCOPIA, si: [{citologia_de_vigilancia: true}, {citologia: false}]}
|
||||
resto: INFO_INSUFICIENTE
|
||||
# The follow-up statuses' captions, as the follow-up list shows them (WebApi follow_up/estratos.toml). Kept
|
||||
# out of `estratos` on purpose: the strata's spec is part of a report's key and captions don't change answers.
|
||||
etiquetas_estrato:
|
||||
estatus_seguimiento:
|
||||
PRE_COLPOSCOPIA: "Pre colposcopia"
|
||||
POST_COLPOSCOPIA: "Post colposcopia"
|
||||
POST_TRATAMIENTO: "Post tratamiento"
|
||||
INFO_INSUFICIENTE: "Información insuficiente"
|
||||
- name: cacu_eu_tiempo_reporte
|
||||
label: "Días de la toma de la citología a su resultado"
|
||||
description: >-
|
||||
@@ -185,6 +233,7 @@ metrics:
|
||||
contrato: C3r
|
||||
improvement_notation: decrease
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c3r_caja]
|
||||
poblaciones_fhir: [initial-population]
|
||||
conocida_en: [toma_conocida_en]
|
||||
parametros:
|
||||
@@ -219,6 +268,7 @@ metrics:
|
||||
contrato: C3r
|
||||
improvement_notation: decrease
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c3r_caja]
|
||||
poblaciones_fhir: [initial-population]
|
||||
conocida_en: [toma_conocida_en]
|
||||
# The first resolving note's days, if it was written by the event cut-off; a sample without one whose
|
||||
@@ -230,3 +280,69 @@ metrics:
|
||||
horizonte:
|
||||
dias: "{{ var('horizonte_toma_diagnostico_dias') }}"
|
||||
dia_inicio: toma_dia
|
||||
- name: cacu_dias_toma_tratamiento
|
||||
label: "Tiempo de tamizaje a tratamiento"
|
||||
description: >-
|
||||
Días naturales de la toma de cada citología del periodo al primer tratamiento posterior: una nota médica con un
|
||||
CIE-10 de tratamiento después de la primera colposcopia de la paciente, dentro del horizonte y a la fecha de
|
||||
corte. Entran todas las citologías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de
|
||||
cáncer cervicouterino anterior a la toma. El tratamiento se infiere de la nota: no distingue el indicado del
|
||||
realizado.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: citologias
|
||||
filter: "{{ Dimension('toma__con_antecedente') }} = 0"
|
||||
config:
|
||||
meta:
|
||||
measure_url: cacu/CACU_DIAS_TOMA_TRATAMIENTO
|
||||
version: 0.1.0
|
||||
scoring: continuous-variable
|
||||
basis: examen
|
||||
grupo: TOTAL
|
||||
contrato: C3r
|
||||
improvement_notation: decrease
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c3r_caja]
|
||||
poblaciones_fhir: [initial-population]
|
||||
conocida_en: [toma_conocida_en]
|
||||
# The first treatment's days, if it was written by the event cut-off; a sample without one whose horizon
|
||||
# hasn't passed by then isn't measured yet. The horizon is the one the model used to find the treatment.
|
||||
observacion:
|
||||
valor: dias_toma_tratamiento
|
||||
fechada_en: [fecha_tratamiento]
|
||||
conocida_en: [tratamiento_conocido_en]
|
||||
horizonte:
|
||||
dias: "{{ var('horizonte_toma_tratamiento_dias') }}"
|
||||
dia_inicio: toma_dia
|
||||
- name: cacu_dias_diagnostico_tratamiento
|
||||
label: "Tiempo de diagnóstico a tratamiento"
|
||||
description: >-
|
||||
Días naturales del diagnóstico que resuelve cada citología del periodo al primer tratamiento posterior: una nota
|
||||
médica con un CIE-10 de tratamiento después de la primera colposcopia de la paciente, dentro del horizonte y a la
|
||||
fecha de corte. Solo entran las citologías que un diagnóstico resolvió; se excluyen las de pacientes con un
|
||||
diagnóstico de cáncer cervicouterino anterior a la toma. Dos citologías que resuelve el mismo diagnóstico cuentan
|
||||
cada una. El tratamiento se infiere de la nota: no distingue el indicado del realizado.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: citologias
|
||||
filter: "{{ Dimension('toma__con_antecedente') }} = 0 and {{ Dimension('toma__diagnostico_dia') }} is not null"
|
||||
config:
|
||||
meta:
|
||||
measure_url: cacu/CACU_DIAS_DIAGNOSTICO_TRATAMIENTO
|
||||
version: 0.1.0
|
||||
scoring: continuous-variable
|
||||
basis: examen
|
||||
grupo: TOTAL
|
||||
contrato: C3r
|
||||
improvement_notation: decrease
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c3r_caja]
|
||||
poblaciones_fhir: [initial-population]
|
||||
conocida_en: [toma_conocida_en, diagnostico_conocido_en]
|
||||
observacion:
|
||||
valor: dias_diagnostico_tratamiento
|
||||
fechada_en: [fecha_tratamiento_diagnostico]
|
||||
conocida_en: [tratamiento_diagnostico_conocido_en]
|
||||
horizonte:
|
||||
dias: "{{ var('horizonte_diagnostico_tratamiento_dias') }}"
|
||||
dia_inicio: diagnostico_dia
|
||||
|
||||
@@ -1,8 +1,27 @@
|
||||
{# A view, not ephemeral like the other silver models: cohorts query it. Its sources: cacu_linea_de_tiempo.yml;
|
||||
the procedures silver doesn't hold but its facts imply (colposcopy, treatment): cacu_procedimientos_inferidos. #}
|
||||
the procedures silver doesn't hold but its facts imply (colposcopy, treatment): cacu_procedimientos_inferidos; her
|
||||
birth and death, from `persona` (as CaMa's timeline): the survival scenario's age and outcome. They are not
|
||||
clinical events, so a cohort indexed at the first event leaves them out (`cacu_total_index_date`). #}
|
||||
{{ config(materialized = 'view') }}
|
||||
|
||||
{{ linea_de_tiempo(config.get('meta')['fuentes']) }}
|
||||
union all
|
||||
select pac_id, fecha, conocida_en, clase, tipo, codigo, valor_codigo, valor_numerico, fuente_tabla, fuente_id
|
||||
from {{ ref('cacu_procedimientos_inferidos') }}
|
||||
{#- `persona` holds staging's current value, with no load of its own: it's known as of the latest load. #}
|
||||
{%- for tipo, columna in [('nacimiento', 'fecha_nacimiento'), ('defuncion', 'fecha_defuncion')] %}
|
||||
union all
|
||||
select
|
||||
persona.pac_id as pac_id,
|
||||
persona.{{ columna }} as fecha,
|
||||
(select max(carga.inicio) from {{ source('silver', 'carga') }} carga) as conocida_en,
|
||||
{{ as_text("'persona'") }} as clase,
|
||||
{{ as_text("'" ~ tipo ~ "'") }} as tipo,
|
||||
{{ as_text("'" ~ tipo ~ "'") }} as codigo,
|
||||
{{ as_text('null') }} as valor_codigo,
|
||||
cast(null as {{ dbt.type_float() }}) as valor_numerico,
|
||||
{{ as_text("'persona'") }} as fuente_tabla,
|
||||
{{ as_text('persona.pac_id') }} as fuente_id
|
||||
from {{ source('silver', 'persona') }} persona
|
||||
where persona.{{ columna }} is not null
|
||||
{%- endfor %}
|
||||
|
||||
@@ -16,8 +16,12 @@ models:
|
||||
fuentes:
|
||||
- {estudio_id: "citologia", clase: "toma", resultado_id: "citologia.calidad_muestra", clase_de_linea: "procedimiento", tipo: "citologia", codigo: "citologia_cervical"}
|
||||
- {estudio_id: "citologia", clase: "reporte", resultado_id: "citologia.bethesda", clase_de_linea: "medicion", tipo: "bethesda", codigo: "bethesda"}
|
||||
- {estudio_id: "citologia", clase: "reporte", resultado_id: "citologia.celulas_glandulares", clase_de_linea: "medicion", tipo: "glandular"}
|
||||
- {estudio_id: "vph", clase: "reporte", resultado_id: "vph.resultado", clase_de_linea: "medicion", tipo: "vph", codigo: "vph"}
|
||||
- {estudio_id: "vph", clase: "reporte", resultado_id: "vph.genotipo_16_18", clase_de_linea: "medicion", tipo: "vph_genotipo_16_18", valor: "numerico"}
|
||||
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.grado", clase_de_linea: "medicion", tipo: "biopsia", codigo: "cin"}
|
||||
- {estudio_id: null, clase: "orden", resultado_id: null, clase_de_linea: "orden", tipo: "orden", columna: "codigo_fuente"}
|
||||
# A biopsy order as such: the post-colposcopy cohorts tell an order still without a report (same source row
|
||||
# as its `biopsia`) from a colposcopy with no biopsy taken.
|
||||
- {estudio_id: "biopsia", clase: "orden", resultado_id: null, clase_de_linea: "orden", tipo: "orden_biopsia"}
|
||||
- {estudio_id: "nota_medica", clase: "encuentro", resultado_id: "nota_medica.diagnostico", clase_de_linea: "diagnostico", tipo: "nota_medica"}
|
||||
|
||||
@@ -68,7 +68,7 @@ unit_tests:
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2024-03-10' as fecha, 'escenario_postratamiento' as tipo
|
||||
union all select 2, '2024-02-01', 'escenario_control'
|
||||
union all select 2, '2024-02-01', 'antecedente'
|
||||
union all select 3, '2027-02-01', 'escenario_postratamiento'
|
||||
expect:
|
||||
rows:
|
||||
|
||||
@@ -1,17 +1,44 @@
|
||||
version: 2
|
||||
|
||||
# The total cohort: every patient with an invasive carcinoma, from the date of its first biopsy report, with no further
|
||||
# rule. It is the source of the survival model, which reads each patient's variables from her whole timeline.
|
||||
# The total cohort: every patient with a clinical event up to the cut-off, at her first event, with no rules. The CaMa
|
||||
# scenarios read this cohort and the timeline and apply their own index and rules (`models/steps/indexing.py`), which
|
||||
# then belong to the model and its tests, not to a cohort. Parameters: the `cama_total_cohort` var.
|
||||
models:
|
||||
- name: cama_total_all_patients
|
||||
- name: cama_total_population
|
||||
description: Every patient of the domain.
|
||||
config:
|
||||
materialized: ephemeral
|
||||
meta:
|
||||
cohort: cama/cohorte_total
|
||||
kind: population
|
||||
cutoff: "{{ var('total_cohort')['cutoff'] }}"
|
||||
parameters: "{{ var('total_cohort') | tojson }}"
|
||||
# Changing a rule changes the cohort: bump `version` (stored with every build).
|
||||
version: "0.1.0"
|
||||
cutoff: "{{ var('cama_total_cohort')['cutoff'] }}"
|
||||
parameters: "{{ var('cama_total_cohort') | tojson }}"
|
||||
- name: cama_total_index_date
|
||||
description: First biopsy reported as invasive carcinoma up to the cut-off. Sets the index date.
|
||||
description: The patient's first clinical event in the timeline up to the cut-off. Sets the index date.
|
||||
config: {materialized: ephemeral, meta: {cohort: cama/cohorte_total, kind: index}}
|
||||
|
||||
unit_tests:
|
||||
- name: total_index_is_the_first_clinical_event_up_to_the_cutoff
|
||||
description: >
|
||||
Pins down: patient 1's index is her earliest clinical event, whatever its type, and her birth, which is earlier,
|
||||
does not set it; patient 2's only clinical event is after the cut-off, so she has no index. Fails if the index
|
||||
takes a later event, one type only, a persona event, or ignores the cut-off.
|
||||
model: cama_total_index_date
|
||||
overrides:
|
||||
vars:
|
||||
cama_total_cohort: {recruitment_start: "2018-01-01", recruitment_end: "2027-01-01", cutoff: "2026-01-01"}
|
||||
given:
|
||||
- input: ref('cama_linea_de_tiempo')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '1970-05-01' as fecha, 'persona' as fuente_tabla, '1' as fuente_id
|
||||
union all select 1, '2025-05-01', 'mastografia', 'b'
|
||||
union all select 1, '2024-02-01', 'notamedica', 'a'
|
||||
union all select 2, '1960-01-01', 'persona', '2'
|
||||
union all select 2, '2027-03-01', 'mastografia', 'c'
|
||||
expect:
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as pac_id, '2024-02-01' as fecha_indice, 'notamedica' as indice_fuente_tabla, 'a' as indice_fuente_id
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
{# Every patient of the domain: the total cohort has no rule but the index. #}
|
||||
select pac_id
|
||||
from {{ source('silver', 'persona') }}
|
||||
@@ -1,13 +1,16 @@
|
||||
{# The date of the patient's first biopsy reported as invasive carcinoma, up to the cut-off: the diagnosis. The report's
|
||||
`fuente_id` names it. #}
|
||||
{% set p = var('total_cohort') %}
|
||||
with biopsies as (
|
||||
select
|
||||
pac_id, fecha, fuente_tabla, fuente_id,
|
||||
row_number() over (partition by pac_id order by fecha, fuente_id) as position
|
||||
{#
|
||||
Every patient with at least one clinical event in the timeline up to the cut-off, indexed at her first one (the
|
||||
earliest, ties broken by source). Her birth and death come from `persona` and are not clinical events, so they never
|
||||
set the index. No recruitment window and no exclusions: a model whose rules can't be written as SQL starts from this
|
||||
cohort and applies them in its own pipeline, over the timeline.
|
||||
#}
|
||||
{% set p = var('cama_total_cohort') %}
|
||||
with eventos as (
|
||||
select pac_id, fecha, fuente_tabla, fuente_id,
|
||||
row_number() over (partition by pac_id order by fecha, fuente_tabla, fuente_id) as posicion
|
||||
from {{ ref('cama_linea_de_tiempo') }}
|
||||
where tipo = 'biopsia' and valor_codigo = 'CARCINOMA_INVASOR' and fecha <= '{{ p.cutoff }}'
|
||||
where fecha <= '{{ p.cutoff }}' and fuente_tabla <> 'persona'
|
||||
)
|
||||
select pac_id, fecha as fecha_indice, fuente_tabla as indice_fuente_tabla, fuente_id as indice_fuente_id
|
||||
from biopsies
|
||||
where position = 1
|
||||
from eventos
|
||||
where posicion = 1
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
{# Every patient of the domain: where the cohort's attrition starts. #}
|
||||
select pac_id
|
||||
from {{ source('silver', 'persona') }}
|
||||
@@ -4,13 +4,10 @@
|
||||
-- diagnostico a note that can resolve a mammogram: a diagnosis ICD-10 (`cama.cie_diagnostico`) written by a
|
||||
-- diagnosing specialty (`cama.especialidades_diagnostico`)
|
||||
-- antecedente a note with a breast cancer ICD-10 (`cama.cie_antecedente`), whoever wrote it
|
||||
-- and each patient's clinical scenario (`cama.escenarios`), a hierarchy, each level from its first evidence:
|
||||
-- escenario_tamizaje level 1: her first mammogram before any malignant diagnosis
|
||||
-- escenario_control level 2: a malignant breast tumour
|
||||
-- escenario_postratamiento level 3: a discharge after that diagnosis
|
||||
-- The kind of evidence goes in `valor_codigo` and the level in `valor_numerico`. A patient's scenario on a date is the
|
||||
-- highest level she has reached by then; one with no fact is in screening. Every rule is a dbt var, so changing one
|
||||
-- is recompiling, not reloading.
|
||||
-- and each patient's clinical scenario (`cama.escenarios`), one of two:
|
||||
-- escenario_postratamiento from her first evidence of a treatment after a malignant breast tumour
|
||||
-- en observación every other patient, and a post-treatment one before that evidence; it has no fact
|
||||
-- The kind of evidence goes in `valor_codigo`. Every rule is a dbt var, so changing one is recompiling, not reloading.
|
||||
{% set r = var('cama') %}
|
||||
{% set e = r['escenarios'] %}
|
||||
|
||||
@@ -35,34 +32,22 @@ nota_maligna as (
|
||||
select * from nota where cie_codigo in {{ sql_list(e['cie_tumor_maligno']) }}
|
||||
),
|
||||
|
||||
-- Each level's evidence, of the kinds its rule lists.
|
||||
evidencia_control as (
|
||||
select pac_id, fecha, conocida_en, fuente_tabla, fuente_id, 'cie' as evidencia from nota where 1 = 0
|
||||
{% if 'cie' in e['control_evidencias'] %}
|
||||
-- The malignant diagnosis a post-treatment evidence must follow, of the kinds `diagnostico_evidencias` lists.
|
||||
evidencia_diagnostico as (
|
||||
select pac_id, fecha from nota where 1 = 0
|
||||
{% if 'cie' in e['diagnostico_evidencias'] %}
|
||||
union all
|
||||
select pac_id, fecha, conocida_en, fuente_tabla, fuente_id, 'cie' from nota_maligna
|
||||
select pac_id, fecha from nota_maligna
|
||||
{% endif %}
|
||||
{% if 'biopsia' in e['control_evidencias'] %}
|
||||
{% if 'biopsia' in e['diagnostico_evidencias'] %}
|
||||
union all
|
||||
select b.pac_id, b.fecha_reporte, c.inicio, b.fuente_tabla, b.fuente_id, 'biopsia'
|
||||
from {{ ref('cama_biopsias') }} b
|
||||
join {{ source('silver', 'carga') }} c on c.carga_id = b.reporte_carga_id
|
||||
where b.grado in {{ sql_list(e['grados_malignos']) }}
|
||||
select pac_id, fecha_reporte from {{ ref('cama_biopsias') }}
|
||||
where grado in {{ sql_list(e['grados_malignos']) }}
|
||||
{% endif %}
|
||||
),
|
||||
|
||||
diagnostico_maligno as (
|
||||
select pac_id, min(fecha) as primera from evidencia_control where fecha is not null group by pac_id
|
||||
),
|
||||
|
||||
evidencia_tamizaje as (
|
||||
select pac_id, fecha, conocida_en, fuente_tabla, fuente_id, 'mastografia' as evidencia from nota where 1 = 0
|
||||
{% if 'mastografia' in e['tamizaje_evidencias'] %}
|
||||
union all
|
||||
select m.pac_id, m.fecha_toma, c.inicio, m.fuente_tabla, m.fuente_id, 'mastografia'
|
||||
from {{ ref('cama_mastografias') }} m
|
||||
join {{ source('silver', 'carga') }} c on c.carga_id = m.toma_carga_id
|
||||
{% endif %}
|
||||
select pac_id, min(fecha) as primera from evidencia_diagnostico where fecha is not null group by pac_id
|
||||
),
|
||||
|
||||
evidencia_postratamiento as (
|
||||
@@ -75,6 +60,14 @@ evidencia_postratamiento as (
|
||||
where n.tipo_nota in {{ sql_list(e['tipos_nota_egreso']) }}
|
||||
and (n.cie_codigo in {{ sql_list(e['cie_tumor_maligno']) }} or n.fecha >= d.primera)
|
||||
{% endif %}
|
||||
{% if 'tratamiento' in e['postratamiento_evidencias'] %}
|
||||
union all
|
||||
select t.pac_id, t.fecha, c.inicio, t.fuente_tabla, t.fuente_id, 'tratamiento'
|
||||
from {{ source('silver', 'procedimiento') }} t
|
||||
join {{ source('silver', 'carga') }} c on c.carga_id = t.carga_id
|
||||
join diagnostico_maligno d on d.pac_id = t.pac_id and t.fecha >= d.primera
|
||||
where t.estudio_id in {{ sql_list(e['tratamiento_estudios']) }} and t.clase = 'encuentro'
|
||||
{% endif %}
|
||||
{% if 'nota' in e['postratamiento_evidencias'] %}
|
||||
union all
|
||||
select n.pac_id, n.fecha, n.conocida_en, n.fuente_tabla, n.fuente_id, 'nota'
|
||||
@@ -84,39 +77,25 @@ evidencia_postratamiento as (
|
||||
{% endif %}
|
||||
),
|
||||
|
||||
-- Screening only before a diagnosis; the other two from their first evidence.
|
||||
escenario as (
|
||||
select t.pac_id, t.fecha, t.conocida_en, 'escenario_tamizaje' as tipo, 1 as nivel, t.fuente_tabla, t.fuente_id,
|
||||
t.evidencia
|
||||
from evidencia_tamizaje t
|
||||
left join diagnostico_maligno d on d.pac_id = t.pac_id
|
||||
where d.primera is null or t.fecha < d.primera
|
||||
union all
|
||||
select pac_id, fecha, conocida_en, 'escenario_control', 2, fuente_tabla, fuente_id, evidencia
|
||||
from evidencia_control
|
||||
union all
|
||||
select pac_id, fecha, conocida_en, 'escenario_postratamiento', 3, fuente_tabla, fuente_id, evidencia
|
||||
from evidencia_postratamiento
|
||||
),
|
||||
|
||||
primera as (
|
||||
select escenario.*,
|
||||
row_number() over (partition by pac_id, tipo order by fecha, evidencia, fuente_id) as orden
|
||||
from escenario
|
||||
select evidencia_postratamiento.*,
|
||||
row_number() over (partition by pac_id order by fecha, evidencia, fuente_id) as orden
|
||||
from evidencia_postratamiento
|
||||
where fecha is not null
|
||||
),
|
||||
|
||||
inferidos as (
|
||||
select pac_id, fecha, conocida_en, 'diagnostico' as tipo, fuente_tabla, fuente_id,
|
||||
null as evidencia, null as nivel
|
||||
null as evidencia
|
||||
from nota
|
||||
where cie_codigo in {{ sql_list(r['cie_diagnostico']) }}
|
||||
and especialidad in {{ sql_list(r['especialidades_diagnostico']) }}
|
||||
union all
|
||||
select pac_id, fecha, conocida_en, 'antecedente', fuente_tabla, fuente_id, null, null from nota
|
||||
select pac_id, fecha, conocida_en, 'antecedente', fuente_tabla, fuente_id, null from nota
|
||||
where cie_codigo in {{ sql_list(r['cie_antecedente']) }}
|
||||
union all
|
||||
select pac_id, fecha, conocida_en, tipo, fuente_tabla, fuente_id, evidencia, nivel from primera where orden = 1
|
||||
select pac_id, fecha, conocida_en, 'escenario_postratamiento', fuente_tabla, fuente_id, evidencia
|
||||
from primera where orden = 1
|
||||
)
|
||||
|
||||
select
|
||||
@@ -127,7 +106,7 @@ select
|
||||
{{ as_text('tipo') }} as tipo,
|
||||
{{ as_text('tipo') }} as codigo,
|
||||
{{ as_text('evidencia') }} as valor_codigo,
|
||||
cast(nivel as {{ dbt.type_float() }}) as valor_numerico,
|
||||
cast(null as {{ dbt.type_float() }}) as valor_numerico,
|
||||
fuente_tabla,
|
||||
fuente_id
|
||||
from inferidos
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
version: 2
|
||||
|
||||
# The ADOS-2 association model's staging, read by dbt directly. Its rows are model output, not patient events
|
||||
# (no patient, no date), so they don't go through the two-table silver load like the studies; the import API
|
||||
# fills them until the `tea` library does. dbt reads them like the `oro` tables the Python cycle writes
|
||||
# (`_silver.yml`): as sources, and only the gold view on top of them reaches the WebApi.
|
||||
sources:
|
||||
- name: staging
|
||||
schema: "{{ target.schema }}"
|
||||
tables:
|
||||
- name: relacion_ados2
|
||||
- name: relacion_ados2_paciente
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user