Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f4864c1981 | |||
| 5fb2bc682a | |||
| 11dabc4714 | |||
| c67b52b828 | |||
| 3aec97a8b7 | |||
| f7faabf699 | |||
| 987efe54f8 | |||
| bcfd6aef07 | |||
| f13efbad67 |
@@ -14,3 +14,4 @@ dist/imagenes/
|
||||
dist/.env
|
||||
dist/datos/
|
||||
dist/*.tar.gz
|
||||
graphify-out/
|
||||
@@ -1,7 +1,7 @@
|
||||
from enum import Enum
|
||||
|
||||
class TipoEstudio(str, Enum):
|
||||
MASTOGRAFIA = "MASTOGRAFIA" # the study this domain orders (indicadores_kit cama)
|
||||
MASTOGRAFIA = "MASTOGRAFIA" # the study this domain orders
|
||||
BIOPSIA_CHICA = "BIOPSIA_CHICA"
|
||||
SOLICITUD_PAPANICOLAO_BASE_LIQUIDA = "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA"
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Catálogos de la plata (F1)
|
||||
|
||||
Un TOML por proyecto: estudio → resultado → valor.
|
||||
El paso `catalogos` de `webapi.orquestacion` los materializa en `cat_estudio`, `cat_resultado` y `cat_valor`
|
||||
El paso `catalogos` de `webapi.orchestration` los materializa en `cat_estudio`, `cat_resultado` y `cat_valor`
|
||||
(`core/indicadores/catalogos.py`) antes de cargar. Un valor que sale del TOML pasa a `retirado`; nunca se borra.
|
||||
|
||||
```toml
|
||||
@@ -19,5 +19,21 @@ valores = [ # solo codigo; el orden de la lista es el de
|
||||
]
|
||||
```
|
||||
|
||||
A result read from a document's text (a report's interpretation, a PDF's text layer, a note) also says how it's
|
||||
printed. These keys don't reach any table; the silver load reads them (`webapi.orchestration.silver.extracted`):
|
||||
|
||||
```toml
|
||||
[<estudio>.resultados.<resultado>]
|
||||
etiquetas_fuente = ["Densidad mamaria", "Densidad"] # the captions it's printed under
|
||||
buscar_en_texto = true # codigo only: also as a mention anywhere in the text
|
||||
provisional = true # captions and spellings not yet confirmed with the hospital's documents
|
||||
valores = [
|
||||
{ valor = "C", etiqueta = "Heterogéneamente densa", alias = ["Tipo C", "ACR C"] }, # each spelling of the value
|
||||
]
|
||||
```
|
||||
|
||||
A spelling with no alias is stored as `valor_fuente` without `valor_id` and counted as out of catalog; adding it
|
||||
as an alias and reloading turns it into the code. One spelling on two values of a result is rejected.
|
||||
|
||||
Los valores son los que llegan del hospital (los enums de Core). Las etiquetas y los colores de las figuras
|
||||
siguen en `parametros.toml` del kit hasta F3; `indicadores_kit/tests/test_catalogos.py` exige que coincidan.
|
||||
|
||||
@@ -30,6 +30,27 @@ valores = [
|
||||
{ valor = "B6", etiqueta = "BI-RADS 6" },
|
||||
]
|
||||
|
||||
# Read from the radiologist's interpretation (`mast_interpretacion`). Provisional: captions and spellings are
|
||||
# assumptions until the hospital's reports are seen; adding one is a line in `etiquetas_fuente` or `alias`.
|
||||
[mastografia.resultados.densidad]
|
||||
etiqueta = "Densidad mamaria (ACR)"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Densidad mamaria", "Densidad", "Composición mamaria", "Patrón mamario"]
|
||||
valores = [
|
||||
{ valor = "A", etiqueta = "Predominantemente grasa", alias = ["Tipo A", "ACR A", "Categoría A", "(A)", "Grasa"] },
|
||||
{ valor = "B", etiqueta = "Densidades fibroglandulares dispersas", alias = ["Tipo B", "ACR B", "Categoría B", "(B)", "Fibroglandular dispersa"] },
|
||||
{ valor = "C", etiqueta = "Heterogéneamente densa", alias = ["Tipo C", "ACR C", "Categoría C", "(C)", "Heterogéneamente densas"] },
|
||||
{ valor = "D", etiqueta = "Extremadamente densa", alias = ["Tipo D", "ACR D", "Categoría D", "(D)", "Extremadamente densas"] },
|
||||
]
|
||||
|
||||
[mastografia.resultados.tamano_lesion_mm]
|
||||
etiqueta = "Tamaño de la lesión"
|
||||
tipo_valor = "numero"
|
||||
unidad = "mm"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Tamaño de la lesión", "Tamaño del nódulo", "Diámetro mayor", "Mide"]
|
||||
|
||||
[biopsia]
|
||||
etiqueta = "Biopsia de mama"
|
||||
codigos_hospital = ["BIOPSIA_CHICA"]
|
||||
@@ -48,6 +69,85 @@ valores = [
|
||||
etiqueta = "Fecha de solicitud"
|
||||
tipo_valor = "fecha"
|
||||
|
||||
# Read from the pathology report's text layer (`bx_pdf_blob`). Provisional, as the mammography's.
|
||||
[biopsia.resultados.tipo_histologico]
|
||||
etiqueta = "Tipo histológico"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Tipo histológico", "Diagnóstico histopatológico", "Diagnóstico"]
|
||||
buscar_en_texto = true
|
||||
valores = [
|
||||
{ valor = "DUCTAL_INFILTRANTE", etiqueta = "Carcinoma ductal infiltrante", alias = ["Ductal infiltrante", "Carcinoma ductal invasor", "Carcinoma infiltrante de tipo no especial", "CDI"] },
|
||||
{ valor = "LOBULILLAR_INFILTRANTE", etiqueta = "Carcinoma lobulillar infiltrante", alias = ["Lobulillar infiltrante", "Carcinoma lobulillar invasor", "CLI"] },
|
||||
{ valor = "DUCTAL_IN_SITU", etiqueta = "Carcinoma ductal in situ", alias = ["Ductal in situ", "CDIS"] },
|
||||
{ valor = "OTRO", etiqueta = "Otro tipo histológico" },
|
||||
]
|
||||
|
||||
[biopsia.resultados.grado_nottingham]
|
||||
etiqueta = "Grado histológico (Nottingham)"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Grado histológico", "Grado de Nottingham", "Grado Scarff-Bloom-Richardson", "SBR"]
|
||||
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"] },
|
||||
]
|
||||
|
||||
[biopsia.resultados.receptor_estrogeno]
|
||||
etiqueta = "Receptor de estrógeno"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Receptores de estrógeno", "Receptor de estrógenos", "Receptores estrogénicos", "RE", "ER"]
|
||||
valores = [
|
||||
{ valor = "POSITIVO", etiqueta = "Positivo", alias = ["Pos", "+"] },
|
||||
{ valor = "NEGATIVO", etiqueta = "Negativo", alias = ["Neg", "-"] },
|
||||
]
|
||||
|
||||
[biopsia.resultados.receptor_estrogeno_pct]
|
||||
etiqueta = "Receptor de estrógeno, células teñidas"
|
||||
tipo_valor = "numero"
|
||||
unidad = "%"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Receptores de estrógeno", "Receptor de estrógenos", "Receptores estrogénicos", "RE", "ER"]
|
||||
|
||||
[biopsia.resultados.receptor_progesterona]
|
||||
etiqueta = "Receptor de progesterona"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Receptores de progesterona", "Receptor de progesterona", "Receptores progestágenos", "RP", "PR"]
|
||||
valores = [
|
||||
{ valor = "POSITIVO", etiqueta = "Positivo", alias = ["Pos", "+"] },
|
||||
{ valor = "NEGATIVO", etiqueta = "Negativo", alias = ["Neg", "-"] },
|
||||
]
|
||||
|
||||
[biopsia.resultados.receptor_progesterona_pct]
|
||||
etiqueta = "Receptor de progesterona, células teñidas"
|
||||
tipo_valor = "numero"
|
||||
unidad = "%"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Receptores de progesterona", "Receptor de progesterona", "Receptores progestágenos", "RP", "PR"]
|
||||
|
||||
# A bare "positivo" is left unmatched on purpose: it doesn't say whether it's 3+ or an amplified 2+.
|
||||
[biopsia.resultados.her2]
|
||||
etiqueta = "HER2 (inmunohistoquímica)"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["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+"] },
|
||||
{ valor = "H2", etiqueta = "2+", alias = ["2+", "Equívoco", "Indeterminado", "Score 2+"] },
|
||||
{ valor = "H3", etiqueta = "3+", alias = ["3+", "Positivo (3+)", "Score 3+"] },
|
||||
]
|
||||
|
||||
[biopsia.resultados.ki67_pct]
|
||||
etiqueta = "Ki-67"
|
||||
tipo_valor = "numero"
|
||||
unidad = "%"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Ki-67", "Ki67", "Índice de proliferación"]
|
||||
|
||||
[nota_medica]
|
||||
etiqueta = "Nota médica"
|
||||
|
||||
@@ -56,6 +156,25 @@ etiqueta = "Diagnóstico"
|
||||
tipo_valor = "externo"
|
||||
sistema = "CIE-10"
|
||||
|
||||
# Read from the note's diagnosis and prognosis texts. Provisional; a stage mentioned without a caption counts too
|
||||
# ("... estadio clínico IIA (T2N0M0)").
|
||||
[nota_medica.resultados.estadio_clinico]
|
||||
etiqueta = "Estadio clínico"
|
||||
tipo_valor = "codigo"
|
||||
provisional = true
|
||||
etiquetas_fuente = ["Estadio clínico", "Etapa clínica", "Estadio", "EC"]
|
||||
buscar_en_texto = true
|
||||
valores = [
|
||||
{ valor = "E0", etiqueta = "Estadio 0", alias = ["EC 0", "Etapa 0", "In situ", "Estadio clínico 0", "Etapa clínica 0"] },
|
||||
{ valor = "EI", etiqueta = "Estadio I", alias = ["I", "IA", "IB", "EC I", "EC IA", "EC IB", "Estadio IA", "Estadio IB", "Etapa I", "Estadio clínico I", "Etapa clínica I", "Estadio clínico IA", "Estadio clínico IB"] },
|
||||
{ valor = "EIIA", etiqueta = "Estadio IIA", alias = ["IIA", "EC IIA", "Etapa IIA", "Estadio clínico IIA", "Etapa clínica IIA"] },
|
||||
{ valor = "EIIB", etiqueta = "Estadio IIB", alias = ["IIB", "EC IIB", "Etapa IIB", "Estadio clínico IIB", "Etapa clínica IIB"] },
|
||||
{ valor = "EIIIA", etiqueta = "Estadio IIIA", alias = ["IIIA", "EC IIIA", "Etapa IIIA", "Estadio clínico IIIA", "Etapa clínica IIIA"] },
|
||||
{ valor = "EIIIB", etiqueta = "Estadio IIIB", alias = ["IIIB", "EC IIIB", "Etapa IIIB", "Estadio clínico IIIB", "Etapa clínica IIIB"] },
|
||||
{ valor = "EIIIC", etiqueta = "Estadio IIIC", alias = ["IIIC", "EC IIIC", "Etapa IIIC", "Estadio clínico IIIC", "Etapa clínica IIIC"] },
|
||||
{ valor = "EIV", etiqueta = "Estadio IV", alias = ["IV", "EC IV", "Etapa IV", "Metastásico", "Estadio clínico IV", "Etapa clínica IV"] },
|
||||
]
|
||||
|
||||
[nota_medica.resultados.especialidad]
|
||||
etiqueta = "Especialidad que la escribe"
|
||||
tipo_valor = "codigo"
|
||||
|
||||
+228
-219
@@ -1,267 +1,276 @@
|
||||
# Catálogo de TEA (F1). Valores: los enums de Core (`core/tea/enums.py`) y lo que guarda la carga.
|
||||
# Los instrumentos aplicados (M-CHAT-R/F, Ramos) son un estudio cada uno: una aplicación por informante y área.
|
||||
# TEA's catalog: the studies of the screening (M-CHAT, ADOS-2, neuropediatrics note, EEG) and their results.
|
||||
# Values are Core's enums (`core/tea/enums.py`). `codigos_hospital` are the codes of `ord_tipo_estudio`: an order's
|
||||
# `estudio_id` is the study it asks for.
|
||||
|
||||
[evaluacion_psicologica]
|
||||
etiqueta = "Evaluación psicológica"
|
||||
codigos_hospital = ["EVALUACION_PSICOLOGICA_TEA"]
|
||||
[mchat]
|
||||
etiqueta = "M-CHAT-R/F"
|
||||
|
||||
[evaluacion_psicologica.resultados.instrumento_tamizaje]
|
||||
etiqueta = "Instrumento de tamizaje"
|
||||
[mchat.resultados.puntaje]
|
||||
etiqueta = "Puntaje total"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
# The ADOS-2: module, algorithm, classification, CSS and the algorithm items. An item's domain is its prefix:
|
||||
# `sa_` social affect, `rrb_` restricted and repetitive behaviour. Labels of the items without a published short name
|
||||
# wait for the hospital's manuals.
|
||||
[ados2]
|
||||
etiqueta = "Evaluación psicológica (ADOS-2)"
|
||||
codigos_hospital = ["ADOS2"]
|
||||
|
||||
[ados2.resultados.modulo]
|
||||
etiqueta = "Módulo"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "M_CHAT_R", etiqueta = "M-CHAT-R" },
|
||||
{ valor = "M_CHAT_RF", etiqueta = "M-CHAT-R/F" },
|
||||
{ valor = "OTRO", etiqueta = "Otro" },
|
||||
{ valor = "NO_REGISTRADO", etiqueta = "No registrado" },
|
||||
{ valor = "TODDLER", etiqueta = "Módulo T (niños pequeños)" },
|
||||
{ valor = "MODULO_1", etiqueta = "Módulo 1" },
|
||||
{ valor = "MODULO_2", etiqueta = "Módulo 2" },
|
||||
{ valor = "MODULO_3", etiqueta = "Módulo 3" },
|
||||
]
|
||||
|
||||
[evaluacion_psicologica.resultados.edad_meses]
|
||||
etiqueta = "Edad del niño"
|
||||
tipo_valor = "numero"
|
||||
unidad = "meses"
|
||||
[ados2.resultados.algoritmo]
|
||||
etiqueta = "Algoritmo"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[evaluacion_psicologica.resultados.fecha_evaluacion]
|
||||
etiqueta = "Fecha de la evaluación"
|
||||
tipo_valor = "fecha"
|
||||
|
||||
[evaluacion_psicologica.resultados.fecha_entrevista_inicial]
|
||||
etiqueta = "Fecha de la entrevista inicial"
|
||||
tipo_valor = "fecha"
|
||||
|
||||
[ados2]
|
||||
etiqueta = "ADOS-2"
|
||||
[ados2.resultados.clasificacion]
|
||||
etiqueta = "Clasificación"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "NO_ESPECTRO", etiqueta = "No espectro" },
|
||||
{ valor = "ESPECTRO_AUTISTA", etiqueta = "Espectro autista" },
|
||||
{ valor = "AUTISMO", etiqueta = "Autismo" },
|
||||
{ valor = "PREOCUPACION_LEVE_MODERADA", etiqueta = "Preocupación leve a moderada" },
|
||||
{ valor = "PREOCUPACION_SEVERA", etiqueta = "Preocupación moderada a severa" },
|
||||
]
|
||||
|
||||
[ados2.resultados.css]
|
||||
etiqueta = "Puntaje de severidad (CSS)"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[mchat]
|
||||
etiqueta = "M-CHAT-R/F aplicado"
|
||||
codigos_hospital = ["M_CHAT_R_F"]
|
||||
|
||||
[mchat.resultados.informante]
|
||||
etiqueta = "Informante"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "MADRE", etiqueta = "Madre" },
|
||||
{ valor = "PADRE", etiqueta = "Padre" },
|
||||
{ valor = "OTRO_CUIDADOR", etiqueta = "Otro cuidador" },
|
||||
{ valor = "MAESTRO", etiqueta = "Maestro" },
|
||||
{ valor = "OBSERVACION_CLINICA", etiqueta = "Observación clínica" },
|
||||
{ valor = "NO_REGISTRADO", etiqueta = "No registrado" },
|
||||
]
|
||||
|
||||
[mchat.resultados.area]
|
||||
etiqueta = "Área"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "TOTAL", etiqueta = "Total" },
|
||||
]
|
||||
|
||||
[mchat.resultados.interpretacion]
|
||||
etiqueta = "Interpretación"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "RIESGO_BAJO", etiqueta = "Riesgo bajo" },
|
||||
{ valor = "RIESGO_MEDIO", etiqueta = "Riesgo medio" },
|
||||
{ valor = "RIESGO_ALTO", etiqueta = "Riesgo alto" },
|
||||
]
|
||||
|
||||
[ramos]
|
||||
etiqueta = "Escala de Ramos aplicada"
|
||||
codigos_hospital = ["RAMOS"]
|
||||
|
||||
[ramos.resultados.informante]
|
||||
etiqueta = "Informante"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "MADRE", etiqueta = "Madre" },
|
||||
{ valor = "PADRE", etiqueta = "Padre" },
|
||||
{ valor = "OTRO_CUIDADOR", etiqueta = "Otro cuidador" },
|
||||
{ valor = "MAESTRO", etiqueta = "Maestro" },
|
||||
{ valor = "OBSERVACION_CLINICA", etiqueta = "Observación clínica" },
|
||||
{ valor = "NO_REGISTRADO", etiqueta = "No registrado" },
|
||||
]
|
||||
|
||||
[ramos.resultados.area]
|
||||
etiqueta = "Área"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "ADAPTATIVO", etiqueta = "Adaptativo" },
|
||||
{ valor = "COGNOSCITIVO", etiqueta = "Cognoscitivo" },
|
||||
{ valor = "FISICO", etiqueta = "Físico" },
|
||||
{ valor = "LINGUISTICO", etiqueta = "Lingüístico" },
|
||||
{ valor = "SOCIOEMOCIONAL", etiqueta = "Socioemocional" },
|
||||
{ valor = "TOTAL", etiqueta = "Total" },
|
||||
]
|
||||
|
||||
[ramos.resultados.interpretacion]
|
||||
etiqueta = "Interpretación"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "DESARROLLO_ADECUADO", etiqueta = "Desarrollo adecuado" },
|
||||
{ valor = "MONITOREO", etiqueta = "Monitoreo" },
|
||||
{ valor = "RETRASO", etiqueta = "Retraso" },
|
||||
]
|
||||
|
||||
[eeg]
|
||||
etiqueta = "Electroencefalograma"
|
||||
codigos_hospital = ["ELECTROENCEFALOGRAMA"]
|
||||
|
||||
[eeg.resultados.duracion_min]
|
||||
etiqueta = "Duración"
|
||||
tipo_valor = "numero"
|
||||
unidad = "min"
|
||||
|
||||
[eeg.resultados.utilizable]
|
||||
etiqueta = "Utilizable"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.fecha_nacimiento_archivo]
|
||||
etiqueta = "Fecha de nacimiento en el archivo del equipo"
|
||||
tipo_valor = "fecha"
|
||||
|
||||
# Un segmento es una parte del EEG (procedimiento con clase `parte`).
|
||||
[eeg.resultados.estado_segmento]
|
||||
etiqueta = "Estado del segmento"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "NO_MARCADO", etiqueta = "No marcado" },
|
||||
{ valor = "OJOS_CERRADOS", etiqueta = "Ojos cerrados" },
|
||||
{ valor = "FOTOESTIMULACION", etiqueta = "Fotoestimulación" },
|
||||
{ valor = "SUENO", etiqueta = "Sueño" },
|
||||
]
|
||||
|
||||
[eeg.resultados.duracion_segmento]
|
||||
etiqueta = "Duración del segmento"
|
||||
tipo_valor = "numero"
|
||||
unidad = "s"
|
||||
|
||||
[pea]
|
||||
etiqueta = "Potenciales evocados auditivos"
|
||||
codigos_hospital = ["POTENCIALES_EVOCADOS_AUDITIVOS", "POTENCIALES_EVOCADOS"] # el segundo, como llega (responsable de TEA, 2026-10-21)
|
||||
|
||||
[pea.resultados.grado_hipoacusia]
|
||||
etiqueta = "Grado de hipoacusia"
|
||||
tipo_valor = "codigo"
|
||||
valores = [
|
||||
{ valor = "NORMAL", etiqueta = "Normal" },
|
||||
{ valor = "LEVE", etiqueta = "Leve" },
|
||||
{ valor = "MODERADA", etiqueta = "Moderada" },
|
||||
{ valor = "SEVERA", etiqueta = "Severa" },
|
||||
{ valor = "PROFUNDA", etiqueta = "Profunda" },
|
||||
{ valor = "NO_CONCLUYENTE", etiqueta = "No concluyente" },
|
||||
]
|
||||
|
||||
[parto]
|
||||
etiqueta = "Parto"
|
||||
|
||||
[parto.resultados.apgar_5min]
|
||||
etiqueta = "APGAR a los 5 minutos"
|
||||
[ados2.resultados.sa_a2]
|
||||
etiqueta = "Frecuencia de la vocalización espontánea dirigida a otros"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[parto.resultados.ingreso_ucin]
|
||||
etiqueta = "Ingreso a UCIN"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_a6]
|
||||
etiqueta = "Uso del cuerpo de otra persona para comunicarse"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal]
|
||||
etiqueta = "Antecedentes maternos de la gestación"
|
||||
[ados2.resultados.sa_a7]
|
||||
etiqueta = "Señalar"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.antecedente_aborto]
|
||||
etiqueta = "Antecedente de aborto"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_a8]
|
||||
etiqueta = "Gestos"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.asma]
|
||||
etiqueta = "Asma"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b1]
|
||||
etiqueta = "Contacto visual inusual"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.crisis_convulsivas]
|
||||
etiqueta = "Crisis convulsivas"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b2]
|
||||
etiqueta = "Sonrisa social en respuesta"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.diabetes_gestacional]
|
||||
etiqueta = "Diabetes gestacional"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b3]
|
||||
etiqueta = "Expresiones faciales dirigidas a otros"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.embarazo_multiple]
|
||||
etiqueta = "Embarazo múltiple"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b4]
|
||||
etiqueta = "Integración de la mirada y otras conductas en las iniciaciones sociales"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.enfermedad_autoinmune]
|
||||
etiqueta = "Enfermedad autoinmune"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b5]
|
||||
etiqueta = "Placer compartido durante la interacción"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.estres_agudo]
|
||||
etiqueta = "Estrés agudo"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b6]
|
||||
etiqueta = "Respuesta al nombre"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.farmaco_riesgo_neurodesarrollo]
|
||||
etiqueta = "Fármaco de riesgo para el neurodesarrollo"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b7]
|
||||
etiqueta = "Pedir"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.hipertension_preeclampsia]
|
||||
etiqueta = "Hipertensión o preeclampsia"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b8]
|
||||
etiqueta = "Dar"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.hipertiroidismo]
|
||||
etiqueta = "Hipertiroidismo"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b9]
|
||||
etiqueta = "Mostrar"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.hipotiroidismo]
|
||||
etiqueta = "Hipotiroidismo"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b10]
|
||||
etiqueta = "Iniciación espontánea de la atención conjunta"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.hipoxia_materna]
|
||||
etiqueta = "Hipoxia materna"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b11]
|
||||
etiqueta = "Respuesta a la atención conjunta"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.incompatibilidad_rh]
|
||||
etiqueta = "Incompatibilidad Rh"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b12]
|
||||
etiqueta = "Calidad de los acercamientos sociales"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.infeccion_gestacion]
|
||||
etiqueta = "Infección en la gestación"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b13]
|
||||
etiqueta = "Reactivo B13"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.liquido_amniotico]
|
||||
etiqueta = "Alteración del líquido amniótico"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b14]
|
||||
etiqueta = "Reactivo B14"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.migrana]
|
||||
etiqueta = "Migraña"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b15]
|
||||
etiqueta = "Reactivo B15"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.proceso_proinflamatorio]
|
||||
etiqueta = "Proceso proinflamatorio"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b16b]
|
||||
etiqueta = "Reactivo B16b"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.tabaquismo_gestacion]
|
||||
etiqueta = "Tabaquismo en la gestación"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.sa_b18]
|
||||
etiqueta = "Reactivo B18"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[historia_perinatal.resultados.trastorno_neurologico]
|
||||
etiqueta = "Trastorno neurológico"
|
||||
tipo_valor = "booleano"
|
||||
[ados2.resultados.rrb_a3]
|
||||
etiqueta = "Entonación de las vocalizaciones o verbalizaciones"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[nota_medica]
|
||||
etiqueta = "Nota médica"
|
||||
[ados2.resultados.rrb_a4]
|
||||
etiqueta = "Ecolalia inmediata"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[nota_medica.resultados.diagnostico]
|
||||
[ados2.resultados.rrb_a5]
|
||||
etiqueta = "Uso estereotipado o idiosincrásico de palabras o frases"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[ados2.resultados.rrb_d1]
|
||||
etiqueta = "Interés sensorial inusual en los materiales de juego o en las personas"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[ados2.resultados.rrb_d2]
|
||||
etiqueta = "Manierismos de manos, dedos y otros manierismos complejos"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[ados2.resultados.rrb_d4]
|
||||
etiqueta = "Intereses inusualmente repetitivos o conductas estereotipadas"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[ados2.resultados.rrb_d5]
|
||||
etiqueta = "Reactivo D5"
|
||||
tipo_valor = "numero"
|
||||
unidad = "puntos"
|
||||
|
||||
[evaluacion_neuropediatrica]
|
||||
etiqueta = "Evaluación neuropediátrica"
|
||||
codigos_hospital = ["NEUROPEDIATRIA"]
|
||||
|
||||
[evaluacion_neuropediatrica.resultados.diagnostico]
|
||||
etiqueta = "Diagnóstico"
|
||||
tipo_valor = "externo"
|
||||
sistema = "CIE-10"
|
||||
|
||||
# Los datos de una orden (procedimiento con clase `orden`; su `estudio_id` es el estudio pedido, de
|
||||
# `codigos_hospital`). ADR-MD-007.
|
||||
# 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.
|
||||
[eeg]
|
||||
etiqueta = "Electroencefalograma"
|
||||
codigos_hospital = ["EEG"]
|
||||
|
||||
[eeg.resultados.con_sueno]
|
||||
etiqueta = "Registro con sueño"
|
||||
tipo_valor = "booleano"
|
||||
|
||||
[eeg.resultados.canales]
|
||||
etiqueta = "Canales"
|
||||
tipo_valor = "numero"
|
||||
unidad = "canales"
|
||||
|
||||
[eeg.resultados.duracion_min]
|
||||
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]
|
||||
etiqueta = "Ruido de la línea eléctrica"
|
||||
tipo_valor = "numero"
|
||||
unidad = "dB"
|
||||
|
||||
[eeg.resultados.ritmo_posterior]
|
||||
etiqueta = "Ritmo posterior"
|
||||
tipo_valor = "numero"
|
||||
unidad = "Hz"
|
||||
|
||||
[eeg.resultados.husos_sueno_n2]
|
||||
etiqueta = "Husos de sueño N2"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.husos_sueno_n3]
|
||||
etiqueta = "Husos de sueño N3"
|
||||
tipo_valor = "numero"
|
||||
unidad = "husos/min"
|
||||
|
||||
[eeg.resultados.picos_paroxisticos]
|
||||
etiqueta = "Picos paroxísticos"
|
||||
tipo_valor = "numero"
|
||||
unidad = "picos/min"
|
||||
|
||||
[eeg.resultados.gradiente_anteroposterior]
|
||||
etiqueta = "Gradiente anteroposterior"
|
||||
tipo_valor = "numero"
|
||||
unidad = "razón posterior/anterior"
|
||||
|
||||
# An order (procedure of class `orden`): its `estudio_id` is the study it asks for, from `codigos_hospital`.
|
||||
[orden]
|
||||
etiqueta = "Orden de estudio"
|
||||
|
||||
[orden.resultados.intencion]
|
||||
etiqueta = "Intención (FHIR intent)"
|
||||
tipo_valor = "texto"
|
||||
|
||||
[orden.resultados.fecha_realizacion]
|
||||
etiqueta = "Fecha de realización"
|
||||
tipo_valor = "fecha"
|
||||
|
||||
@@ -130,7 +130,7 @@ def evaluacion_unica() -> UniqueConstraint:
|
||||
class TablasCohorte:
|
||||
"""Las seis tablas de cohortes y riesgos de un dominio, juntas (como `TablasKit` del kit).
|
||||
|
||||
Las declara cada proyecto (`indicadores_kit.<proyecto>.tablas.COHORTES`); el kit las lee
|
||||
Las declara cada proyecto (`webapi.orchestration.tables.<proyecto>.COHORTES`); el ciclo las lee
|
||||
y Persistance las escribe.
|
||||
"""
|
||||
|
||||
|
||||
+31
-297
@@ -1,327 +1,61 @@
|
||||
"""Vocabularios controlados del proyecto TEA.
|
||||
"""Controlled vocabularies of TEA's staging (spec/tablas_TEA.md).
|
||||
|
||||
Capa Core: sin importaciones de infraestructura. Seguro de importar
|
||||
desde cualquier módulo de src/.
|
||||
|
||||
Generado desde spec/tablas_TEA.md. No editar a mano.
|
||||
Core layer: no infrastructure imports.
|
||||
"""
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class Parentesco(str, Enum):
|
||||
"""pac_parentesco in table pacientes."""
|
||||
HIJO = "HIJO"
|
||||
HIJA = "HIJA"
|
||||
HIJASTRO = "HIJASTRO"
|
||||
TUTELADO = "TUTELADO"
|
||||
OTRO = "OTRO"
|
||||
|
||||
|
||||
class SexoBiologico(str, Enum):
|
||||
"""pac_sexo in table pacientes."""
|
||||
F = "F"
|
||||
M = "M"
|
||||
I = "I"
|
||||
|
||||
|
||||
class Especialidad(str, Enum):
|
||||
"""ord_especialidad in table ordenes_estudio."""
|
||||
NEUROLOGIA_PEDIATRICA = "NEUROLOGIA_PEDIATRICA"
|
||||
PEDIATRIA = "PEDIATRIA"
|
||||
PSICOLOGIA = "PSICOLOGIA"
|
||||
PSIQUIATRIA_INFANTIL = "PSIQUIATRIA_INFANTIL"
|
||||
AUDIOLOGIA = "AUDIOLOGIA"
|
||||
MEDICINA_FAMILIAR = "MEDICINA_FAMILIAR"
|
||||
ENFERMERIA = "ENFERMERIA"
|
||||
OTRO = "OTRO"
|
||||
|
||||
|
||||
class TipoEstudio(str, Enum):
|
||||
"""ord_tipo_estudio in table ordenes_estudio."""
|
||||
ELECTROENCEFALOGRAMA = "ELECTROENCEFALOGRAMA"
|
||||
POTENCIALES_EVOCADOS_AUDITIVOS = "POTENCIALES_EVOCADOS_AUDITIVOS"
|
||||
EVALUACION_PSICOLOGICA_TEA = "EVALUACION_PSICOLOGICA_TEA"
|
||||
OTRO = "OTRO"
|
||||
ADOS2 = "ADOS2"
|
||||
NEUROPEDIATRIA = "NEUROPEDIATRIA"
|
||||
EEG = "EEG"
|
||||
|
||||
|
||||
# How the hospital writes each study, normalized (upper case, without accents) before it is looked up.
|
||||
TIPO_ESTUDIO_ALIAS: dict[str, str] = {
|
||||
"POTENCIALES_EVOCADOS": "POTENCIALES_EVOCADOS_AUDITIVOS",
|
||||
"POTENCIALES EVOCADOS": "POTENCIALES_EVOCADOS_AUDITIVOS",
|
||||
"POTENCIALES EVOCADOS AUDITIVOS": "POTENCIALES_EVOCADOS_AUDITIVOS",
|
||||
"EVALUACION PSICOLOGICA TEA": "EVALUACION_PSICOLOGICA_TEA",
|
||||
"EEG": "ELECTROENCEFALOGRAMA",
|
||||
"ADOS-2": "ADOS2",
|
||||
"ADOS 2": "ADOS2",
|
||||
"EVALUACION PSICOLOGICA": "ADOS2",
|
||||
"EVALUACION_PSICOLOGICA_TEA": "ADOS2",
|
||||
"NEUROLOGIA PEDIATRICA": "NEUROPEDIATRIA",
|
||||
"NEUROLOGIA_PEDIATRICA": "NEUROPEDIATRIA",
|
||||
"EVALUACION NEUROPEDIATRICA": "NEUROPEDIATRIA",
|
||||
"ELECTROENCEFALOGRAMA": "EEG",
|
||||
}
|
||||
|
||||
|
||||
class EstatusEstudio(str, Enum):
|
||||
"""ord_estatus in table ordenes_estudio."""
|
||||
SOLICITADO = "SOLICITADO"
|
||||
EN_PROCESO = "EN_PROCESO"
|
||||
REALIZADO = "REALIZADO"
|
||||
RESULTADO_DISPONIBLE = "RESULTADO_DISPONIBLE"
|
||||
CANCELADO = "CANCELADO"
|
||||
NO_ACUDIO = "NO_ACUDIO"
|
||||
|
||||
|
||||
class VentanaMadurativa(str, Enum):
|
||||
"""ord_ventana_madurativa in table ordenes_estudio."""
|
||||
V1_16_23 = "V1_16_23"
|
||||
V2_24_30 = "V2_24_30"
|
||||
V3_31_36 = "V3_31_36"
|
||||
FUERA_DE_RANGO = "FUERA_DE_RANGO"
|
||||
|
||||
|
||||
class TipoNota(str, Enum):
|
||||
"""nm_tipo_nota in table nota_medica."""
|
||||
PRIMERA_VEZ = "PRIMERA_VEZ"
|
||||
TAMIZAJE = "TAMIZAJE"
|
||||
INTERPRETACION_EEG = "INTERPRETACION_EEG"
|
||||
TRATAMIENTO = "TRATAMIENTO"
|
||||
SEGUIMIENTO = "SEGUIMIENTO"
|
||||
INTERCONSULTA = "INTERCONSULTA"
|
||||
URGENCIA = "URGENCIA"
|
||||
OTRO = "OTRO"
|
||||
|
||||
|
||||
class Pronostico(str, Enum):
|
||||
"""nm_pronostico in table nota_medica."""
|
||||
BUENO = "BUENO"
|
||||
RESERVADO = "RESERVADO"
|
||||
MALO = "MALO"
|
||||
NO_ESPECIFICADO = "NO_ESPECIFICADO"
|
||||
|
||||
|
||||
class InstrumentoTamizaje(str, Enum):
|
||||
"""psi_instrumento_tamizaje in table evaluacion_psicologica."""
|
||||
M_CHAT_R = "M_CHAT_R"
|
||||
M_CHAT_RF = "M_CHAT_RF"
|
||||
OTRO = "OTRO"
|
||||
NO_REGISTRADO = "NO_REGISTRADO"
|
||||
|
||||
|
||||
class NivelRiesgoTamizaje(str, Enum):
|
||||
"""psi_tamizaje_riesgo in table evaluacion_psicologica."""
|
||||
BAJO = "BAJO"
|
||||
MEDIO = "MEDIO"
|
||||
ALTO = "ALTO"
|
||||
NO_APLICA = "NO_APLICA"
|
||||
|
||||
|
||||
class ModuloAdos2(str, Enum):
|
||||
"""psi_ados2_modulo in table evaluacion_psicologica."""
|
||||
"""ado_modulo in table ados2."""
|
||||
TODDLER = "TODDLER"
|
||||
MODULO_1 = "MODULO_1"
|
||||
MODULO_2 = "MODULO_2"
|
||||
NO_REGISTRADO = "NO_REGISTRADO"
|
||||
MODULO_3 = "MODULO_3"
|
||||
|
||||
|
||||
class ClasificacionAdos2(str, Enum):
|
||||
"""psi_ados2_clasificacion in table evaluacion_psicologica."""
|
||||
NO_TEA = "NO_TEA"
|
||||
"""ado_clasificacion in table ados2."""
|
||||
NO_ESPECTRO = "NO_ESPECTRO"
|
||||
ESPECTRO_AUTISTA = "ESPECTRO_AUTISTA"
|
||||
AUTISMO = "AUTISMO"
|
||||
PREOCUPACION_LEVE_MODERADA = "PREOCUPACION_LEVE_MODERADA"
|
||||
PREOCUPACION_SEVERA = "PREOCUPACION_SEVERA"
|
||||
|
||||
|
||||
class GradoHipoacusia(str, Enum):
|
||||
"""pea_grado_hipoacusia in table potenciales_evocados_auditivos."""
|
||||
NORMAL = "NORMAL"
|
||||
LEVE = "LEVE"
|
||||
MODERADA = "MODERADA"
|
||||
SEVERA = "SEVERA"
|
||||
PROFUNDA = "PROFUNDA"
|
||||
NO_CONCLUYENTE = "NO_CONCLUYENTE"
|
||||
CLASIFICACION_ADOS2_ALIAS: dict[str, str] = {"NO_TEA": "NO_ESPECTRO", "NO ESPECTRO": "NO_ESPECTRO"}
|
||||
|
||||
|
||||
class ClasificacionEeg(str, Enum):
|
||||
"""eeg_clasificacion in table eeg_estudio."""
|
||||
SIN_REFERENCIA_AURICULAR = "SIN_REFERENCIA_AURICULAR"
|
||||
class MetricaEeg(str, Enum):
|
||||
"""met_codigo in table eeg_metrica."""
|
||||
RITMO_POSTERIOR = "RITMO_POSTERIOR"
|
||||
HUSOS_SUENO_N2 = "HUSOS_SUENO_N2"
|
||||
HUSOS_SUENO_N3 = "HUSOS_SUENO_N3"
|
||||
PICOS_PAROXISTICOS = "PICOS_PAROXISTICOS"
|
||||
GRADIENTE_ANTEROPOSTERIOR = "GRADIENTE_ANTEROPOSTERIOR"
|
||||
|
||||
|
||||
class EstadoSegmentoEeg(str, Enum):
|
||||
"""seg_estado in table eeg_segmento."""
|
||||
NO_MARCADO = "NO_MARCADO"
|
||||
OJOS_CERRADOS = "OJOS_CERRADOS"
|
||||
FOTOESTIMULACION = "FOTOESTIMULACION"
|
||||
SUENO = "SUENO"
|
||||
|
||||
|
||||
class FuenteSegmentoEeg(str, Enum):
|
||||
"""seg_fuente in table eeg_segmento."""
|
||||
SIN_ANOTACION = "SIN_ANOTACION"
|
||||
ANOTACION_TECNICO = "ANOTACION_TECNICO"
|
||||
TRIGGER_EQUIPO = "TRIGGER_EQUIPO"
|
||||
|
||||
|
||||
class FuenteInterpretacionEeg(str, Enum):
|
||||
"""eeg_fuente_interpretacion in table eeg_estudio."""
|
||||
REPORTE_NEUROPEDIATRIA = "REPORTE_NEUROPEDIATRIA"
|
||||
NOTA_MEDICA = "NOTA_MEDICA"
|
||||
AMBAS = "AMBAS"
|
||||
NINGUNA = "NINGUNA"
|
||||
|
||||
|
||||
class EstadoRegistroEeg(str, Enum):
|
||||
"""eeg_estado_registro in table eeg_estudio."""
|
||||
VIGILIA = "VIGILIA"
|
||||
SUENO_ESPONTANEO = "SUENO_ESPONTANEO"
|
||||
SUENO_INDUCIDO = "SUENO_INDUCIDO"
|
||||
MIXTO = "MIXTO"
|
||||
NO_ESPECIFICADO = "NO_ESPECIFICADO"
|
||||
|
||||
|
||||
class CalidadTecnicaEeg(str, Enum):
|
||||
"""eeg_calidad_tecnica in table eeg_estudio."""
|
||||
SATISFACTORIA = "SATISFACTORIA"
|
||||
LIMITADA_POR_ARTEFACTO = "LIMITADA_POR_ARTEFACTO"
|
||||
LIMITADA_POR_COLABORACION = "LIMITADA_POR_COLABORACION"
|
||||
NO_VALORABLE = "NO_VALORABLE"
|
||||
NO_ESPECIFICADA = "NO_ESPECIFICADA"
|
||||
|
||||
|
||||
class Simetria(str, Enum):
|
||||
"""eeg_simetria in table eeg_estudio."""
|
||||
SIMETRICO = "SIMETRICO"
|
||||
ASIMETRICO_IZQUIERDO = "ASIMETRICO_IZQUIERDO"
|
||||
ASIMETRICO_DERECHO = "ASIMETRICO_DERECHO"
|
||||
NO_ESPECIFICADA = "NO_ESPECIFICADA"
|
||||
|
||||
|
||||
class TipoGrafoelemento(str, Enum):
|
||||
"""eeg_tipo_grafoelemento in table eeg_estudio."""
|
||||
NINGUNO = "NINGUNO"
|
||||
ESPIGA = "ESPIGA"
|
||||
ONDA_AGUDA = "ONDA_AGUDA"
|
||||
COMPLEJO_ESPIGA_ONDA = "COMPLEJO_ESPIGA_ONDA"
|
||||
COMPLEJO_POLIESPIGA_ONDA = "COMPLEJO_POLIESPIGA_ONDA"
|
||||
PUNTA_ONDA_LENTA = "PUNTA_ONDA_LENTA"
|
||||
DESCARGA_RITMICA = "DESCARGA_RITMICA"
|
||||
OTRO = "OTRO"
|
||||
|
||||
|
||||
class DistribucionAnormalidad(str, Enum):
|
||||
"""eeg_distribucion_anormalidad in table eeg_estudio."""
|
||||
FOCAL = "FOCAL"
|
||||
MULTIFOCAL = "MULTIFOCAL"
|
||||
GENERALIZADA = "GENERALIZADA"
|
||||
LATERALIZADA = "LATERALIZADA"
|
||||
NO_ESPECIFICADA = "NO_ESPECIFICADA"
|
||||
|
||||
|
||||
class Lentificacion(str, Enum):
|
||||
"""eeg_lentificacion in table eeg_estudio."""
|
||||
NINGUNA = "NINGUNA"
|
||||
FOCAL = "FOCAL"
|
||||
GENERALIZADA = "GENERALIZADA"
|
||||
INTERMITENTE = "INTERMITENTE"
|
||||
|
||||
|
||||
class RespuestaFotoestimulacion(str, Enum):
|
||||
"""eeg_respuesta_fotoestimulacion in table eeg_estudio."""
|
||||
NORMAL = "NORMAL"
|
||||
RESPUESTA_FOTOPAROXISTICA = "RESPUESTA_FOTOPAROXISTICA"
|
||||
SIN_RESPUESTA = "SIN_RESPUESTA"
|
||||
NO_PRACTICADA = "NO_PRACTICADA"
|
||||
|
||||
|
||||
class ConclusionEeg(str, Enum):
|
||||
"""eeg_conclusion_categoria in table eeg_estudio."""
|
||||
NORMAL_PARA_LA_EDAD = "NORMAL_PARA_LA_EDAD"
|
||||
NORMAL_CON_VARIANTES = "NORMAL_CON_VARIANTES"
|
||||
ANORMAL_EPILEPTIFORME = "ANORMAL_EPILEPTIFORME"
|
||||
ANORMAL_NO_EPILEPTIFORME = "ANORMAL_NO_EPILEPTIFORME"
|
||||
ANORMAL_MIXTO = "ANORMAL_MIXTO"
|
||||
NO_CONCLUYENTE = "NO_CONCLUYENTE"
|
||||
|
||||
|
||||
class FuenteAntecedenteMaterno(str, Enum):
|
||||
"""amg_fuente_antecedente in table antecedentes_maternos_gestacion."""
|
||||
EXPEDIENTE_MATERNO = "EXPEDIENTE_MATERNO"
|
||||
INTERROGATORIO_NM11 = "INTERROGATORIO_NM11"
|
||||
AMBAS = "AMBAS"
|
||||
NO_LOCALIZADO = "NO_LOCALIZADO"
|
||||
|
||||
|
||||
class CategoriaPesoMaterno(str, Enum):
|
||||
"""amg_categoria_peso_materno in table antecedentes_maternos_gestacion."""
|
||||
BAJO_PESO = "BAJO_PESO"
|
||||
NORMAL = "NORMAL"
|
||||
SOBREPESO = "SOBREPESO"
|
||||
OBESIDAD_I = "OBESIDAD_I"
|
||||
OBESIDAD_II = "OBESIDAD_II"
|
||||
OBESIDAD_III = "OBESIDAD_III"
|
||||
NO_REGISTRADA = "NO_REGISTRADA"
|
||||
|
||||
|
||||
class TipoEmbarazo(str, Enum):
|
||||
"""amg_embarazo_multiple in table antecedentes_maternos_gestacion."""
|
||||
UNICO = "UNICO"
|
||||
GEMELAR = "GEMELAR"
|
||||
TRIPLE_O_MAS = "TRIPLE_O_MAS"
|
||||
NO_REGISTRADO = "NO_REGISTRADO"
|
||||
|
||||
|
||||
class TrastornoHipertensivoGestacion(str, Enum):
|
||||
"""amg_hipertension_preeclampsia in table antecedentes_maternos_gestacion."""
|
||||
NINGUNO = "NINGUNO"
|
||||
HIPERTENSION_GESTACIONAL = "HIPERTENSION_GESTACIONAL"
|
||||
PREECLAMPSIA = "PREECLAMPSIA"
|
||||
ECLAMPSIA = "ECLAMPSIA"
|
||||
SINDROME_HELLP = "SINDROME_HELLP"
|
||||
NO_REGISTRADO = "NO_REGISTRADO"
|
||||
|
||||
|
||||
class VolumenLiquidoAmniotico(str, Enum):
|
||||
"""amg_liquido_amniotico in table antecedentes_maternos_gestacion."""
|
||||
NORMAL = "NORMAL"
|
||||
OLIGOHIDRAMNIOS = "OLIGOHIDRAMNIOS"
|
||||
POLIHIDRAMNIOS = "POLIHIDRAMNIOS"
|
||||
NO_REGISTRADO = "NO_REGISTRADO"
|
||||
|
||||
|
||||
class FuenteAntecedenteNeonatal(str, Enum):
|
||||
"""pnn_fuente_antecedente in table parto_neonatal."""
|
||||
NOTA_RECIEN_NACIDO = "NOTA_RECIEN_NACIDO"
|
||||
NOTA_RESOLUCION_OBSTETRICA = "NOTA_RESOLUCION_OBSTETRICA"
|
||||
INTERROGATORIO_NM11 = "INTERROGATORIO_NM11"
|
||||
AMBAS = "AMBAS"
|
||||
NO_LOCALIZADA = "NO_LOCALIZADA"
|
||||
|
||||
|
||||
class TipoParto(str, Enum):
|
||||
"""pnn_tipo_parto in table parto_neonatal."""
|
||||
VAGINAL_ESPONTANEO = "VAGINAL_ESPONTANEO"
|
||||
VAGINAL_INSTRUMENTADO = "VAGINAL_INSTRUMENTADO"
|
||||
CESAREA_ELECTIVA = "CESAREA_ELECTIVA"
|
||||
CESAREA_URGENCIA = "CESAREA_URGENCIA"
|
||||
NO_REGISTRADO = "NO_REGISTRADO"
|
||||
|
||||
|
||||
class ComplicacionIntraparto(str, Enum):
|
||||
"""pnn_complicacion_tipo in table parto_neonatal."""
|
||||
NINGUNA = "NINGUNA"
|
||||
HIPOXIA = "HIPOXIA"
|
||||
ISQUEMIA = "ISQUEMIA"
|
||||
TRAUMA_OBSTETRICO = "TRAUMA_OBSTETRICO"
|
||||
CIRCULAR_DE_CORDON = "CIRCULAR_DE_CORDON"
|
||||
SUFRIMIENTO_FETAL_AGUDO = "SUFRIMIENTO_FETAL_AGUDO"
|
||||
OTRA = "OTRA"
|
||||
|
||||
|
||||
class ClasificacionEdadGestacional(str, Enum):
|
||||
"""pnn_clasificacion_eg in table parto_neonatal."""
|
||||
PRETERMINO_EXTREMO = "PRETERMINO_EXTREMO"
|
||||
MUY_PRETERMINO = "MUY_PRETERMINO"
|
||||
PRETERMINO_TARDIO = "PRETERMINO_TARDIO"
|
||||
TERMINO = "TERMINO"
|
||||
POSTERMINO = "POSTERMINO"
|
||||
NO_DETERMINADA = "NO_DETERMINADA"
|
||||
|
||||
|
||||
class TamanoParaEdadGestacional(str, Enum):
|
||||
"""pnn_tamano_para_eg in table parto_neonatal."""
|
||||
PEQUENO = "PEQUENO"
|
||||
ADECUADO = "ADECUADO"
|
||||
GRANDE = "GRANDE"
|
||||
NO_DETERMINADO = "NO_DETERMINADO"
|
||||
# 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",
|
||||
"T5", "P3", "Pz", "P4", "T6", "O1", "O2",
|
||||
)
|
||||
|
||||
+133
-338
@@ -1,18 +1,52 @@
|
||||
"""TEA staging tables (data dictionary: spec/tablas_TEA.md).
|
||||
|
||||
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).
|
||||
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.
|
||||
|
||||
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, datetime
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Field
|
||||
|
||||
from core.tea.base import TeaModel
|
||||
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
|
||||
from core.tea.base import TeaModel
|
||||
|
||||
# The ADOS-2 items with an algorithm score: social affect (SA) and restricted and repetitive behaviour (RRB).
|
||||
ADOS2_ITEMS = (
|
||||
"sa_a2", "sa_a6", "sa_a7", "sa_a8", "sa_b1", "sa_b2", "sa_b3", "sa_b4", "sa_b5", "sa_b6", "sa_b7", "sa_b8",
|
||||
"sa_b9", "sa_b10", "sa_b11", "sa_b12", "sa_b13", "sa_b14", "sa_b15", "sa_b16b", "sa_b18",
|
||||
"rrb_a3", "rrb_a4", "rrb_a5", "rrb_d1", "rrb_d2", "rrb_d4", "rrb_d5",
|
||||
)
|
||||
|
||||
|
||||
def _uuid() -> str:
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def _id() -> Field:
|
||||
return Field(default_factory=_uuid, sa_column=sa.Column(sa.String(36), primary_key=True))
|
||||
|
||||
|
||||
def _text() -> Field:
|
||||
return Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
|
||||
|
||||
def _int() -> Field:
|
||||
return Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
|
||||
|
||||
def _float() -> Field:
|
||||
return Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
|
||||
|
||||
def _date() -> Field:
|
||||
return Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
|
||||
|
||||
class Pacientes(TeaModel, table=True):
|
||||
@@ -22,366 +56,127 @@ class Pacientes(TeaModel, table=True):
|
||||
default=None,
|
||||
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
|
||||
)
|
||||
pac_id_hospital: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pac_id_titular: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pac_parentesco: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pac_fecha_nacimiento: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
pac_sexo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pac_codigo_postal_vigente: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pac_dependencia: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pac_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
pac_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
pac_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pac_id_hospital: Optional[str] = _text()
|
||||
pac_fecha_nacimiento: Optional[date] = _date()
|
||||
|
||||
|
||||
class OrdenesEstudio(TeaModel, table=True):
|
||||
__tablename__ = "ordenes_estudio"
|
||||
|
||||
ord_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
ord_pac_id: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
ord_nota_medica_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
# Bounded and indexed, unlike TEA's other unenforced Text references: it
|
||||
# is the natural key the import layer upserts/merges orders on.
|
||||
ord_id: Optional[str] = _id()
|
||||
ord_pac_id: Optional[int] = _int()
|
||||
# Bounded and indexed: the natural key the import layer merges orders on.
|
||||
ord_id_hospital: Optional[str] = Field(
|
||||
default=None, sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True)
|
||||
)
|
||||
ord_fecha: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
ord_medico_solicitante: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_especialidad: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_diagnostico_asignado: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_cie_asignado: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_dias_vigencia: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
ord_fecha_vencimiento: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
ord_tipo_estudio: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_estatus: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_fecha_realizacion: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
ord_fecha_resultado: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
ord_dias_espera: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
ord_proveedor: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_edad_meses: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
ord_ventana_madurativa: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_pdf_ruta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_observaciones: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
ord_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
ord_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ord_tipo_estudio: Optional[str] = _text() # TipoEstudio: ADOS2, NEUROPEDIATRIA, EEG
|
||||
ord_fecha: Optional[date] = _date()
|
||||
|
||||
|
||||
class NotaMedica(TeaModel, table=True):
|
||||
__tablename__ = "nota_medica"
|
||||
class Mchat(TeaModel, table=True):
|
||||
__tablename__ = "mchat"
|
||||
|
||||
nm_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
nm_pac_id: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
# Bounded and indexed, unlike TEA's other unenforced Text references: it
|
||||
# is the natural key the import layer upserts/merges notes on.
|
||||
nm_id_hospital: Optional[str] = Field(
|
||||
default=None, sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True)
|
||||
)
|
||||
nm_nota_previa_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_tipo_nota: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_especialidad: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_fecha: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
nm_edad_meses: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
nm_ventana_madurativa: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_medico_tratante: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_motivo_consulta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_interrogatorio: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_regresion_referida: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
nm_antecedente_familiar_tea: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
nm_perimetro_cefalico: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
nm_diagnostico_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_cie_codigo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_cie_descripcion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_tratamiento_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_receta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_plan_estudios: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_pronostico: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_observaciones: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_masa_corporal: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
nm_talla: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
nm_imc_visita: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
nm_frecuencia_cardiaca: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
nm_frecuencia_respiratoria: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
nm_presion_arterial_sistolica: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
nm_presion_arterial_diastolica: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
nm_temperatura: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
nm_pdf_ruta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
nm_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
nm_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
nm_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
mch_id: Optional[str] = _id()
|
||||
mch_pac_id: Optional[int] = _int()
|
||||
mch_ord_id: Optional[str] = _text()
|
||||
mch_fecha: Optional[date] = _date()
|
||||
mch_puntaje: Optional[int] = _int() # 0 to 20
|
||||
|
||||
|
||||
class EvaluacionPsicologica(TeaModel, table=True):
|
||||
__tablename__ = "evaluacion_psicologica"
|
||||
class Ados2(TeaModel, table=True):
|
||||
__tablename__ = "ados2"
|
||||
|
||||
psi_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
psi_ord_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_pac_id: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_fecha_entrevista_inicial: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
psi_fecha_ados2: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
psi_fecha_evaluacion: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
psi_psicologo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_edad_meses: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
psi_ventana_madurativa: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_instrumento_tamizaje: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_tamizaje_puntaje: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_tamizaje_riesgo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_ados2_modulo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
# ADOS-2 item columns (data dictionary, annex B); the valid range and which
|
||||
# items apply depend on psi_ados2_modulo.
|
||||
psi_ados2_sa_a2: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_a6: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_a7: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_a8: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b1: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b2: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b3: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b4: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b5: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b6: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b7: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b8: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b9: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b10: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b11: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b12: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b13: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b14: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b15: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b16b: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa_b18: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_rrb_a3: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_rrb_a4: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_rrb_a5: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_rrb_d1: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_rrb_d2: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_rrb_d4: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_rrb_d5: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_sa: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_rrb: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_total: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_css: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_css_sa: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_css_rrb: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_ados2_clasificacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_rgd: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_cociente_desarrollo: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
psi_css_umbral_aplicado: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_caso_confirmado: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_cars_total: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
psi_otros_instrumentos: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_regresion_desarrollo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
psi_diagnostico_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
psi_nlp_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
psi_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
psi_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
ado_id: Optional[str] = _id()
|
||||
ado_pac_id: Optional[int] = _int()
|
||||
ado_ord_id: Optional[str] = _text()
|
||||
ado_fecha: Optional[date] = _date()
|
||||
ado_modulo: Optional[str] = _text()
|
||||
# Within a module the algorithm depends on the child's language level (item A1).
|
||||
ado_algoritmo: Optional[str] = _text()
|
||||
ado_css: Optional[int] = _int() # 1 to 10
|
||||
ado_clasificacion: Optional[str] = _text()
|
||||
# Item scores, 0 to 3. The domain subtotals and the total are sums of their algorithm scores.
|
||||
ado_sa_a2: Optional[int] = _int()
|
||||
ado_sa_a6: Optional[int] = _int()
|
||||
ado_sa_a7: Optional[int] = _int()
|
||||
ado_sa_a8: Optional[int] = _int()
|
||||
ado_sa_b1: Optional[int] = _int()
|
||||
ado_sa_b2: Optional[int] = _int()
|
||||
ado_sa_b3: Optional[int] = _int()
|
||||
ado_sa_b4: Optional[int] = _int()
|
||||
ado_sa_b5: Optional[int] = _int()
|
||||
ado_sa_b6: Optional[int] = _int()
|
||||
ado_sa_b7: Optional[int] = _int()
|
||||
ado_sa_b8: Optional[int] = _int()
|
||||
ado_sa_b9: Optional[int] = _int()
|
||||
ado_sa_b10: Optional[int] = _int()
|
||||
ado_sa_b11: Optional[int] = _int()
|
||||
ado_sa_b12: Optional[int] = _int()
|
||||
ado_sa_b13: Optional[int] = _int()
|
||||
ado_sa_b14: Optional[int] = _int()
|
||||
ado_sa_b15: Optional[int] = _int()
|
||||
ado_sa_b16b: Optional[int] = _int()
|
||||
ado_sa_b18: Optional[int] = _int()
|
||||
ado_rrb_a3: Optional[int] = _int()
|
||||
ado_rrb_a4: Optional[int] = _int()
|
||||
ado_rrb_a5: Optional[int] = _int()
|
||||
ado_rrb_d1: Optional[int] = _int()
|
||||
ado_rrb_d2: Optional[int] = _int()
|
||||
ado_rrb_d4: Optional[int] = _int()
|
||||
ado_rrb_d5: Optional[int] = _int()
|
||||
|
||||
|
||||
class PotencialesEvocadosAuditivos(TeaModel, table=True):
|
||||
__tablename__ = "potenciales_evocados_auditivos"
|
||||
class EvaluacionNeuropediatrica(TeaModel, table=True):
|
||||
__tablename__ = "evaluacion_neuropediatrica"
|
||||
|
||||
pea_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
pea_ord_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pea_pac_id: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pea_fecha_estudio: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
pea_medico_interpreta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pea_umbral_od: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pea_umbral_oi: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pea_latencia_v_od: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pea_latencia_v_oi: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pea_interpico_i_v_od: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pea_interpico_i_v_oi: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pea_grado_hipoacusia: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pea_conclusion_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pea_flag_diferencial_auditivo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pea_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pea_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
pea_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
neu_id: Optional[str] = _id()
|
||||
neu_pac_id: Optional[int] = _int()
|
||||
neu_ord_id: Optional[str] = _text()
|
||||
neu_fecha: Optional[date] = _date()
|
||||
neu_cie_codigo: Optional[str] = _text()
|
||||
|
||||
|
||||
class EegEstudio(TeaModel, table=True):
|
||||
__tablename__ = "eeg_estudio"
|
||||
class Eeg(TeaModel, table=True):
|
||||
__tablename__ = "eeg"
|
||||
|
||||
eeg_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
eeg_ord_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
# The child's integer pac_id, like the other studies' `*_pac_id`: the
|
||||
# indicator kit links each EEG to its patient by this key.
|
||||
eeg_pac_id: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_reporte_disponible: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_fuente_interpretacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_fecha_nacimiento_archivo: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
eeg_edad_meses: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
eeg_fecha_estudio: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
eeg_fecha_reporte: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
|
||||
eeg_dias_respuesta: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_medico_interpreta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_estado_registro: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_privacion_sueno: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_sedacion: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_sedacion_farmaco: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_duracion_min: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
eeg_calidad_tecnica: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_descripcion_senal: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_ritmo_base_frecuencia: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
eeg_ritmo_base_amplitud: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_simetria: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_anormalidad_presente: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_actividad_epileptiforme: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_tipo_grafoelemento: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_distribucion_anormalidad: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_localizacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_activacion_sueno: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_lentificacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_crisis_registradas: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_respuesta_fotoestimulacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_conclusion_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_conclusion_categoria: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
# Bounded and indexed (unlike TEA's other unenforced Text references):
|
||||
# it is the natural key multiple sources (a report PDF, the EDF file
|
||||
# itself) use to land in the same row, so the import layer upserts on it.
|
||||
eeg_id: Optional[str] = _id()
|
||||
eeg_pac_id: Optional[int] = _int()
|
||||
eeg_ord_id: Optional[str] = _text()
|
||||
# Bounded and indexed: the natural key several sources (a report, the EDF itself) land in the same row by.
|
||||
eeg_id_registro_laboratorio: Optional[str] = Field(
|
||||
default=None, sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True)
|
||||
)
|
||||
eeg_pdf_ruta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
eeg_nlp_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
eeg_utilizable: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
eeg_estudio: Optional[bytes] = Field(default=None, sa_column=sa.Column(FileBlob))
|
||||
eeg_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
eeg_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
eeg_fecha_estudio: Optional[date] = _date()
|
||||
# Written by the EEG analysis.
|
||||
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
|
||||
|
||||
|
||||
class EegSegmento(TeaModel, table=True):
|
||||
__tablename__ = "eeg_segmento"
|
||||
class EegMetrica(TeaModel, table=True):
|
||||
"""One metric the EEG analysis measured on an EEG. A null value is a metric that can't be evaluated."""
|
||||
|
||||
seg_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
seg_eeg_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
seg_estado: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
seg_inicio_s: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
seg_fin_s: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
seg_duracion_s: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
seg_fuente: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
seg_frecuencia_flash_hz: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
seg_n_destellos: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
seg_cobertura: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
seg_rms_uv: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
seg_emg: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
seg_p2p_max_uv: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
__tablename__ = "eeg_metrica"
|
||||
|
||||
met_id: Optional[str] = _id()
|
||||
met_eeg_id: Optional[str] = _text()
|
||||
met_codigo: Optional[str] = _text() # MetricaEeg
|
||||
met_valor: Optional[float] = _float()
|
||||
|
||||
|
||||
class InstrumentoAplicado(TeaModel, table=True):
|
||||
__tablename__ = "instrumento_aplicado"
|
||||
class EegMetricaElectrodo(TeaModel, table=True):
|
||||
"""A metric's value at one electrode of the 10-20 system."""
|
||||
|
||||
ins_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
ins_psi_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ins_instrumento: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ins_informante: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ins_area: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
ins_interpretacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
__tablename__ = "eeg_metrica_electrodo"
|
||||
|
||||
|
||||
class AntecedentesMaternosGestacion(TeaModel, table=True):
|
||||
__tablename__ = "antecedentes_maternos_gestacion"
|
||||
|
||||
amg_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
amg_pac_id: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_id_madre_seudonimo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_fuente_antecedente: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_flag_vinculo_verificado: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_imc_pregestacional: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
amg_categoria_peso_materno: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_tabaquismo_gestacion: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_acido_folico_preconcepcional: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_intervalo_intergenesico_meses: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_antecedente_aborto: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_embarazo_multiple: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_infeccion_gestacion: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_infeccion_tipo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_infeccion_hospitalizacion: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_diabetes_gestacional: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_hipertension_preeclampsia: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_hipotiroidismo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_hipertiroidismo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_incompatibilidad_rh: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_crisis_convulsivas: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_proceso_proinflamatorio: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_enfermedad_autoinmune: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_migrana: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_asma: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_hipoxia_materna: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_estres_agudo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_trastorno_neurologico: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_liquido_amniotico: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_medicamentos_gestacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_farmaco_riesgo_neurodesarrollo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
amg_observaciones: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
amg_nlp_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
amg_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
amg_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
amg_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
|
||||
|
||||
class PartoNeonatal(TeaModel, table=True):
|
||||
__tablename__ = "parto_neonatal"
|
||||
|
||||
pnn_id: Optional[str] = Field(
|
||||
default_factory=lambda: str(uuid.uuid4()),
|
||||
sa_column=sa.Column(sa.String(36), primary_key=True),
|
||||
)
|
||||
pnn_pac_id: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_fuente_antecedente: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pnn_tipo_parto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pnn_complicaciones_intraparto: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_complicacion_tipo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pnn_peso_nacer_g: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_talla_nacer_cm: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pnn_perimetro_cefalico_nacer_cm: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pnn_edad_gestacional_sem: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pnn_clasificacion_eg: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pnn_tamano_para_eg: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pnn_peso_nacer_zscore: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pnn_apgar_1min: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_apgar_5min: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_ingreso_ucin: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_dias_ucin: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_encefalopatia_hipoxico_isquemica: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_hipotermia_nacer: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_hiperbilirrubinemia: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_fototerapia: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_hipoglucemia_neonatal: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_anoxia: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_sindrome_congenito: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_sindrome_congenito_desc: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pnn_flag_riesgo_neonatal: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
|
||||
pnn_observaciones: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pnn_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
|
||||
pnn_nlp_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
pnn_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
pnn_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
|
||||
pnn_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
|
||||
mel_id: Optional[str] = _id()
|
||||
mel_met_id: Optional[str] = _text()
|
||||
mel_electrodo: Optional[str] = _text()
|
||||
mel_valor: Optional[float] = _float()
|
||||
|
||||
+58
-479
@@ -1,8 +1,12 @@
|
||||
# Diccionario de datos y reglas de validación — Proyecto TEA
|
||||
|
||||
Este documento describe la base de datos del proyecto. Para cada tabla se listan sus
|
||||
variables, el tipo de dato, la unidad (cuando aplica) y la validación que debe
|
||||
cumplir cada una.
|
||||
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,
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
@@ -12,27 +16,7 @@ cumplir cada una.
|
||||
|---|---|---|---|---|
|
||||
| `pac_id` | INTEGER, llave primaria, autoincremental | — | — | — |
|
||||
| `pac_id_hospital` | TEXT | — | — | — |
|
||||
| `pac_id_titular` | TEXT | — | — | — |
|
||||
| `pac_parentesco` | TEXT | — | Catálogo cerrado `Parentesco`: `HIJO, HIJA, HIJASTRO, TUTELADO, OTRO`. | — |
|
||||
| `pac_fecha_nacimiento` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `pac_sexo` | TEXT | — | Catálogo cerrado `SexoBiologico`: `F, M, I`. | — |
|
||||
| `pac_codigo_postal_vigente` | TEXT | — | Debe quedar en 5 dígitos numéricos exactos (se completa con ceros a la izquierda si llega con menos). | — |
|
||||
| `pac_dependencia` | TEXT | — | — | — |
|
||||
| `pac_created_at` | DATETIME | — | — | — |
|
||||
| `pac_updated_at` | DATETIME | — | — | — |
|
||||
| `pac_fuente_sistema` | TEXT | — | — | — |
|
||||
|
||||
Sin validaciones cruzadas.
|
||||
|
||||
`pac_id` cambió de `VARCHAR(36)` (UUID) a `INTEGER` autoincremental el
|
||||
2026-10-19, para que `indicadores_kit` pueda cargar su CDM directamente
|
||||
(`core.indicadores.comunes.PersonaBase.pac_id` es `int`; el ETL del kit,
|
||||
`tea/etl.py::a_persona`, pasa `paciente.pac_id` sin convertir). Todas las
|
||||
columnas `*_pac_id` de las demás tablas de este documento cambiaron con
|
||||
ella. `eeg_estudio.eeg_pac_id` pasó a INTEGER después (2026-10-29): el
|
||||
origen la trae y `indicadores_kit` liga cada EEG a su niño por esta llave. Reset de la cadena de Alembic a una
|
||||
sola migración base (rule 3), no una migración de `ALTER COLUMN`: no había
|
||||
datos reales en ninguna base de TEA todavía.
|
||||
|
||||
---
|
||||
|
||||
@@ -42,502 +26,97 @@ datos reales en ninguna base de TEA todavía.
|
||||
|---|---|---|---|---|
|
||||
| `ord_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `ord_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `ord_nota_medica_id` | TEXT | — | — | → `nota_medica.nm_id` |
|
||||
| `ord_id_hospital` | VARCHAR(64), indexado | — | Llave natural para `on_conflict=upsert`/`merge` al importar órdenes de varias fuentes. | — |
|
||||
| `ord_id_hospital` | VARCHAR(64), indexado | — | Llave natural para unir órdenes de varias fuentes al importar. | — |
|
||||
| `ord_tipo_estudio` | TEXT | — | Catálogo `TipoEstudio`: `ADOS2, NEUROPEDIATRIA, EEG`. | — |
|
||||
| `ord_fecha` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `ord_medico_solicitante` | TEXT | — | — | — |
|
||||
| `ord_especialidad` | TEXT | — | Catálogo `Especialidad`: `NEUROLOGIA_PEDIATRICA, PEDIATRIA, PSICOLOGIA, PSIQUIATRIA_INFANTIL, AUDIOLOGIA, MEDICINA_FAMILIAR, ENFERMERIA, OTRO`. | — |
|
||||
| `ord_diagnostico_asignado` | TEXT | — | — | — |
|
||||
| `ord_cie_asignado` | TEXT | — | Formato CIE: una letra mayúscula, dos dígitos, y opcionalmente un punto con uno o dos dígitos más (ejemplo: `A09.1`). | — |
|
||||
| `ord_dias_vigencia` | INTEGER | días | Entre 1 y 365. | — |
|
||||
| `ord_fecha_vencimiento` | DATE | — | Ver validación cruzada. | — |
|
||||
| `ord_proveedor` | TEXT | — | — | — |
|
||||
| `ord_tipo_estudio` | TEXT | — | Catálogo `TipoEstudio`: `ELECTROENCEFALOGRAMA, POTENCIALES_EVOCADOS_AUDITIVOS, EVALUACION_PSICOLOGICA_TEA, OTRO`. | — |
|
||||
| `ord_estatus` | TEXT | — | Catálogo `EstatusEstudio`: `SOLICITADO, EN_PROCESO, REALIZADO, RESULTADO_DISPONIBLE, CANCELADO, NO_ACUDIO`. | — |
|
||||
| `ord_fecha_realizacion` | DATE | — | No puede ser una fecha futura. Ver validación cruzada. | — |
|
||||
| `ord_fecha_resultado` | DATE | — | No puede ser una fecha futura. Ver validación cruzada. | — |
|
||||
| `ord_dias_espera` | INTEGER | días | Entre 0 y 180. | — |
|
||||
| `ord_edad_meses` | FLOAT | meses | Entre 16.0 y 36.0. | — |
|
||||
| `ord_ventana_madurativa` | TEXT | — | Catálogo `VentanaMadurativa`: `V1_16_23, V2_24_30, V3_31_36, FUERA_DE_RANGO`. Ver validación cruzada. | — |
|
||||
| `ord_pdf_ruta` | TEXT | — | — | — |
|
||||
| `ord_observaciones` | TEXT | — | — | — |
|
||||
| `ord_created_at` | DATETIME | — | — | — |
|
||||
| `ord_updated_at` | DATETIME | — | — | — |
|
||||
| `ord_fuente_sistema` | TEXT | — | — | — |
|
||||
|
||||
**Validaciones cruzadas de `ordenes_estudio`:**
|
||||
- `ord_fecha_vencimiento` debe ser igual a `ord_fecha + ord_dias_vigencia` días, cuando ambos valores existen.
|
||||
- `ord_fecha_realizacion` no puede ser anterior a `ord_fecha`.
|
||||
- `ord_fecha_resultado` no puede ser anterior a `ord_fecha_realizacion`.
|
||||
- `ord_ventana_madurativa` debe corresponder a `ord_edad_meses` según la tabla de ventanas (Anexo A).
|
||||
|
||||
---
|
||||
|
||||
## 3. Tabla `nota_medica`
|
||||
## 3. Tabla `mchat`
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `nm_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `nm_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `nm_id_hospital` | VARCHAR(64), indexado | — | Llave natural para `on_conflict=upsert`/`merge` al importar notas de varias fuentes. | — |
|
||||
| `nm_nota_previa_id` | TEXT | — | — | → `nota_medica.nm_id` (autorreferencia: nota previa del mismo paciente) |
|
||||
| `nm_tipo_nota` | TEXT | — | Catálogo `TipoNota`: `PRIMERA_VEZ, TAMIZAJE, INTERPRETACION_EEG, TRATAMIENTO, SEGUIMIENTO, INTERCONSULTA, URGENCIA, OTRO`. | — |
|
||||
| `nm_especialidad` | TEXT | — | Catálogo `Especialidad` (mismo que `ord_especialidad`). | — |
|
||||
| `nm_fecha` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `nm_edad_meses` | FLOAT | meses | Entre 16.0 y 36.0. | — |
|
||||
| `nm_ventana_madurativa` | TEXT | — | Catálogo `VentanaMadurativa`. Ver validación cruzada. | — |
|
||||
| `nm_medico_tratante` | TEXT | — | — | — |
|
||||
| `nm_motivo_consulta` | TEXT | — | — | — |
|
||||
| `nm_interrogatorio` | TEXT | — | — | — |
|
||||
| `nm_regresion_referida` | BOOL | — | — | — |
|
||||
| `nm_antecedente_familiar_tea` | BOOL | — | — | — |
|
||||
| `nm_perimetro_cefalico` | FLOAT | cm | Entre 38.0 y 58.0. | — |
|
||||
| `nm_diagnostico_texto` | TEXT | — | — | — |
|
||||
| `nm_cie_codigo` | TEXT | — | Formato CIE: una letra mayúscula, dos dígitos, punto opcional con uno o dos dígitos más. | — |
|
||||
| `nm_cie_descripcion` | TEXT | — | — | — |
|
||||
| `nm_tratamiento_texto` | TEXT | — | — | — |
|
||||
| `nm_receta` | TEXT | — | — | — |
|
||||
| `nm_plan_estudios` | TEXT | — | — | — |
|
||||
| `nm_pronostico` | TEXT | — | Catálogo `Pronostico`: `BUENO, RESERVADO, MALO, NO_ESPECIFICADO`. | — |
|
||||
| `nm_observaciones` | TEXT | — | — | — |
|
||||
| `nm_masa_corporal` | FLOAT | kg | Entre 2.0 y 40.0. | — |
|
||||
| `nm_talla` | FLOAT | m | Entre 0.4 y 1.4. | — |
|
||||
| `nm_imc_visita` | FLOAT | kg/m² | Entre 5.0 y 40.0. Ver validación cruzada con peso y talla. | — |
|
||||
| `nm_frecuencia_cardiaca` | INTEGER | lpm | Entre 50 y 230. | — |
|
||||
| `nm_frecuencia_respiratoria` | INTEGER | rpm | Entre 10 y 80. | — |
|
||||
| `nm_presion_arterial_sistolica` | INTEGER | mmHg | Entre 45 y 160. Ver validación cruzada. | — |
|
||||
| `nm_presion_arterial_diastolica` | INTEGER | mmHg | Entre 25 y 110. Ver validación cruzada. | — |
|
||||
| `nm_temperatura` | FLOAT | °C | Entre 32.0 y 43.0. | — |
|
||||
| `nm_pdf_ruta` | TEXT | — | — | — |
|
||||
| `nm_created_at` | DATETIME | — | — | — |
|
||||
| `nm_updated_at` | DATETIME | — | — | — |
|
||||
| `nm_fuente_sistema` | TEXT | — | — | — |
|
||||
|
||||
**Validaciones cruzadas de `nota_medica`:**
|
||||
- La presión sistólica debe ser mayor que la diastólica.
|
||||
- `nm_imc_visita` debe ser aproximadamente igual a `nm_masa_corporal / nm_talla²` (tolerancia de 0.5).
|
||||
- `nm_ventana_madurativa` debe corresponder a `nm_edad_meses` (Anexo A).
|
||||
| `mch_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `mch_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `mch_ord_id` | TEXT | — | Casi siempre nulo: el M-CHAT rara vez tiene orden. | → `ordenes_estudio.ord_id` |
|
||||
| `mch_fecha` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `mch_puntaje` | INTEGER | puntos | Entre 0 y 20. | — |
|
||||
|
||||
---
|
||||
|
||||
## 4. Tabla `evaluacion_psicologica`
|
||||
## 4. Tabla `ados2`
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `psi_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `psi_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
|
||||
| `psi_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `psi_fecha_entrevista_inicial` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `psi_fecha_ados2` | DATE | — | No puede ser una fecha futura. La fecha en que se aplicó el ADOS-2, distinta de `psi_fecha_evaluacion`. | — |
|
||||
| `psi_fecha_evaluacion` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `psi_psicologo` | TEXT | — | — | — |
|
||||
| `psi_edad_meses` | FLOAT | meses | Entre 16.0 y 36.0. | — |
|
||||
| `psi_ventana_madurativa` | TEXT | — | Catálogo `VentanaMadurativa`. Ver validación cruzada. | — |
|
||||
| `psi_instrumento_tamizaje` | TEXT | — | Catálogo `InstrumentoTamizaje`: `M_CHAT_R, M_CHAT_RF, OTRO, NO_REGISTRADO`. | — |
|
||||
| `psi_tamizaje_puntaje` | INTEGER | — | Entre 0 y 20. | — |
|
||||
| `psi_tamizaje_riesgo` | TEXT | — | Catálogo `NivelRiesgoTamizaje`: `BAJO, MEDIO, ALTO, NO_APLICA`. | — |
|
||||
| `psi_ados2_modulo` | TEXT | — | Catálogo `ModuloAdos2`: `TODDLER, MODULO_1, MODULO_2, NO_REGISTRADO`. Define qué ítems del ADOS-2 aplican (Anexo B). | — |
|
||||
| `psi_ados2_sa` | INTEGER | — | Entre 0 y 30. Ver validación cruzada. | — |
|
||||
| `psi_ados2_rrb` | INTEGER | — | Entre 0 y 20. Ver validación cruzada. | — |
|
||||
| `psi_ados2_total` | INTEGER | — | Entre 0 y 50. Debe ser igual a `psi_ados2_sa + psi_ados2_rrb`. | — |
|
||||
| `psi_ados2_css` | INTEGER | — | Entre 1 y 10. | — |
|
||||
| `psi_ados2_css_sa` | INTEGER | — | Entre 1 y 10. | — |
|
||||
| `psi_ados2_css_rrb` | INTEGER | — | Entre 1 y 10. | — |
|
||||
| `psi_ados2_clasificacion` | TEXT | — | Catálogo `ClasificacionAdos2`: `NO_TEA, ESPECTRO_AUTISTA, AUTISMO, PREOCUPACION_LEVE_MODERADA, PREOCUPACION_SEVERA`. | — |
|
||||
| `psi_rgd` | BOOL | — | Ver validación cruzada (retraso global del desarrollo). | — |
|
||||
| `psi_cociente_desarrollo` | FLOAT | — | Entre 20.0 y 160.0. | — |
|
||||
| `psi_css_umbral_aplicado` | INTEGER | — | Entre 1 y 10. Ver validación cruzada. | — |
|
||||
| `psi_caso_confirmado` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `psi_cars_total` | FLOAT | — | Entre 15.0 y 60.0. Solo válido a partir de los 24 meses (ver validación cruzada). | — |
|
||||
| `psi_otros_instrumentos` | TEXT | — | — | — |
|
||||
| `psi_regresion_desarrollo` | BOOL | — | — | — |
|
||||
| `psi_diagnostico_texto` | TEXT | — | — | — |
|
||||
| `psi_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
|
||||
| `psi_nlp_version` | TEXT | — | — | — |
|
||||
| `psi_created_at` | DATETIME | — | — | — |
|
||||
| `psi_updated_at` | DATETIME | — | — | — |
|
||||
| `ado_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `ado_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `ado_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
|
||||
| `ado_fecha` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `ado_modulo` | TEXT | — | Catálogo `ModuloAdos2`: `TODDLER, MODULO_1, MODULO_2, MODULO_3`. | — |
|
||||
| `ado_algoritmo` | TEXT | — | El algoritmo del módulo, que depende del nivel de lenguaje (reactivo A1). | — |
|
||||
| `ado_css` | INTEGER | puntos | Entre 1 y 10. | — |
|
||||
| `ado_clasificacion` | TEXT | — | Catálogo `ClasificacionAdos2`: `NO_ESPECTRO, ESPECTRO_AUTISTA, AUTISMO, PREOCUPACION_LEVE_MODERADA, PREOCUPACION_SEVERA`. | — |
|
||||
| `ado_sa_a2` … `ado_sa_b18` (21) | INTEGER | puntos | Entre 0 y 3. Reactivos de afecto social. | — |
|
||||
| `ado_rrb_a3` … `ado_rrb_d5` (7) | INTEGER | puntos | Entre 0 y 3. Reactivos de comportamiento restringido y repetitivo. | — |
|
||||
|
||||
**Columnas de ítem del ADOS-2** (mismo tipo y patrón de validación que los puntajes enteros de arriba):
|
||||
|
||||
| Variable | Tipo | Unidad | Validación |
|
||||
|---|---|---|---|
|
||||
| `psi_ados2_sa_a2`, `psi_ados2_sa_a6`, `psi_ados2_sa_a7`, `psi_ados2_sa_a8`, `psi_ados2_sa_b1` … `psi_ados2_sa_b16b`, `psi_ados2_sa_b18` | INTEGER | — | Rango permitido según el módulo (Anexo B); fuera de rango se rechaza. |
|
||||
| `psi_ados2_rrb_a3`, `psi_ados2_rrb_a4`, `psi_ados2_rrb_a5`, `psi_ados2_rrb_d1`, `psi_ados2_rrb_d2`, `psi_ados2_rrb_d4`, `psi_ados2_rrb_d5` | INTEGER | — | Rango permitido según el módulo (Anexo B); fuera de rango se rechaza. |
|
||||
|
||||
El detalle exacto de rango por código y por módulo, la validación de completitud y
|
||||
la validación de pertenencia a módulo están en el **Anexo B**.
|
||||
|
||||
**Validaciones cruzadas de `evaluacion_psicologica`:**
|
||||
- `psi_ados2_total` debe ser igual a `psi_ados2_sa + psi_ados2_rrb`.
|
||||
- `psi_css_umbral_aplicado` debe ser 6 si `psi_rgd` es verdadero, y 5 si es falso.
|
||||
- `psi_caso_confirmado` debe ser igual a `psi_ados2_css >= psi_css_umbral_aplicado`.
|
||||
- `psi_cars_total` solo es válido si la ventana madurativa no es `V1_16_23` (la escala CARS aplica desde los 24 meses).
|
||||
- `psi_ventana_madurativa` debe corresponder a `psi_edad_meses` (Anexo A).
|
||||
- `psi_rgd` debe ser verdadero cuando `psi_cociente_desarrollo` es menor o igual a 75.0, y falso en caso contrario.
|
||||
|
||||
Las validaciones cruzadas propias del Anexo B (completitud y pertenencia a módulo) se
|
||||
suman a esta lista.
|
||||
Los subtotales por dominio y el total no se guardan: son sumas de los puntajes de algoritmo de los reactivos.
|
||||
|
||||
---
|
||||
|
||||
## 5. Tabla `potenciales_evocados_auditivos`
|
||||
## 5. Tabla `evaluacion_neuropediatrica`
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `pea_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `pea_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
|
||||
| `pea_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `pea_fecha_estudio` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `pea_medico_interpreta` | TEXT | — | — | — |
|
||||
| `pea_umbral_od` | INTEGER | dB | Entre 0 y 120 (oído derecho). | — |
|
||||
| `pea_umbral_oi` | INTEGER | dB | Entre 0 y 120 (oído izquierdo). | — |
|
||||
| `pea_latencia_v_od` | FLOAT | ms | Entre 3.5 y 12.0. | — |
|
||||
| `pea_latencia_v_oi` | FLOAT | ms | Entre 3.5 y 12.0. | — |
|
||||
| `pea_interpico_i_v_od` | FLOAT | ms | Entre 2.0 y 8.0. | — |
|
||||
| `pea_interpico_i_v_oi` | FLOAT | ms | Entre 2.0 y 8.0. | — |
|
||||
| `pea_grado_hipoacusia` | TEXT | — | Catálogo `GradoHipoacusia`: `NORMAL, LEVE, MODERADA, SEVERA, PROFUNDA, NO_CONCLUYENTE`. | — |
|
||||
| `pea_conclusion_texto` | TEXT | — | — | — |
|
||||
| `pea_flag_diferencial_auditivo` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `pea_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
|
||||
| `pea_created_at` | DATETIME | — | — | — |
|
||||
| `pea_updated_at` | DATETIME | — | — | — |
|
||||
|
||||
**Validación cruzada de `potenciales_evocados_auditivos`:**
|
||||
- Si `pea_grado_hipoacusia` es `MODERADA`, `SEVERA` o `PROFUNDA`, entonces `pea_flag_diferencial_auditivo` debe ser verdadero.
|
||||
| `neu_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `neu_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `neu_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
|
||||
| `neu_fecha` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `neu_cie_codigo` | TEXT | — | Formato CIE-10: una letra, dos dígitos y opcionalmente un punto con uno o dos dígitos (`F84.0`). | — |
|
||||
|
||||
---
|
||||
|
||||
## 6. Tabla `eeg_estudio`
|
||||
## 6. Tabla `eeg`
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `eeg_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `eeg_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
|
||||
| `eeg_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `eeg_reporte_disponible` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `eeg_fuente_interpretacion` | TEXT | — | Catálogo `FuenteInterpretacionEeg`: `REPORTE_NEUROPEDIATRIA, NOTA_MEDICA, AMBAS, NINGUNA`. | — |
|
||||
| `eeg_fecha_nacimiento_archivo` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `eeg_edad_meses` | FLOAT | meses | Entre 16.0 y 36.0. | — |
|
||||
| `eeg_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
|
||||
| `eeg_id_registro_laboratorio` | VARCHAR(64), indexado | — | Llave natural: el reporte y el EDF del mismo estudio caen en la misma fila. | — |
|
||||
| `eeg_fecha_estudio` | DATE | — | No puede ser una fecha futura. | — |
|
||||
| `eeg_fecha_reporte` | DATE | — | No puede ser una fecha futura. Ver validación cruzada. | — |
|
||||
| `eeg_dias_respuesta` | INTEGER | días | Entre 0 y 60. Ver validación cruzada. | — |
|
||||
| `eeg_medico_interpreta` | TEXT | — | — | — |
|
||||
| `eeg_estado_registro` | TEXT | — | Catálogo `EstadoRegistroEeg`: `VIGILIA, SUENO_ESPONTANEO, SUENO_INDUCIDO, MIXTO, NO_ESPECIFICADO`. | — |
|
||||
| `eeg_privacion_sueno` | BOOL | — | — | — |
|
||||
| `eeg_sedacion` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `eeg_sedacion_farmaco` | TEXT | — | Ver validación cruzada. | — |
|
||||
| `eeg_duracion_min` | REAL | min | Entre 10 y 1440. | — |
|
||||
| `eeg_calidad_tecnica` | TEXT | — | Catálogo `CalidadTecnicaEeg`: `SATISFACTORIA, LIMITADA_POR_ARTEFACTO, LIMITADA_POR_COLABORACION, NO_VALORABLE, NO_ESPECIFICADA`. | — |
|
||||
| `eeg_descripcion_senal` | TEXT | — | — | — |
|
||||
| `eeg_ritmo_base_frecuencia` | FLOAT | Hz | Entre 2.0 y 14.0. | — |
|
||||
| `eeg_ritmo_base_amplitud` | INTEGER | µV | Entre 5 y 300. | — |
|
||||
| `eeg_simetria` | TEXT | — | Catálogo `Simetria`: `SIMETRICO, ASIMETRICO_IZQUIERDO, ASIMETRICO_DERECHO, NO_ESPECIFICADA`. | — |
|
||||
| `eeg_anormalidad_presente` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `eeg_actividad_epileptiforme` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `eeg_tipo_grafoelemento` | TEXT | — | Catálogo `TipoGrafoelemento`: `NINGUNO, ESPIGA, ONDA_AGUDA, COMPLEJO_ESPIGA_ONDA, COMPLEJO_POLIESPIGA_ONDA, PUNTA_ONDA_LENTA, DESCARGA_RITMICA, OTRO`. Ver validación cruzada. | — |
|
||||
| `eeg_distribucion_anormalidad` | TEXT | — | Catálogo `DistribucionAnormalidad`: `FOCAL, MULTIFOCAL, GENERALIZADA, LATERALIZADA, NO_ESPECIFICADA`. | — |
|
||||
| `eeg_localizacion` | TEXT | — | — | — |
|
||||
| `eeg_activacion_sueno` | BOOL | — | — | — |
|
||||
| `eeg_lentificacion` | TEXT | — | Catálogo `Lentificacion`: `NINGUNA, FOCAL, GENERALIZADA, INTERMITENTE`. | — |
|
||||
| `eeg_crisis_registradas` | BOOL | — | — | — |
|
||||
| `eeg_respuesta_fotoestimulacion` | TEXT | — | Catálogo `RespuestaFotoestimulacion`: `NORMAL, RESPUESTA_FOTOPAROXISTICA, SIN_RESPUESTA, NO_PRACTICADA`. | — |
|
||||
| `eeg_conclusion_texto` | TEXT | — | Ver validación cruzada. | — |
|
||||
| `eeg_conclusion_categoria` | TEXT | — | Catálogo `ConclusionEeg`: `NORMAL_PARA_LA_EDAD, NORMAL_CON_VARIANTES, ANORMAL_EPILEPTIFORME, ANORMAL_NO_EPILEPTIFORME, ANORMAL_MIXTO, NO_CONCLUYENTE`. Ver validación cruzada. | — |
|
||||
| `eeg_id_registro_laboratorio` | VARCHAR(64), indexado | — | Llave natural: un reporte en PDF y el archivo EDF del mismo estudio comparten este valor y se combinan en el mismo renglón al importar (`on_conflict=upsert`/`merge`). | — |
|
||||
| `eeg_pdf_ruta` | TEXT | — | — | — |
|
||||
| `eeg_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
|
||||
| `eeg_nlp_version` | TEXT | — | — | — |
|
||||
| `eeg_utilizable` | BOOL | — | Si el estudio completo puede usarse para calcular indicadores; criterio de `indicadores_kit` (medida K06), no de esta capa. | — |
|
||||
| `eeg_estudio` | BLOB | — | Archivo European Data Format (`.edf`) del registro; se valida con `mne.io.read_raw_edf` (Enmienda). | — |
|
||||
| `eeg_created_at` | DATETIME | — | — | — |
|
||||
| `eeg_updated_at` | DATETIME | — | — | — |
|
||||
| `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_estudio` | BLOB (LONGBLOB en MySQL) | — | El archivo EDF. | — |
|
||||
|
||||
**Validaciones cruzadas de `eeg_estudio`:**
|
||||
- `eeg_fecha_reporte` no puede ser anterior a `eeg_fecha_estudio`.
|
||||
- `eeg_dias_respuesta` debe ser igual a la diferencia en días entre `eeg_fecha_reporte` y `eeg_fecha_estudio`.
|
||||
- Si `eeg_actividad_epileptiforme` es falso, `eeg_tipo_grafoelemento` debe quedar vacío o en `NINGUNO`.
|
||||
- Si `eeg_actividad_epileptiforme` es verdadero, `eeg_anormalidad_presente` debe ser verdadero.
|
||||
- Si `eeg_sedacion` es falso, `eeg_sedacion_farmaco` debe quedar vacío.
|
||||
- Si `eeg_reporte_disponible` es verdadero, `eeg_conclusion_texto` no puede quedar vacío.
|
||||
- Si `eeg_conclusion_categoria` es `NORMAL_PARA_LA_EDAD` o `NORMAL_CON_VARIANTES`, entonces `eeg_anormalidad_presente` debe ser falso.
|
||||
|
||||
`eeg_fecha_nacimiento_archivo` se llamaba `eeg_fecha_nacimiento_declarada`
|
||||
hasta el 2026-10-19: se renombró para que coincidiera con el nombre real
|
||||
de la columna en el hospital (confirmado por introspección directa de
|
||||
`hospital.eeg_estudio` vía el túnel) y con lo que lee
|
||||
`indicadores_kit.tea.mapeo.ligar_eegs` (la liga del EEG con el niño por
|
||||
fecha de nacimiento, ver `tea/mapeo.md`). Mismo nombre, no un campo
|
||||
nuevo.
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## 7. Tabla `antecedentes_maternos_gestacion`
|
||||
## 7. Tabla `eeg_metrica` **(análisis del EEG)**
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `amg_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `amg_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `amg_id_madre_seudonimo` | TEXT | — | Ver validación cruzada. | — |
|
||||
| `amg_fuente_antecedente` | TEXT | — | Catálogo `FuenteAntecedenteMaterno`: `EXPEDIENTE_MATERNO, INTERROGATORIO_NM11, AMBAS, NO_LOCALIZADO`. Ver validación cruzada. | — |
|
||||
| `amg_flag_vinculo_verificado` | BOOL | — | — | — |
|
||||
| `amg_imc_pregestacional` | FLOAT | kg/m² | Entre 12.0 y 70.0. Ver validación cruzada. | — |
|
||||
| `amg_categoria_peso_materno` | TEXT | — | Catálogo `CategoriaPesoMaterno`: `BAJO_PESO, NORMAL, SOBREPESO, OBESIDAD_I, OBESIDAD_II, OBESIDAD_III, NO_REGISTRADA`. Ver validación cruzada. | — |
|
||||
| `amg_tabaquismo_gestacion` | BOOL | — | — | — |
|
||||
| `amg_acido_folico_preconcepcional` | BOOL | — | — | — |
|
||||
| `amg_intervalo_intergenesico_meses` | INTEGER | meses | Entre 0 y 360. | — |
|
||||
| `amg_antecedente_aborto` | BOOL | — | — | — |
|
||||
| `amg_embarazo_multiple` | TEXT | — | Catálogo `TipoEmbarazo`: `UNICO, GEMELAR, TRIPLE_O_MAS, NO_REGISTRADO`. | — |
|
||||
| `amg_infeccion_gestacion` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `amg_infeccion_tipo` | TEXT | — | Ver validación cruzada. | — |
|
||||
| `amg_infeccion_hospitalizacion` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `amg_diabetes_gestacional` | BOOL | — | — | — |
|
||||
| `amg_hipertension_preeclampsia` | TEXT | — | Catálogo `TrastornoHipertensivoGestacion`: `NINGUNO, HIPERTENSION_GESTACIONAL, PREECLAMPSIA, ECLAMPSIA, SINDROME_HELLP, NO_REGISTRADO`. | — |
|
||||
| `amg_hipotiroidismo` | BOOL | — | — | — |
|
||||
| `amg_hipertiroidismo` | BOOL | — | — | — |
|
||||
| `amg_incompatibilidad_rh` | BOOL | — | — | — |
|
||||
| `amg_crisis_convulsivas` | BOOL | — | — | — |
|
||||
| `amg_proceso_proinflamatorio` | BOOL | — | — | — |
|
||||
| `amg_enfermedad_autoinmune` | BOOL | — | — | — |
|
||||
| `amg_migrana` | BOOL | — | — | — |
|
||||
| `amg_asma` | BOOL | — | — | — |
|
||||
| `amg_hipoxia_materna` | BOOL | — | — | — |
|
||||
| `amg_estres_agudo` | BOOL | — | — | — |
|
||||
| `amg_trastorno_neurologico` | BOOL | — | — | — |
|
||||
| `amg_liquido_amniotico` | TEXT | — | Catálogo `VolumenLiquidoAmniotico`: `NORMAL, OLIGOHIDRAMNIOS, POLIHIDRAMNIOS, NO_REGISTRADO`. | — |
|
||||
| `amg_medicamentos_gestacion` | TEXT | — | Ver validación cruzada. | — |
|
||||
| `amg_farmaco_riesgo_neurodesarrollo` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `amg_observaciones` | TEXT | — | — | — |
|
||||
| `amg_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
|
||||
| `amg_nlp_version` | TEXT | — | — | — |
|
||||
| `amg_created_at` | DATETIME | — | — | — |
|
||||
| `amg_updated_at` | DATETIME | — | — | — |
|
||||
| `amg_fuente_sistema` | TEXT | — | — | — |
|
||||
| `met_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `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). | — |
|
||||
|
||||
**Validaciones cruzadas de `antecedentes_maternos_gestacion`:**
|
||||
- Si `amg_fuente_antecedente` es `EXPEDIENTE_MATERNO` o `AMBAS`, `amg_id_madre_seudonimo` debe estar presente.
|
||||
- `amg_categoria_peso_materno` debe corresponder al valor de `amg_imc_pregestacional` (Anexo A).
|
||||
- Si `amg_infeccion_gestacion` es falso, `amg_infeccion_tipo` debe quedar vacío y `amg_infeccion_hospitalizacion` debe ser falso o vacío.
|
||||
- Si `amg_farmaco_riesgo_neurodesarrollo` es verdadero, `amg_medicamentos_gestacion` no puede quedar vacío.
|
||||
Solo se guarda el valor medido: el puntaje z y el estado salen de los rangos de referencia por grupo de edad.
|
||||
|
||||
---
|
||||
|
||||
## 8. Tabla `parto_neonatal`
|
||||
## 8. Tabla `eeg_metrica_electrodo` **(análisis del EEG)**
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `pnn_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `pnn_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
|
||||
| `pnn_fuente_antecedente` | TEXT | — | Catálogo `FuenteAntecedenteNeonatal`: `NOTA_RECIEN_NACIDO, NOTA_RESOLUCION_OBSTETRICA, INTERROGATORIO_NM11, AMBAS, NO_LOCALIZADA`. | — |
|
||||
| `pnn_tipo_parto` | TEXT | — | Catálogo `TipoParto`: `VAGINAL_ESPONTANEO, VAGINAL_INSTRUMENTADO, CESAREA_ELECTIVA, CESAREA_URGENCIA, NO_REGISTRADO`. | — |
|
||||
| `pnn_complicaciones_intraparto` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `pnn_complicacion_tipo` | TEXT | — | Catálogo `ComplicacionIntraparto`: `NINGUNA, HIPOXIA, ISQUEMIA, TRAUMA_OBSTETRICO, CIRCULAR_DE_CORDON, SUFRIMIENTO_FETAL_AGUDO, OTRA`. Ver validación cruzada. | — |
|
||||
| `pnn_peso_nacer_g` | INTEGER | g | Entre 400 y 6000. | — |
|
||||
| `pnn_talla_nacer_cm` | FLOAT | cm | Entre 25.0 y 60.0. | — |
|
||||
| `pnn_perimetro_cefalico_nacer_cm` | FLOAT | cm | Entre 25.0 y 42.0. | — |
|
||||
| `pnn_edad_gestacional_sem` | FLOAT | semanas | Entre 22.0 y 43.0. | — |
|
||||
| `pnn_clasificacion_eg` | TEXT | — | Catálogo `ClasificacionEdadGestacional`: `PRETERMINO_EXTREMO, MUY_PRETERMINO, PRETERMINO_TARDIO, TERMINO, POSTERMINO, NO_DETERMINADA`. Ver validación cruzada. | — |
|
||||
| `pnn_tamano_para_eg` | TEXT | — | Catálogo `TamanoParaEdadGestacional`: `PEQUENO, ADECUADO, GRANDE, NO_DETERMINADO`. | — |
|
||||
| `pnn_peso_nacer_zscore` | FLOAT | — | Entre -5.0 y 5.0. | — |
|
||||
| `pnn_apgar_1min` | INTEGER | — | Entre 0 y 10. Ver validación cruzada. | — |
|
||||
| `pnn_apgar_5min` | INTEGER | — | Entre 0 y 10. Ver validación cruzada. | — |
|
||||
| `pnn_ingreso_ucin` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `pnn_dias_ucin` | INTEGER | días | Entre 0 y 365. Ver validación cruzada. | — |
|
||||
| `pnn_encefalopatia_hipoxico_isquemica` | BOOL | — | — | — |
|
||||
| `pnn_hipotermia_nacer` | BOOL | — | — | — |
|
||||
| `pnn_hiperbilirrubinemia` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `pnn_fototerapia` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `pnn_hipoglucemia_neonatal` | BOOL | — | — | — |
|
||||
| `pnn_anoxia` | BOOL | — | — | — |
|
||||
| `pnn_sindrome_congenito` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `pnn_sindrome_congenito_desc` | TEXT | — | Ver validación cruzada. | — |
|
||||
| `pnn_flag_riesgo_neonatal` | BOOL | — | Ver validación cruzada. | — |
|
||||
| `pnn_observaciones` | TEXT | — | — | — |
|
||||
| `pnn_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
|
||||
| `pnn_nlp_version` | TEXT | — | — | — |
|
||||
| `pnn_created_at` | DATETIME | — | — | — |
|
||||
| `pnn_updated_at` | DATETIME | — | — | — |
|
||||
| `pnn_fuente_sistema` | TEXT | — | — | — |
|
||||
|
||||
**Validaciones cruzadas de `parto_neonatal`:**
|
||||
- `pnn_clasificacion_eg` debe corresponder a `pnn_edad_gestacional_sem` (Anexo A).
|
||||
- `pnn_apgar_5min` no puede ser menor que `pnn_apgar_1min`.
|
||||
- Si `pnn_dias_ucin` es mayor que 0, `pnn_ingreso_ucin` debe ser verdadero.
|
||||
- Si `pnn_fototerapia` es verdadero, `pnn_hiperbilirrubinemia` debe ser verdadero.
|
||||
- Si `pnn_complicaciones_intraparto` es falso, `pnn_complicacion_tipo` debe quedar vacío o en `NINGUNA`.
|
||||
- Si `pnn_sindrome_congenito` es falso, `pnn_sindrome_congenito_desc` debe quedar vacío.
|
||||
- `pnn_flag_riesgo_neonatal` debe ser verdadero si se cumple al menos una de estas cuatro condiciones: `pnn_apgar_5min < 7`, `pnn_ingreso_ucin` verdadero, `pnn_encefalopatia_hipoxico_isquemica` verdadero, o `pnn_anoxia` verdadero. Si no se cumple ninguna, debe ser falso.
|
||||
|
||||
---
|
||||
|
||||
## 9. Tabla `eeg_segmento`
|
||||
|
||||
Añadida 2026-10-19, junto con `eeg_utilizable` e `instrumento_aplicado`,
|
||||
para que `indicadores_kit` pueda calcular sus indicadores TEA (el campo
|
||||
que falta en su `tea/etl.py`/`tea/mapeo.py`, confirmado leyendo el fork).
|
||||
Una fila por segmento de un estudio de EEG (por ejemplo, el tramo de
|
||||
fotoestimulación o el tramo de sueño dentro del registro). Solo
|
||||
`seg_eeg_id`, `seg_estado` y `seg_duracion_s` los lee el kit hoy (K7, K8);
|
||||
el resto queda sin mapear pero existe en la fuente real (confirmado
|
||||
contra `hospital.eeg_segmento` en el espejo MySQL del hospital).
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `seg_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `seg_eeg_id` | TEXT | — | — | → `eeg_estudio.eeg_id` |
|
||||
| `seg_estado` | TEXT | — | Código del segmento, por ejemplo `FOTOESTIMULACION` o `SUENO`. | — |
|
||||
| `seg_inicio_s` | FLOAT | s | — | — |
|
||||
| `seg_fin_s` | FLOAT | s | — | — |
|
||||
| `seg_duracion_s` | FLOAT | s | — | — |
|
||||
| `seg_fuente` | TEXT | — | — | — |
|
||||
| `seg_frecuencia_flash_hz` | FLOAT | Hz | — | — |
|
||||
| `seg_n_destellos` | INTEGER | — | — | — |
|
||||
| `seg_cobertura` | FLOAT | — | — | — |
|
||||
| `seg_rms_uv` | FLOAT | µV | — | — |
|
||||
| `seg_emg` | FLOAT | — | — | — |
|
||||
| `seg_p2p_max_uv` | FLOAT | µV | — | — |
|
||||
|
||||
---
|
||||
|
||||
## 10. Tabla `instrumento_aplicado`
|
||||
|
||||
Añadida 2026-10-19, ver nota de `eeg_segmento`. Una fila por instrumento
|
||||
aplicado dentro de una evaluación psicológica (por ejemplo, un
|
||||
cuestionario a un informante distinto del niño).
|
||||
|
||||
| Variable | Tipo | Unidad | Validación | Llave foránea |
|
||||
|---|---|---|---|---|
|
||||
| `ins_id` | VARCHAR(36), llave primaria | — | — | — |
|
||||
| `ins_psi_id` | TEXT | — | Puede ser nulo: el kit no lo exige. | → `evaluacion_psicologica.psi_id` |
|
||||
| `ins_instrumento` | TEXT | — | Código del instrumento. | — |
|
||||
| `ins_informante` | TEXT | — | Código de quién lo respondió. | — |
|
||||
| `ins_area` | TEXT | — | Código del área evaluada. | — |
|
||||
| `ins_interpretacion` | TEXT | — | Código de la interpretación. | — |
|
||||
|
||||
---
|
||||
|
||||
## Anexo A — Funciones de referencia usadas en varias validaciones cruzadas
|
||||
|
||||
**Ventana madurativa según edad en meses** (usada en `ordenes_estudio`, `nota_medica`, `evaluacion_psicologica`):
|
||||
|
||||
| Edad en meses | Ventana |
|
||||
|---|---|
|
||||
| 16.0 a 23.9 | `V1_16_23` |
|
||||
| 24.0 a 30.9 | `V2_24_30` |
|
||||
| 31.0 a 36.0 | `V3_31_36` |
|
||||
| Cualquier otro valor | `FUERA_DE_RANGO` |
|
||||
|
||||
**Categoría de peso materno según IMC pregestacional** (usada en `antecedentes_maternos_gestacion`, clasificación estándar de adultos de la OMS):
|
||||
|
||||
| IMC (kg/m²) | Categoría |
|
||||
|---|---|
|
||||
| Menor a 18.5 | `BAJO_PESO` |
|
||||
| 18.5 a 24.9 | `NORMAL` |
|
||||
| 25.0 a 29.9 | `SOBREPESO` |
|
||||
| 30.0 a 34.9 | `OBESIDAD_I` |
|
||||
| 35.0 a 39.9 | `OBESIDAD_II` |
|
||||
| 40.0 o más | `OBESIDAD_III` |
|
||||
|
||||
**Clasificación por edad gestacional al nacer** (usada en `parto_neonatal`):
|
||||
|
||||
| Semanas de gestación | Clasificación |
|
||||
|---|---|
|
||||
| Menos de 28.0 | `PRETERMINO_EXTREMO` |
|
||||
| 28.0 a 31.9 | `MUY_PRETERMINO` |
|
||||
| 32.0 a 36.9 | `PRETERMINO_TARDIO` |
|
||||
| 37.0 a 41.9 | `TERMINO` |
|
||||
| 42.0 o más | `POSTERMINO` |
|
||||
|
||||
---
|
||||
|
||||
## Anexo B — Validación de los códigos del ADOS-2 (`evaluacion_psicologica`)
|
||||
|
||||
El campo `psi_ados2_modulo` fija qué módulo del ADOS-2 se aplicó al paciente. Cada
|
||||
módulo usa un subconjunto distinto de códigos, dentro de los dos dominios que ya
|
||||
existen como columnas agregadas: `SA` (Interacción social recíproca / comunicación) y
|
||||
`RRB` (Conductas restringidas y repetitivas). Equivalencia entre el catálogo
|
||||
`ModuloAdos2` y los módulos del manual: `TODDLER` = Módulo T, `MODULO_1` = Módulo 1,
|
||||
`MODULO_2` = Módulo 2.
|
||||
|
||||
### B.1 Rango válido de cada código, por módulo
|
||||
|
||||
| Código | Dominio | Módulo T | Módulo 1 | Módulo 2 |
|
||||
|---|---|---|---|---|
|
||||
| a2 | SA | 0–3 | 0–3 | — |
|
||||
| a6 | SA | — | — | 0–3 |
|
||||
| a7 | SA | 0–3 | 0–3 | 0–3, 8 |
|
||||
| a8 | SA | 0–3, 8 | 0–2, 8 | — |
|
||||
| b1 | SA | 0–3 | 0, 2 | 0, 2 |
|
||||
| b2 | SA | — | — | 0–2 |
|
||||
| b3 | SA | — | 0–2 | 0–3 |
|
||||
| b4 | SA | 0–3 | 0–3 | — |
|
||||
| b5 | SA | 0–3 | 0–3 | 0–2 |
|
||||
| b6 | SA | 0–3 | — | 0–2 |
|
||||
| b7 | SA | 0–3 | — | — |
|
||||
| b8 | SA | 0–3 | — | 0–3 |
|
||||
| b9 | SA | 0–3 | 0–2 | — |
|
||||
| b10 | SA | — | 0–2 | — |
|
||||
| b11 | SA | — | 0–3 | 0–3 |
|
||||
| b12 | SA | 0–3 | 0–3 | 0–3 |
|
||||
| b13 | SA | 0–3 | — | — |
|
||||
| b14 | SA | 0–3 | — | — |
|
||||
| b15 | SA | 0–3 | — | — |
|
||||
| b16b | SA | 0–3, 7, 8 | — | — |
|
||||
| b18 | SA | 0–3 | — | — |
|
||||
| a3 | RRB | 0–3, 8 | 0–2, 8 | — |
|
||||
| a4 | RRB | — | — | 0–3 |
|
||||
| a5 | RRB | — | 0–3, 8 | — |
|
||||
| d1 | RRB | 0–3 | 0–3 | 0–3 |
|
||||
| d2 | RRB | 0–3 | 0–3 | 0–3 |
|
||||
| d4 | RRB | — | 0–3 | 0–3 |
|
||||
| d5 | RRB | 0–3 | — | — |
|
||||
|
||||
Nota de lectura: "0–3, 8" significa que, además de los valores enteros 0 a 3, el
|
||||
manual permite el código adicional 8 en ese ítem y módulo. Una celda con "—" quiere
|
||||
decir que ese código no existe para ese módulo (ver regla de pertenencia, B.3).
|
||||
|
||||
**Validación de rango por código:** si la columna correspondiente al código no está
|
||||
vacía, su valor debe ser un entero dentro del conjunto permitido para el módulo
|
||||
indicado en `psi_ados2_modulo`. Cualquier valor fuera del conjunto (incluido un
|
||||
entero "razonable" pero no listado, como un 4 donde el máximo es 3) se rechaza.
|
||||
|
||||
### B.2 Validación de completitud del módulo
|
||||
|
||||
Todos los códigos que pertenecen al módulo indicado en `psi_ados2_modulo` (columna
|
||||
correspondiente en la tabla de B.1) deben tener un valor, es decir, no pueden quedar
|
||||
vacíos. Si al menos uno de los códigos propios del módulo está vacío, el renglón se
|
||||
considera incompleto y se rechaza.
|
||||
|
||||
Ejemplo: si `psi_ados2_modulo = MODULO_1`, deben estar llenas las columnas
|
||||
`psi_ados2_sa_a2, sa_a7, sa_a8, sa_b1, sa_b3, sa_b4, sa_b5, sa_b9, sa_b10, sa_b11,
|
||||
sa_b12, rrb_a3, rrb_a5, rrb_d1, rrb_d2, rrb_d4`.
|
||||
|
||||
### B.3 Validación de pertenencia a módulo
|
||||
|
||||
Los códigos que **no** pertenecen al módulo indicado (celda "—" en B.1 para ese
|
||||
módulo) deben quedar vacíos. Si alguno de esos códigos trae un valor, el renglón se
|
||||
rechaza, porque ese código no corresponde a la versión de la prueba aplicada.
|
||||
|
||||
Ejemplo: si `psi_ados2_modulo = TODDLER`, las columnas `psi_ados2_sa_b2,
|
||||
sa_b3, sa_b10, sa_b11, rrb_a4, rrb_a5, rrb_d4` (propias de otros módulos) deben
|
||||
quedar vacías.
|
||||
|
||||
---
|
||||
|
||||
## Anexo C — Llaves foráneas (resumen)
|
||||
|
||||
| Columna | Tabla y columna referenciada |
|
||||
|---|---|
|
||||
| `ordenes_estudio.ord_pac_id` | `pacientes.pac_id` |
|
||||
| `ordenes_estudio.ord_nota_medica_id` | `nota_medica.nm_id` |
|
||||
| `nota_medica.nm_pac_id` | `pacientes.pac_id` |
|
||||
| `nota_medica.nm_nota_previa_id` | `nota_medica.nm_id` (autorreferencia) |
|
||||
| `evaluacion_psicologica.psi_ord_id` | `ordenes_estudio.ord_id` |
|
||||
| `evaluacion_psicologica.psi_pac_id` | `pacientes.pac_id` |
|
||||
| `potenciales_evocados_auditivos.pea_ord_id` | `ordenes_estudio.ord_id` |
|
||||
| `potenciales_evocados_auditivos.pea_pac_id` | `pacientes.pac_id` |
|
||||
| `eeg_estudio.eeg_ord_id` | `ordenes_estudio.ord_id` |
|
||||
| `eeg_estudio.eeg_pac_id` | `pacientes.pac_id` |
|
||||
| `antecedentes_maternos_gestacion.amg_pac_id` | `pacientes.pac_id` |
|
||||
| `parto_neonatal.pnn_pac_id` | `pacientes.pac_id` |
|
||||
| `eeg_segmento.seg_eeg_id` | `eeg_estudio.eeg_id` |
|
||||
| `instrumento_aplicado.ins_psi_id` | `evaluacion_psicologica.psi_id` |
|
||||
| `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 | — | — |
|
||||
|
||||
@@ -75,14 +75,12 @@ def test_tea_tables_registered():
|
||||
# Staging: fed by the hospital source via the import pipeline.
|
||||
"pacientes",
|
||||
"ordenes_estudio",
|
||||
"nota_medica",
|
||||
"evaluacion_psicologica",
|
||||
"potenciales_evocados_auditivos",
|
||||
"eeg_estudio",
|
||||
"eeg_segmento",
|
||||
"instrumento_aplicado",
|
||||
"antecedentes_maternos_gestacion",
|
||||
"parto_neonatal",
|
||||
"mchat",
|
||||
"ados2",
|
||||
"evaluacion_neuropediatrica",
|
||||
"eeg",
|
||||
"eeg_metrica",
|
||||
"eeg_metrica_electrodo",
|
||||
# indicadores_kit CDM, built from staging by the webapi.orquestacion graph.
|
||||
*INDICADORES_KIT_CDM,
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ CaCu, CaMa, TEA y gobernanza. El esquema está en `../Core`. Cambiar de motor
|
||||
| `repository.py` | `Repository`: `get`, `list`, `iter_all`, `count`, `create`, `bulk_upsert` (rechaza o actualiza por llave natural) y `open_session` para escribir varias tablas en una transacción. |
|
||||
| `identity.py` | Tras insertar ids explícitos, adelanta la secuencia en PostgreSQL (los demás motores lo hacen solos). |
|
||||
| `cacu/`, `cama/`, `tea/`, `governance/` | El ambiente de Alembic de cada base y una instancia de `Repository` por tabla (`persistance.cacu.paciente_repository`, ...). |
|
||||
| `aristas/`, `materializador.py` | Repositorios del ciclo de indicadores (`webapi.orquestacion`), por capa: bronce, plata y oro. |
|
||||
| `edges/`, `materializer.py` | Repositorios del ciclo de indicadores (`webapi.orchestration`), por capa: bronce, plata y oro. |
|
||||
|
||||
WebApi y `models` usan las mismas instancias de repositorio; no hay otra ruta
|
||||
a las tablas.
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
"""Oro: el registro (parámetros, periodos, definiciones), los reportes de indicadores y las cohortes con sus riesgos."""
|
||||
|
||||
from persistance.aristas.comun import RegistroRepository
|
||||
from persistance.aristas.oro.calculo import CalculoRepository, MeasureReportRepository, guardar_reporte_en
|
||||
from persistance.aristas.oro.publicacion import PublicacionRepository, sincronizar_publicacion_en
|
||||
from persistance.aristas.oro.cohortes import (
|
||||
ERROR,
|
||||
FINAL,
|
||||
PRELIMINAR,
|
||||
PROCEDENCIA,
|
||||
CohortBuild,
|
||||
CohorteRepository,
|
||||
CohortMember,
|
||||
PatientMembership,
|
||||
PatientRisk,
|
||||
RiesgoFueraDeCohorte,
|
||||
RiskHorizon,
|
||||
cambiar_estado_en,
|
||||
guardar_armado_en,
|
||||
guardar_lote_en,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"ERROR",
|
||||
"FINAL",
|
||||
"PRELIMINAR",
|
||||
"PROCEDENCIA",
|
||||
"CalculoRepository",
|
||||
"CohortBuild",
|
||||
"CohorteRepository",
|
||||
"CohortMember",
|
||||
"MeasureReportRepository",
|
||||
"PatientMembership",
|
||||
"PatientRisk",
|
||||
"PublicacionRepository",
|
||||
"RegistroRepository",
|
||||
"RiesgoFueraDeCohorte",
|
||||
"RiskHorizon",
|
||||
"cambiar_estado_en",
|
||||
"guardar_armado_en",
|
||||
"guardar_lote_en",
|
||||
"guardar_reporte_en",
|
||||
"sincronizar_publicacion_en",
|
||||
]
|
||||
@@ -1,37 +0,0 @@
|
||||
"""Plata: los catálogos, la carga del staging directo, `v_persona`, el periodo de observación, la verificación y la línea de tiempo."""
|
||||
|
||||
from persistance.aristas.plata.carga import (
|
||||
CargaRepository,
|
||||
abrir_carga,
|
||||
cerrar_carga,
|
||||
guardar_carga_en,
|
||||
)
|
||||
from persistance.aristas.plata.catalogos import CatalogoRepository
|
||||
from persistance.aristas.plata.observacion import ObservacionRepository
|
||||
from persistance.aristas.plata.procedimientos import guardar_plata_en
|
||||
from persistance.aristas.plata.timeline import (
|
||||
TIMELINE_COLUMNS,
|
||||
TimelineContractError,
|
||||
TimelineQuery,
|
||||
TimelineQueryMissing,
|
||||
TimelineRepository,
|
||||
)
|
||||
from persistance.aristas.plata.vinculos import VinculosRepository
|
||||
from persistance.aristas.plata.vistas import VistasRepository
|
||||
|
||||
__all__ = [
|
||||
"CargaRepository",
|
||||
"CatalogoRepository",
|
||||
"ObservacionRepository",
|
||||
"TIMELINE_COLUMNS",
|
||||
"TimelineContractError",
|
||||
"TimelineQuery",
|
||||
"TimelineQueryMissing",
|
||||
"TimelineRepository",
|
||||
"VinculosRepository",
|
||||
"VistasRepository",
|
||||
"abrir_carga",
|
||||
"cerrar_carga",
|
||||
"guardar_carga_en",
|
||||
"guardar_plata_en",
|
||||
]
|
||||
@@ -13,14 +13,14 @@ from enum import StrEnum
|
||||
|
||||
|
||||
class Layer(StrEnum):
|
||||
BRONZE = "bronce"
|
||||
SILVER = "plata"
|
||||
GOLD = "oro"
|
||||
MODEL = "modelo"
|
||||
BRONZE = "bronze"
|
||||
SILVER = "silver"
|
||||
GOLD = "gold"
|
||||
MODEL = "model"
|
||||
|
||||
|
||||
class Owner(StrEnum):
|
||||
EXTERNAL = "externo"
|
||||
EXTERNAL = "external"
|
||||
PYTHON = "python"
|
||||
DBT = "dbt"
|
||||
|
||||
|
||||
@@ -40,18 +40,24 @@ from core.cacu.models import (
|
||||
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
|
||||
from persistance.aristas.bronce import StagingRepository
|
||||
from persistance.aristas.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
from persistance.aristas.comun import RegistroRepository
|
||||
from persistance.materializador import Materializador
|
||||
from persistance.aristas.oro import CalculoRepository, CohorteRepository, MeasureReportRepository, PublicacionRepository
|
||||
from persistance.aristas.plata import (
|
||||
CargaRepository,
|
||||
CatalogoRepository,
|
||||
ObservacionRepository,
|
||||
from persistance.edges.bronze import StagingRepository
|
||||
from persistance.edges.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
from persistance.edges.common import ReferenceRepository
|
||||
from persistance.materializer import Materializer
|
||||
from persistance.edges.gold import (
|
||||
CalculationRepository,
|
||||
CohortRepository,
|
||||
MeasureHistoryRepository,
|
||||
MeasureReportRepository,
|
||||
PublicationRepository,
|
||||
)
|
||||
from persistance.edges.silver import (
|
||||
LoadRepository,
|
||||
CatalogRepository,
|
||||
ObservationRepository,
|
||||
TimelineRepository,
|
||||
VinculosRepository,
|
||||
VistasRepository,
|
||||
LinksRepository,
|
||||
ViewsRepository,
|
||||
)
|
||||
from persistance.db import get_cacu_session
|
||||
from persistance.repository import Repository
|
||||
@@ -65,23 +71,23 @@ biometria_hematica_repository = Repository(get_cacu_session, BiometriaHematica)
|
||||
episodio_clinico_repository = Repository(get_cacu_session, EpisodioClinico)
|
||||
|
||||
# indicadores_kit (Core/docs/ADR-004). Se leen con get/list/count; lo que
|
||||
# se escribe va por métodos de subclases (persistance/aristas, por capa).
|
||||
# se escribe va por métodos de subclases (persistance/edges, por capa).
|
||||
persona_repository = Repository(get_cacu_session, Persona)
|
||||
periodo_observacion_repository = RegistroRepository(get_cacu_session, PeriodoObservacion)
|
||||
carga_repository = CargaRepository(get_cacu_session, Carga, persona=Persona, procedimiento=Procedimiento, observacion=Observacion)
|
||||
def_parametro_repository = RegistroRepository(get_cacu_session, DefParametro)
|
||||
dim_periodo_repository = RegistroRepository(get_cacu_session, DimPeriodo)
|
||||
dim_fecha_repository = RegistroRepository(get_cacu_session, DimFecha)
|
||||
dim_grupo_edad_repository = RegistroRepository(get_cacu_session, DimGrupoEdad)
|
||||
periodo_observacion_repository = ReferenceRepository(get_cacu_session, PeriodoObservacion)
|
||||
carga_repository = LoadRepository(get_cacu_session, Carga, persona=Persona, procedimiento=Procedimiento, observacion=Observacion)
|
||||
def_parametro_repository = ReferenceRepository(get_cacu_session, DefParametro)
|
||||
dim_periodo_repository = ReferenceRepository(get_cacu_session, DimPeriodo)
|
||||
dim_fecha_repository = ReferenceRepository(get_cacu_session, DimFecha)
|
||||
dim_grupo_edad_repository = ReferenceRepository(get_cacu_session, DimGrupoEdad)
|
||||
# El oro por unidad y su catálogo (§6f, MD-19): los catálogos se reemplazan enteros desde los TOML del kit.
|
||||
cat_measure_repository = RegistroRepository(get_cacu_session, CatMeasure)
|
||||
cat_measure_resultado_repository = RegistroRepository(get_cacu_session, CatMeasureResultado)
|
||||
cat_measure_valor_repository = RegistroRepository(get_cacu_session, CatMeasureValor)
|
||||
cat_measure_grupo_repository = RegistroRepository(get_cacu_session, CatMeasureGrupo)
|
||||
cat_estrato_repository = RegistroRepository(get_cacu_session, CatEstrato)
|
||||
cat_estrato_valor_repository = RegistroRepository(get_cacu_session, CatEstratoValor)
|
||||
cat_measure_estrato_repository = RegistroRepository(get_cacu_session, CatMeasureEstrato)
|
||||
publicacion_repository = PublicacionRepository(
|
||||
cat_measure_repository = ReferenceRepository(get_cacu_session, CatMeasure)
|
||||
cat_measure_resultado_repository = ReferenceRepository(get_cacu_session, CatMeasureResultado)
|
||||
cat_measure_valor_repository = ReferenceRepository(get_cacu_session, CatMeasureValor)
|
||||
cat_measure_grupo_repository = ReferenceRepository(get_cacu_session, CatMeasureGrupo)
|
||||
cat_estrato_repository = ReferenceRepository(get_cacu_session, CatEstrato)
|
||||
cat_estrato_valor_repository = ReferenceRepository(get_cacu_session, CatEstratoValor)
|
||||
cat_measure_estrato_repository = ReferenceRepository(get_cacu_session, CatMeasureEstrato)
|
||||
publication_repository = PublicationRepository(
|
||||
get_cacu_session, (CatEstrato, CatEstratoValor, CatMeasure, CatMeasureResultado, CatMeasureValor, CatMeasureGrupo, CatMeasureEstrato)
|
||||
)
|
||||
measure_report_unidad_repository = Repository(get_cacu_session, MeasureReportUnidad)
|
||||
@@ -93,20 +99,23 @@ cat_valor_repository = Repository(get_cacu_session, CatValor)
|
||||
procedimiento_repository = Repository(get_cacu_session, Procedimiento)
|
||||
observacion_repository = Repository(get_cacu_session, Observacion)
|
||||
|
||||
# Las aristas del grafo (persistance/aristas): una sesión por operación.
|
||||
# Las aristas del grafo (persistance/edges): una sesión por operación.
|
||||
staging_repository = StagingRepository(get_cacu_session)
|
||||
catalogo_repository = CatalogoRepository(get_cacu_session, CatEstudio, CatResultado, CatValor)
|
||||
calculo_repository = CalculoRepository(get_cacu_session, MeasureReport, periodo=DimPeriodo)
|
||||
observar_repository = ObservacionRepository(get_cacu_session, PeriodoObservacion)
|
||||
vistas_repository = VistasRepository(get_cacu_session)
|
||||
vinculos_repository = VinculosRepository(get_cacu_session)
|
||||
catalog_repository = CatalogRepository(get_cacu_session, CatEstudio, CatResultado, CatValor)
|
||||
calculation_repository = CalculationRepository(get_cacu_session, MeasureReport, periodo=DimPeriodo)
|
||||
history_repository = MeasureHistoryRepository(get_cacu_session, MeasureReport, unit_model=MeasureReportUnidad,
|
||||
stratum_model=MeasureReportUnidadEstrato,
|
||||
value_model=CatEstratoValor)
|
||||
observation_period_repository = ObservationRepository(get_cacu_session, PeriodoObservacion)
|
||||
views_repository = ViewsRepository(get_cacu_session)
|
||||
links_repository = LinksRepository(get_cacu_session)
|
||||
# dbt's timeline view and compiled queries; `with_query` still binds another timeline query.
|
||||
timeline_repository = DbtTimelineRepository(get_cacu_session, "cacu")
|
||||
dbt_query_repository = DbtQueryRepository(get_cacu_session)
|
||||
cohorte_repository = CohorteRepository(
|
||||
cohort_repository = CohortRepository(
|
||||
get_cacu_session,
|
||||
TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, EvaluacionRiesgo),
|
||||
)
|
||||
|
||||
# La E/S de las transformaciones de MD-20 (T0): una sesión, la función y un cuerpo de escritura.
|
||||
materializador = Materializador(get_cacu_session)
|
||||
materializer = Materializer(get_cacu_session)
|
||||
|
||||
@@ -40,18 +40,24 @@ from core.cama.models import (
|
||||
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
|
||||
from persistance.aristas.bronce import StagingRepository
|
||||
from persistance.aristas.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
from persistance.aristas.comun import RegistroRepository
|
||||
from persistance.materializador import Materializador
|
||||
from persistance.aristas.oro import CalculoRepository, CohorteRepository, MeasureReportRepository, PublicacionRepository
|
||||
from persistance.aristas.plata import (
|
||||
CargaRepository,
|
||||
CatalogoRepository,
|
||||
ObservacionRepository,
|
||||
from persistance.edges.bronze import StagingRepository
|
||||
from persistance.edges.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
from persistance.edges.common import ReferenceRepository
|
||||
from persistance.materializer import Materializer
|
||||
from persistance.edges.gold import (
|
||||
CalculationRepository,
|
||||
CohortRepository,
|
||||
MeasureHistoryRepository,
|
||||
MeasureReportRepository,
|
||||
PublicationRepository,
|
||||
)
|
||||
from persistance.edges.silver import (
|
||||
LoadRepository,
|
||||
CatalogRepository,
|
||||
ObservationRepository,
|
||||
TimelineRepository,
|
||||
VinculosRepository,
|
||||
VistasRepository,
|
||||
LinksRepository,
|
||||
ViewsRepository,
|
||||
)
|
||||
from persistance.db import get_cama_session
|
||||
from persistance.repository import Repository
|
||||
@@ -65,23 +71,23 @@ biometria_hematica_repository = Repository(get_cama_session, BiometriaHematica)
|
||||
episodio_clinico_repository = Repository(get_cama_session, EpisodioClinico)
|
||||
|
||||
# indicadores_kit (Core/docs/ADR-004). Se leen con get/list/count; lo que
|
||||
# se escribe va por métodos de subclases (persistance/aristas, por capa).
|
||||
# se escribe va por métodos de subclases (persistance/edges, por capa).
|
||||
persona_repository = Repository(get_cama_session, Persona)
|
||||
periodo_observacion_repository = RegistroRepository(get_cama_session, PeriodoObservacion)
|
||||
carga_repository = CargaRepository(get_cama_session, Carga, persona=Persona, procedimiento=Procedimiento, observacion=Observacion)
|
||||
def_parametro_repository = RegistroRepository(get_cama_session, DefParametro)
|
||||
dim_periodo_repository = RegistroRepository(get_cama_session, DimPeriodo)
|
||||
dim_fecha_repository = RegistroRepository(get_cama_session, DimFecha)
|
||||
dim_grupo_edad_repository = RegistroRepository(get_cama_session, DimGrupoEdad)
|
||||
periodo_observacion_repository = ReferenceRepository(get_cama_session, PeriodoObservacion)
|
||||
carga_repository = LoadRepository(get_cama_session, Carga, persona=Persona, procedimiento=Procedimiento, observacion=Observacion)
|
||||
def_parametro_repository = ReferenceRepository(get_cama_session, DefParametro)
|
||||
dim_periodo_repository = ReferenceRepository(get_cama_session, DimPeriodo)
|
||||
dim_fecha_repository = ReferenceRepository(get_cama_session, DimFecha)
|
||||
dim_grupo_edad_repository = ReferenceRepository(get_cama_session, DimGrupoEdad)
|
||||
# El oro por unidad y su catálogo (§6f, MD-19): los catálogos se reemplazan enteros desde los TOML del kit.
|
||||
cat_measure_repository = RegistroRepository(get_cama_session, CatMeasure)
|
||||
cat_measure_resultado_repository = RegistroRepository(get_cama_session, CatMeasureResultado)
|
||||
cat_measure_valor_repository = RegistroRepository(get_cama_session, CatMeasureValor)
|
||||
cat_measure_grupo_repository = RegistroRepository(get_cama_session, CatMeasureGrupo)
|
||||
cat_estrato_repository = RegistroRepository(get_cama_session, CatEstrato)
|
||||
cat_estrato_valor_repository = RegistroRepository(get_cama_session, CatEstratoValor)
|
||||
cat_measure_estrato_repository = RegistroRepository(get_cama_session, CatMeasureEstrato)
|
||||
publicacion_repository = PublicacionRepository(
|
||||
cat_measure_repository = ReferenceRepository(get_cama_session, CatMeasure)
|
||||
cat_measure_resultado_repository = ReferenceRepository(get_cama_session, CatMeasureResultado)
|
||||
cat_measure_valor_repository = ReferenceRepository(get_cama_session, CatMeasureValor)
|
||||
cat_measure_grupo_repository = ReferenceRepository(get_cama_session, CatMeasureGrupo)
|
||||
cat_estrato_repository = ReferenceRepository(get_cama_session, CatEstrato)
|
||||
cat_estrato_valor_repository = ReferenceRepository(get_cama_session, CatEstratoValor)
|
||||
cat_measure_estrato_repository = ReferenceRepository(get_cama_session, CatMeasureEstrato)
|
||||
publication_repository = PublicationRepository(
|
||||
get_cama_session, (CatEstrato, CatEstratoValor, CatMeasure, CatMeasureResultado, CatMeasureValor, CatMeasureGrupo, CatMeasureEstrato)
|
||||
)
|
||||
measure_report_unidad_repository = Repository(get_cama_session, MeasureReportUnidad)
|
||||
@@ -93,20 +99,23 @@ cat_valor_repository = Repository(get_cama_session, CatValor)
|
||||
procedimiento_repository = Repository(get_cama_session, Procedimiento)
|
||||
observacion_repository = Repository(get_cama_session, Observacion)
|
||||
|
||||
# Las aristas del grafo (persistance/aristas): una sesión por operación.
|
||||
# Las aristas del grafo (persistance/edges): una sesión por operación.
|
||||
staging_repository = StagingRepository(get_cama_session)
|
||||
catalogo_repository = CatalogoRepository(get_cama_session, CatEstudio, CatResultado, CatValor)
|
||||
calculo_repository = CalculoRepository(get_cama_session, MeasureReport, periodo=DimPeriodo)
|
||||
observar_repository = ObservacionRepository(get_cama_session, PeriodoObservacion)
|
||||
vistas_repository = VistasRepository(get_cama_session)
|
||||
vinculos_repository = VinculosRepository(get_cama_session)
|
||||
catalog_repository = CatalogRepository(get_cama_session, CatEstudio, CatResultado, CatValor)
|
||||
calculation_repository = CalculationRepository(get_cama_session, MeasureReport, periodo=DimPeriodo)
|
||||
history_repository = MeasureHistoryRepository(get_cama_session, MeasureReport, unit_model=MeasureReportUnidad,
|
||||
stratum_model=MeasureReportUnidadEstrato,
|
||||
value_model=CatEstratoValor)
|
||||
observation_period_repository = ObservationRepository(get_cama_session, PeriodoObservacion)
|
||||
views_repository = ViewsRepository(get_cama_session)
|
||||
links_repository = LinksRepository(get_cama_session)
|
||||
# dbt's timeline view and compiled queries; `with_query` still binds another timeline query.
|
||||
timeline_repository = DbtTimelineRepository(get_cama_session, "cama")
|
||||
dbt_query_repository = DbtQueryRepository(get_cama_session)
|
||||
cohorte_repository = CohorteRepository(
|
||||
cohort_repository = CohortRepository(
|
||||
get_cama_session,
|
||||
TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, EvaluacionRiesgo),
|
||||
)
|
||||
|
||||
# La E/S de las transformaciones de MD-20 (T0): una sesión, la función y un cuerpo de escritura.
|
||||
materializador = Materializador(get_cama_session)
|
||||
materializer = Materializer(get_cama_session)
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
"""Bronce: el staging, como lo deja la ingesta. Aquí solo se lee."""
|
||||
|
||||
from persistance.aristas.bronce.staging import StagingRepository
|
||||
from persistance.edges.bronze.staging import StagingRepository
|
||||
|
||||
__all__ = ["StagingRepository"]
|
||||
+1
-1
@@ -18,7 +18,7 @@ class StagingRepository(Repository):
|
||||
def __init__(self, session_factory):
|
||||
super().__init__(session_factory, None)
|
||||
|
||||
def leer(self, modelos: Mapping[str, type[SQLModel]]) -> dict[str, list]:
|
||||
def read(self, modelos: Mapping[str, type[SQLModel]]) -> dict[str, list]:
|
||||
"""Todas las filas de cada tabla, por nombre, en una sola sesión y en el orden de su llave primaria."""
|
||||
with self._session_factory() as sesion:
|
||||
return {
|
||||
+12
-12
@@ -12,23 +12,23 @@ from sqlmodel import Session, SQLModel, delete
|
||||
|
||||
from persistance.repository import Repository
|
||||
|
||||
FilaT = TypeVar("FilaT", bound=SQLModel)
|
||||
RowT = TypeVar("RowT", bound=SQLModel)
|
||||
|
||||
|
||||
class RegistroRepository(Repository[FilaT]):
|
||||
class ReferenceRepository(Repository[RowT]):
|
||||
"""Una tabla de registro: se reconstruye desde archivos o se completa, nunca se edita a mano.
|
||||
|
||||
Sirve a parámetros, periodos, tablas de apoyo (fechas, grupos de edad)
|
||||
y definiciones de indicadores. Cada operación es una sesión.
|
||||
"""
|
||||
|
||||
def reemplazar(self, filas: Iterable[FilaT]) -> int:
|
||||
def replace_all(self, filas: Iterable[RowT]) -> int:
|
||||
"""Deja la tabla con exactamente estas filas. Devuelve cuántas. Todo o nada."""
|
||||
with self._session_factory() as sesion:
|
||||
return reemplazar_en(sesion, self.model, filas)
|
||||
return replace_in(sesion, self.model, filas)
|
||||
|
||||
def reemplazar_en_bloque(self, filas: Iterable[FilaT]) -> int:
|
||||
"""Como `reemplazar`, con un solo INSERT: para tablas grandes de apoyo (`dim_fecha`, decenas de miles de días).
|
||||
def replace_in_bulk(self, filas: Iterable[RowT]) -> int:
|
||||
"""Como `replace_all`, con un solo INSERT: para tablas grandes de apoyo (`dim_fecha`, decenas de miles de días).
|
||||
|
||||
Las filas pueden venir como modelos o como diccionarios de sus columnas.
|
||||
"""
|
||||
@@ -44,18 +44,18 @@ class RegistroRepository(Repository[FilaT]):
|
||||
raise
|
||||
return len(filas)
|
||||
|
||||
def agregar_faltantes(self, filas: Iterable[FilaT]) -> int:
|
||||
def add_missing(self, filas: Iterable[RowT]) -> int:
|
||||
"""Agrega las filas cuya llave no está y no toca las demás. Devuelve cuántas agregó.
|
||||
|
||||
Para tablas a las que otras apuntan (los reportes apuntan a
|
||||
`dim_periodo`): reemplazarlas violaría esas llaves foráneas.
|
||||
"""
|
||||
with self._session_factory() as sesion:
|
||||
return agregar_faltantes_en(sesion, self.model, filas)
|
||||
return add_missing_in(sesion, self.model, filas)
|
||||
|
||||
|
||||
def reemplazar_en(sesion: Session, modelo: type[FilaT], filas: Iterable[FilaT]) -> int:
|
||||
"""El cuerpo de `RegistroRepository.reemplazar`, sobre una sesión que se recibe."""
|
||||
def replace_in(sesion: Session, modelo: type[RowT], filas: Iterable[RowT]) -> int:
|
||||
"""El cuerpo de `ReferenceRepository.reemplazar`, sobre una sesión que se recibe."""
|
||||
filas = list(filas)
|
||||
try:
|
||||
sesion.exec(delete(modelo))
|
||||
@@ -67,8 +67,8 @@ def reemplazar_en(sesion: Session, modelo: type[FilaT], filas: Iterable[FilaT])
|
||||
return len(filas)
|
||||
|
||||
|
||||
def agregar_faltantes_en(sesion: Session, modelo: type[FilaT], filas: Iterable[FilaT]) -> int:
|
||||
"""El cuerpo de `RegistroRepository.agregar_faltantes`, sobre una sesión que se recibe."""
|
||||
def add_missing_in(sesion: Session, modelo: type[RowT], filas: Iterable[RowT]) -> int:
|
||||
"""El cuerpo de `ReferenceRepository.agregar_faltantes`, sobre una sesión que se recibe."""
|
||||
llave = modelo.__table__.primary_key.columns.values()
|
||||
nuevas = [
|
||||
fila
|
||||
@@ -1,7 +1,7 @@
|
||||
"""What dbt owns in a domain's database and Python reads: the timeline view and the queries dbt compiled.
|
||||
|
||||
dbt creates and changes these relations, so there's no ORM class and no Alembic migration for them. Both repositories
|
||||
read on a `SesionDeLectura`. That refuses ORM writes and `insert`/`update`/`delete` statements, but not one spelled as
|
||||
read on a `ReadSession`. That refuses ORM writes and `insert`/`update`/`delete` statements, but not one spelled as
|
||||
text, so a compiled query is trusted to be the `select` dbt wrote; a database account that can only read is what
|
||||
guarantees it.
|
||||
"""
|
||||
@@ -9,11 +9,12 @@ guarantees it.
|
||||
from collections.abc import Callable, Iterable
|
||||
from datetime import date, datetime
|
||||
|
||||
from sqlalchemy import Date, column, select, table, text
|
||||
from core.indicadores.tipos import FechaHoraUTC
|
||||
from sqlalchemy import Date, Select, bindparam, column, select, table, text
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
|
||||
from persistance.aristas.plata.timeline import TIMELINE_COLUMNS, TimelineRepository
|
||||
from persistance.materializador import SesionDeLectura
|
||||
from persistance.edges.silver.timeline import TIMELINE_COLUMNS, TimelineRepository
|
||||
from persistance.materializer import ReadSession
|
||||
from persistance.repository import Repository
|
||||
|
||||
|
||||
@@ -28,7 +29,7 @@ def timeline_view(domain: str) -> str:
|
||||
class DbtTimelineRepository(TimelineRepository):
|
||||
"""The domain's timeline, read from dbt's view `<domain>_linea_de_tiempo`.
|
||||
|
||||
`fecha` comes back as a date on every engine. The filters run in the database; `patients` becomes one bound
|
||||
`fecha` comes back as a date and `conocida_en` as an aware UTC datetime on every engine. The filters run in the database; `patients` becomes one bound
|
||||
parameter per patient, so a long list can exceed an engine's limit (SQL Server's is 2,100): read without it and join.
|
||||
"""
|
||||
|
||||
@@ -37,7 +38,8 @@ class DbtTimelineRepository(TimelineRepository):
|
||||
super().__init__(session_factory, self._query)
|
||||
|
||||
def _query(self, *, patients: Iterable[int] | None, until: date | None, known_until: datetime | None):
|
||||
view = table(self.view, *(column(name, Date) if name == "fecha" else column(name) for name in TIMELINE_COLUMNS))
|
||||
types = {"fecha": Date, "conocida_en": FechaHoraUTC}
|
||||
view = table(self.view, *(column(name, types.get(name)) for name in TIMELINE_COLUMNS))
|
||||
query = select(*(view.c[name] for name in TIMELINE_COLUMNS))
|
||||
if patients is not None:
|
||||
query = query.where(view.c.pac_id.in_(list(patients)))
|
||||
@@ -57,13 +59,29 @@ class DbtTimelineRepository(TimelineRepository):
|
||||
|
||||
|
||||
class DbtQueryRepository(Repository):
|
||||
"""Runs a query dbt compiled (a model's `compiled_code` in `manifest.json`); one dict per row."""
|
||||
"""Runs a query dbt compiled (a model's `compiled_code` in `manifest.json`); one dict per row.
|
||||
|
||||
A query compiled with `--vars '{bind: true}'` has placeholders (`:periodo_inicio`) instead of values: `parameters`
|
||||
gives them, and a list or tuple fills an `in :name`. The database does the work; only what the query selects
|
||||
comes back.
|
||||
"""
|
||||
|
||||
def __init__(self, session_factory: Callable):
|
||||
super().__init__(session_factory, None)
|
||||
|
||||
def read(self, sql: str) -> list[dict]:
|
||||
def read(self, sql: str, parameters: dict | None = None) -> list[dict]:
|
||||
columns, rows = self.rows(sql, parameters)
|
||||
return [dict(zip(columns, row)) for row in rows]
|
||||
|
||||
def rows(self, sql: str | Select, parameters: dict | None = None) -> tuple[list[str], list[tuple]]:
|
||||
"""The column names and the rows; the names come back even when there are no rows.
|
||||
|
||||
`sql` can also be a `select` built over dbt's relations, which carries its own bound values.
|
||||
"""
|
||||
parameters = parameters or {}
|
||||
query = sql if isinstance(sql, Select) else text(sql).bindparams(*(
|
||||
bindparam(name, value, expanding=isinstance(value, (list, tuple))) for name, value in parameters.items()
|
||||
))
|
||||
with self._session_factory() as session:
|
||||
result = SesionDeLectura(session).execute(text(sql))
|
||||
columns = list(result.keys())
|
||||
return [dict(zip(columns, row)) for row in result]
|
||||
result = ReadSession(session).execute(query)
|
||||
return list(result.keys()), [tuple(row) for row in result]
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Oro: el registro (parámetros, periodos, definiciones), los reportes de indicadores y las cohortes con sus riesgos."""
|
||||
|
||||
from persistance.edges.common import ReferenceRepository
|
||||
from persistance.edges.gold.calculation import CalculationRepository, MeasureReportRepository, save_report_in
|
||||
from persistance.edges.gold.history import MeasureHistoryRepository
|
||||
from persistance.edges.gold.publication import PublicationRepository, sync_publication_in
|
||||
from persistance.edges.gold.cohorts import (
|
||||
ERROR,
|
||||
FINAL,
|
||||
PRELIMINAR,
|
||||
PROVENANCE,
|
||||
CohortBuild,
|
||||
CohortRepository,
|
||||
CohortMember,
|
||||
PatientMembership,
|
||||
PatientRisk,
|
||||
RiskOutsideCohort,
|
||||
RiskHorizon,
|
||||
change_state_in,
|
||||
save_build_in,
|
||||
save_batch_in,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"ERROR",
|
||||
"FINAL",
|
||||
"PRELIMINAR",
|
||||
"PROVENANCE",
|
||||
"CalculationRepository",
|
||||
"CohortBuild",
|
||||
"CohortRepository",
|
||||
"CohortMember",
|
||||
"MeasureHistoryRepository",
|
||||
"MeasureReportRepository",
|
||||
"PatientMembership",
|
||||
"PatientRisk",
|
||||
"PublicationRepository",
|
||||
"ReferenceRepository",
|
||||
"RiskOutsideCohort",
|
||||
"RiskHorizon",
|
||||
"change_state_in",
|
||||
"save_build_in",
|
||||
"save_batch_in",
|
||||
"save_report_in",
|
||||
"sync_publication_in",
|
||||
]
|
||||
+24
-24
@@ -1,6 +1,6 @@
|
||||
"""Oro: los reportes de indicadores. Un reporte se guarda con sus unidades (§6f), todo o nada.
|
||||
|
||||
`CalculoRepository` es lo que usa la arista `calcular`: mide (lo que calcula el
|
||||
`CalculationRepository` es lo que usa la arista `compute`: mide (lo que calcula el
|
||||
kit, como función de la sesión) y guarda en la misma sesión, una sola foto de la
|
||||
base por reporte.
|
||||
"""
|
||||
@@ -15,14 +15,14 @@ from sqlmodel import Session, SQLModel, select
|
||||
|
||||
from persistance.repository import Repository
|
||||
|
||||
ReporteT = TypeVar("ReporteT", bound=MeasureReportBase)
|
||||
Medicion = tuple[MeasureReportBase, Iterable[SQLModel]]
|
||||
ReportT = TypeVar("ReportT", bound=MeasureReportBase)
|
||||
Measurement = tuple[MeasureReportBase, Iterable[SQLModel]]
|
||||
|
||||
|
||||
class MeasureReportRepository(Repository[ReporteT]):
|
||||
class MeasureReportRepository(Repository[ReportT]):
|
||||
"""Los reportes de indicadores de un dominio. Un reporte se guarda con sus unidades."""
|
||||
|
||||
def guardar(self, reporte: ReporteT, filas: Iterable[SQLModel] = ()) -> int:
|
||||
def save(self, reporte: ReportT, filas: Iterable[SQLModel] = ()) -> int:
|
||||
"""Guarda un reporte y sus filas hijas con una sola sesión. Devuelve el `report_id`.
|
||||
|
||||
Las filas (las unidades de `measure_report_unidad` y sus estratos, §6f) llegan sin `report_id`:
|
||||
@@ -32,10 +32,10 @@ class MeasureReportRepository(Repository[ReporteT]):
|
||||
fecha de corte cuenta para que sea igual (MV-3). Todo o nada.
|
||||
"""
|
||||
with self._session_factory() as sesion:
|
||||
return guardar_reporte_en(sesion, reporte, filas)
|
||||
return save_report_in(sesion, reporte, filas)
|
||||
|
||||
|
||||
def guardar_reporte_en(sesion: Session, reporte: MeasureReportBase, filas: Iterable[SQLModel] = ()) -> int:
|
||||
def save_report_in(sesion: Session, reporte: MeasureReportBase, filas: Iterable[SQLModel] = ()) -> int:
|
||||
"""El cuerpo de `MeasureReportRepository.guardar`, sobre una sesión que se recibe.
|
||||
|
||||
`filas` son las unidades del reporte (`measure_report_unidad`, oro restringido) y el estrato de cada
|
||||
@@ -44,8 +44,8 @@ def guardar_reporte_en(sesion: Session, reporte: MeasureReportBase, filas: Itera
|
||||
"""
|
||||
filas = list(filas)
|
||||
try:
|
||||
anterior = _ultimo_reporte(sesion, reporte)
|
||||
if anterior is not None and _repite(sesion, anterior, reporte, filas):
|
||||
anterior = _last_report(sesion, reporte)
|
||||
if anterior is not None and _repeats(sesion, anterior, reporte, filas):
|
||||
return anterior.report_id
|
||||
sesion.add(reporte)
|
||||
sesion.flush()
|
||||
@@ -61,7 +61,7 @@ def guardar_reporte_en(sesion: Session, reporte: MeasureReportBase, filas: Itera
|
||||
|
||||
|
||||
# Lo que hace distinto a un reporte; la hora en que se generó no cuenta.
|
||||
_COLUMNAS_QUE_DISTINGUEN = (
|
||||
_DISTINGUISHING_COLUMNS = (
|
||||
"measure_version",
|
||||
"kit_version",
|
||||
"toml_sha",
|
||||
@@ -77,7 +77,7 @@ _COLUMNAS_QUE_DISTINGUEN = (
|
||||
)
|
||||
|
||||
|
||||
def _ultimo_reporte(sesion: Session, reporte: MeasureReportBase) -> MeasureReportBase | None:
|
||||
def _last_report(sesion: Session, reporte: MeasureReportBase) -> MeasureReportBase | None:
|
||||
"""El último reporte guardado del mismo indicador y periodo, por `generado_en`."""
|
||||
modelo = type(reporte)
|
||||
return sesion.exec(
|
||||
@@ -88,14 +88,14 @@ def _ultimo_reporte(sesion: Session, reporte: MeasureReportBase) -> MeasureRepor
|
||||
).first()
|
||||
|
||||
|
||||
def _repite(sesion: Session, anterior: MeasureReportBase, reporte: MeasureReportBase, filas: list[SQLModel]) -> bool:
|
||||
def _repeats(sesion: Session, anterior: MeasureReportBase, reporte: MeasureReportBase, filas: list[SQLModel]) -> bool:
|
||||
"""Si el reporte nuevo es igual al anterior: mismo encabezado (con `huella`) y mismas filas, tabla por tabla."""
|
||||
if any(getattr(anterior, columna) != getattr(reporte, columna) for columna in _COLUMNAS_QUE_DISTINGUEN):
|
||||
if any(getattr(anterior, columna) != getattr(reporte, columna) for columna in _DISTINGUISHING_COLUMNS):
|
||||
return False
|
||||
return _iguales(sesion, anterior.report_id, filas)
|
||||
return _equal(sesion, anterior.report_id, filas)
|
||||
|
||||
|
||||
def _iguales(sesion: Session, report_id: int, filas: list[SQLModel]) -> bool:
|
||||
def _equal(sesion: Session, report_id: int, filas: list[SQLModel]) -> bool:
|
||||
"""Las filas de las tablas hijas guardadas con el reporte anterior son estas, tabla por tabla.
|
||||
|
||||
Las filas pueden ser de varias tablas (las unidades de `measure_report_unidad` y sus estratos):
|
||||
@@ -106,27 +106,27 @@ def _iguales(sesion: Session, report_id: int, filas: list[SQLModel]) -> bool:
|
||||
por_tabla.setdefault(type(fila), []).append(fila)
|
||||
for modelo, de_la_tabla in por_tabla.items():
|
||||
guardadas = sesion.exec(select(modelo).where(modelo.report_id == report_id)).all()
|
||||
if sorted(map(_contenido, guardadas)) != sorted(map(_contenido, de_la_tabla)):
|
||||
if sorted(map(_content, guardadas)) != sorted(map(_content, de_la_tabla)):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _contenido(fila: SQLModel) -> str:
|
||||
def _content(fila: SQLModel) -> str:
|
||||
"""Lo que dice una fila hija, sin su `report_id` ni una llave entera que numere la base.
|
||||
|
||||
En `measure_report_unidad`, `valor_id` es la categoría y sí cuenta (T-19b).
|
||||
"""
|
||||
llave = type(fila).__table__.primary_key.columns
|
||||
puesta_por_la_base = {c.name for c in llave} if len(llave) == 1 and _llave_entera(llave) else set()
|
||||
puesta_por_la_base = {c.name for c in llave} if len(llave) == 1 and _whole_key(llave) else set()
|
||||
return json.dumps(fila.model_dump(exclude={"report_id", *puesta_por_la_base}), sort_keys=True, default=str)
|
||||
|
||||
|
||||
def _llave_entera(columnas) -> bool:
|
||||
def _whole_key(columnas) -> bool:
|
||||
"""Si la única columna de la llave es entera: la numera la base."""
|
||||
return all(c.type.python_type is int for c in columnas)
|
||||
|
||||
|
||||
class CalculoRepository(MeasureReportRepository):
|
||||
class CalculationRepository(MeasureReportRepository):
|
||||
"""Los reportes de un dominio, calculados en una sola sesión: una sola foto de la base por reporte.
|
||||
|
||||
`periodo` es la tabla `dim_periodo` del dominio.
|
||||
@@ -136,7 +136,7 @@ class CalculoRepository(MeasureReportRepository):
|
||||
super().__init__(session_factory, model)
|
||||
self.periodo = periodo
|
||||
|
||||
def periodos(self, tipo: str, desde: date, hasta: date) -> list[str]:
|
||||
def periods(self, tipo: str, desde: date, hasta: date) -> list[str]:
|
||||
"""Los `periodo_id` de `tipo` que caben enteros en `[desde, hasta)`, en orden. Falla si no hay ninguno."""
|
||||
p = self.periodo
|
||||
with self._session_factory() as sesion:
|
||||
@@ -146,15 +146,15 @@ class CalculoRepository(MeasureReportRepository):
|
||||
if not ids:
|
||||
raise LookupError(
|
||||
f"dim_periodo no tiene periodos {tipo!r} entre {desde} y {hasta}: "
|
||||
"se agregan con la arista `registro`."
|
||||
"se agregan con la arista `registry`."
|
||||
)
|
||||
return ids
|
||||
|
||||
def calcular(self, medir: Callable[[Session], Medicion]) -> int:
|
||||
def compute(self, medir: Callable[[Session], Measurement]) -> int:
|
||||
"""Mide con `medir(sesion)` (el reporte y sus unidades) y lo guarda en esa misma sesión.
|
||||
|
||||
Devuelve el `report_id`; si el reporte repite al último del periodo, el de ese (`guardar`).
|
||||
"""
|
||||
with self._session_factory() as sesion:
|
||||
reporte, filas = medir(sesion)
|
||||
return guardar_reporte_en(sesion, reporte, filas)
|
||||
return save_report_in(sesion, reporte, filas)
|
||||
+21
-21
@@ -23,48 +23,48 @@ from sqlmodel import Session, SQLModel, select
|
||||
|
||||
from persistance.repository import Repository
|
||||
|
||||
PROCEDENCIA = ("modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha")
|
||||
PROVENANCE = ("modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha")
|
||||
PRELIMINAR, FINAL, ERROR = "preliminary", "final", "entered-in-error"
|
||||
|
||||
|
||||
# Lo que el kit entrega para guardar un armado: la fila del armado y sus hijas, sin `armado_id`.
|
||||
Armado = tuple[SQLModel, Iterable[SQLModel], Iterable[SQLModel], Iterable[SQLModel]]
|
||||
BuildModel = tuple[SQLModel, Iterable[SQLModel], Iterable[SQLModel], Iterable[SQLModel]]
|
||||
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class RiesgoFueraDeCohorte(ValueError):
|
||||
class RiskOutsideCohort(ValueError):
|
||||
"""Se quiso guardar el riesgo de alguien que no es miembro del armado puntuado."""
|
||||
|
||||
|
||||
class CohorteRepository(Repository):
|
||||
class CohortRepository(Repository):
|
||||
"""Los armados de cohortes de un dominio y sus lotes de riesgos. Cada método, una sesión."""
|
||||
|
||||
def __init__(self, session_factory, cohortes: TablasCohorte):
|
||||
super().__init__(session_factory, cohortes.CohorteArmado)
|
||||
self.cohortes = cohortes
|
||||
|
||||
def armar(self, armado: Callable[[Session], Armado]) -> tuple[int, bool]:
|
||||
def assemble(self, armado: Callable[[Session], BuildModel]) -> tuple[int, bool]:
|
||||
"""Calcula el armado con `armado(sesion)` y lo guarda en esa sesión. Devuelve (`armado_id`, nuevo)."""
|
||||
with self._session_factory() as sesion:
|
||||
return guardar_armado_en(sesion, *armado(sesion))
|
||||
return save_build_in(sesion, *armado(sesion))
|
||||
|
||||
def leer(self, leer: Callable[[Session], T]) -> T:
|
||||
def read(self, leer: Callable[[Session], T]) -> T:
|
||||
"""Lo que `leer(sesion)` lee de las cohortes, en una sesión (el marco de un armado para estimar). No escribe."""
|
||||
with self._session_factory() as sesion:
|
||||
return leer(sesion)
|
||||
|
||||
def guardar_lote(
|
||||
def save_batch(
|
||||
self, armado_id: int, procedencia: dict, desenlace: str, riesgos, *, ahora: datetime | None = None
|
||||
) -> tuple[int, bool]:
|
||||
with self._session_factory() as sesion:
|
||||
return guardar_lote_en(sesion, armado_id, procedencia, desenlace, riesgos, cohortes=self.cohortes,
|
||||
return save_batch_in(sesion, armado_id, procedencia, desenlace, riesgos, cohortes=self.cohortes,
|
||||
ahora=ahora)
|
||||
|
||||
def cambiar_estado(self, lote_id: int, estado: str, motivo: str, *, ahora: datetime | None = None) -> int:
|
||||
def change_state(self, lote_id: int, estado: str, motivo: str, *, ahora: datetime | None = None) -> int:
|
||||
with self._session_factory() as sesion:
|
||||
return cambiar_estado_en(sesion, lote_id, estado, motivo, cohortes=self.cohortes, ahora=ahora)
|
||||
return change_state_in(sesion, lote_id, estado, motivo, cohortes=self.cohortes, ahora=ahora)
|
||||
|
||||
def latest_build(self, url: str) -> int | None:
|
||||
"""The most recent build of the cohort `url`, or `None` if it has none."""
|
||||
@@ -219,7 +219,7 @@ def _cohort_build(row: SQLModel) -> CohortBuild:
|
||||
row.n_miembros, row.armado_en)
|
||||
|
||||
|
||||
def guardar_armado_en(
|
||||
def save_build_in(
|
||||
sesion: Session, armado: SQLModel, exclusiones: Iterable[SQLModel], miembros: Iterable[SQLModel],
|
||||
variables: Iterable[SQLModel],
|
||||
) -> tuple[int, bool]:
|
||||
@@ -251,7 +251,7 @@ def guardar_armado_en(
|
||||
return armado_id, True
|
||||
|
||||
|
||||
def guardar_lote_en(
|
||||
def save_batch_in(
|
||||
sesion: Session,
|
||||
armado_id: int,
|
||||
procedencia: dict,
|
||||
@@ -263,18 +263,18 @@ def guardar_lote_en(
|
||||
) -> tuple[int, bool]:
|
||||
"""Guarda los riesgos `(pac_id, horizonte_anios, probabilidad, ic_bajo, ic_alto)`. Devuelve (`lote_id`, nuevo).
|
||||
|
||||
No copia nada de MLflow: guarda sus llaves (`PROCEDENCIA`). Puntuar lo mismo
|
||||
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á.
|
||||
"""
|
||||
faltan = [c for c in PROCEDENCIA if not procedencia.get(c)]
|
||||
faltan = [c for c in PROVENANCE if not procedencia.get(c)]
|
||||
if faltan:
|
||||
raise ValueError(f"La procedencia no trae {faltan}.")
|
||||
miembro = cohortes.CohorteMiembro
|
||||
miembros = set(sesion.exec(select(miembro.pac_id).where(miembro.armado_id == armado_id)))
|
||||
ajenos = sorted({pac for pac, *_ in riesgos} - miembros)
|
||||
if ajenos:
|
||||
raise RiesgoFueraDeCohorte(f"No son miembros del armado {armado_id}: {ajenos[:10]}.")
|
||||
huella = _sha_json({"armado_id": armado_id, "desenlace": desenlace, **{c: procedencia[c] for c in PROCEDENCIA},
|
||||
raise RiskOutsideCohort(f"No son miembros del armado {armado_id}: {ajenos[:10]}.")
|
||||
huella = _json_sha({"armado_id": armado_id, "desenlace": desenlace, **{c: procedencia[c] for c in PROVENANCE},
|
||||
"riesgos": sorted(riesgos)})
|
||||
lote = cohortes.EvaluacionRiesgoLote
|
||||
previo = sesion.exec(select(lote).where(lote.huella == huella)).first()
|
||||
@@ -283,7 +283,7 @@ def guardar_lote_en(
|
||||
momento = ahora or datetime.now(timezone.utc)
|
||||
try:
|
||||
fila = lote(armado_id=armado_id, desenlace=desenlace, evaluado_en=momento, n_evaluaciones=len(riesgos),
|
||||
huella=huella, **{c: str(procedencia[c]) for c in PROCEDENCIA})
|
||||
huella=huella, **{c: str(procedencia[c]) for c in PROVENANCE})
|
||||
sesion.add(fila)
|
||||
sesion.flush()
|
||||
sesion.add_all(
|
||||
@@ -298,7 +298,7 @@ def guardar_lote_en(
|
||||
return fila.lote_id, True
|
||||
|
||||
|
||||
def cambiar_estado_en(
|
||||
def change_state_in(
|
||||
sesion: Session, lote_id: int, estado: str, motivo: str, *, cohortes: TablasCohorte,
|
||||
ahora: datetime | None = None,
|
||||
) -> int:
|
||||
@@ -331,7 +331,7 @@ def cambiar_estado_en(
|
||||
return len(vigentes)
|
||||
|
||||
|
||||
def _sha_json(objeto) -> str:
|
||||
"""sha256 del JSON canónico (el mismo de `indicadores_kit.oro.cohortes.definicion.sha_json`)."""
|
||||
def _json_sha(objeto) -> str:
|
||||
"""sha256 del JSON canónico (el mismo de `models.cohorts.definition.json_sha`)."""
|
||||
texto = json.dumps(objeto, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
|
||||
return hashlib.sha256(texto.encode("utf-8")).hexdigest()
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Oro: measures asked for on request, each answer kept once under the full key of the question.
|
||||
|
||||
A question is a measure and its definition's version, a period, the event cut-off (`fecha`), the knowledge cut-off
|
||||
(`conocida_en`) and the values of its rules. Its answer is a `measure_report` whose `parametros` is that key and
|
||||
whose `parametros_sha` is the key's hash, with its units in `measure_report_unidad` and their strata in
|
||||
`measure_report_unidad_estrato`, so the publication views read it as any other report. The database writes those
|
||||
rows (`INSERT … SELECT`): they never pass through Python. A stratum value not yet in `cat_estrato_valor` is added
|
||||
there first, labelled with itself, so the foreign key from `measure_report_unidad_estrato` holds.
|
||||
|
||||
Asking a stored key again reads it and writes nothing; what was answered can't drift when later loads change silver.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable, Iterable
|
||||
|
||||
from sqlalchemy import Select, and_, distinct, exists, func, insert, literal, select
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
from persistance.repository import Repository
|
||||
|
||||
|
||||
class MeasureHistoryRepository(Repository):
|
||||
"""The reports of a domain's measures asked for on request. `unit_model` and `stratum_model` are the domain's
|
||||
`measure_report_unidad` and `measure_report_unidad_estrato`; `value_model`, its `cat_estrato_valor`."""
|
||||
|
||||
def __init__(self, session_factory, model, *, unit_model, stratum_model, value_model):
|
||||
super().__init__(session_factory, model)
|
||||
self.unit_model, self.stratum_model, self.value_model = unit_model, stratum_model, value_model
|
||||
|
||||
def counts(self, report_id: int) -> dict[tuple[str, str, str, str | None], int]:
|
||||
"""A stored answer's units counted from its rows: `{(stratum, value, resultado_id, valor_id): units}`, the
|
||||
total as `("total", "total", …)`. No view is needed to read what was answered."""
|
||||
u, e = self.unit_model, self.stratum_model
|
||||
units = func.count(distinct(u.unidad_id))
|
||||
with self._session_factory() as session:
|
||||
total = session.execute(select(u.resultado_id, u.valor_id, units).where(u.report_id == report_id)
|
||||
.group_by(u.resultado_id, u.valor_id)).all()
|
||||
by_stratum = session.execute(
|
||||
select(e.estrato_id, e.estrato_valor, u.resultado_id, u.valor_id, units)
|
||||
.join(e, (e.report_id == u.report_id) & (e.unidad_id == u.unidad_id))
|
||||
.where(u.report_id == report_id)
|
||||
.group_by(e.estrato_id, e.estrato_valor, u.resultado_id, u.valor_id)).all()
|
||||
return {**{("total", "total", r, v): n for r, v, n in total},
|
||||
**{(s, sv, r, v): n for s, sv, r, v, n in by_stratum}}
|
||||
|
||||
def group_counts(self, report_id: int) -> dict[tuple[str, str], int]:
|
||||
"""A stored answer's units per group and population: `{(grupo, resultado_id): units}`. For a measure with
|
||||
several groups, whose units repeat in each one."""
|
||||
u = self.unit_model
|
||||
with self._session_factory() as session:
|
||||
rows = session.execute(select(u.grupo, u.resultado_id, func.count(distinct(u.unidad_id)))
|
||||
.where(u.report_id == report_id).group_by(u.grupo, u.resultado_id)).all()
|
||||
return {(g, r): n for g, r, n in rows}
|
||||
|
||||
def find(self, measure_url: str, key_sha: str) -> int | None:
|
||||
"""The report already answering this key, if it was asked before."""
|
||||
report = self.model
|
||||
with self._session_factory() as session:
|
||||
return session.execute(
|
||||
select(report.report_id)
|
||||
.where(report.measure_url == measure_url, report.parametros_sha == key_sha)
|
||||
.order_by(report.report_id)
|
||||
.limit(1)
|
||||
).scalar()
|
||||
|
||||
def record(self, report: SQLModel, rows: Callable[[int], Iterable[tuple[type[SQLModel], Select]]]) -> int:
|
||||
"""Saves the report and, in the same transaction, what each `(model, select)` of `rows(report_id)` gives.
|
||||
|
||||
Each select names its columns as the model's table does. All or nothing. Returns the `report_id`.
|
||||
"""
|
||||
with self._session_factory() as session:
|
||||
try:
|
||||
session.add(report)
|
||||
session.flush()
|
||||
report_id = report.report_id
|
||||
for model, query in rows(report_id):
|
||||
table = model.__table__
|
||||
if model is self.stratum_model:
|
||||
session.execute(self._new_values(query))
|
||||
session.execute(insert(table).from_select([table.c[c.name] for c in query.selected_columns], query))
|
||||
session.commit()
|
||||
except Exception:
|
||||
session.rollback()
|
||||
raise
|
||||
return report_id
|
||||
|
||||
def _new_values(self, strata: Select):
|
||||
"""`INSERT … SELECT` of the stratum values `strata` gives that `cat_estrato_valor` doesn't have yet."""
|
||||
catalog, given = self.value_model.__table__, strata.subquery()
|
||||
new = (select(given.c.estrato_id, given.c.estrato_valor, given.c.estrato_valor, literal(0))
|
||||
.where(~exists().where(and_(catalog.c.estrato_id == given.c.estrato_id,
|
||||
catalog.c.valor_id == given.c.estrato_valor)))
|
||||
.distinct())
|
||||
return insert(catalog).from_select(["estrato_id", "valor_id", "etiqueta", "orden"], new)
|
||||
+12
-12
@@ -1,6 +1,6 @@
|
||||
"""Oro: el catálogo de publicación (§6f, MD-19), `cat_measure*` y `cat_estrato*`, sincronizado con los TOML del kit.
|
||||
|
||||
Las filas llegan ya armadas y por capas (`indicadores_kit.registry.publicacion.semillas_de`). No se
|
||||
Las filas llegan ya armadas y por capas (`webapi.orchestration.reference.publicacion.semillas_de`). No se
|
||||
reemplazan enteras: las unidades de los reportes guardados apuntan a `cat_measure_resultado` y a
|
||||
`cat_estrato_valor`. Se inserta o actualiza por llave, y se borra solo lo que ya no viene **y nadie usa**.
|
||||
Lo que una fila de otra tabla todavía referencia se queda.
|
||||
@@ -15,25 +15,25 @@ from sqlmodel import Session, SQLModel, select
|
||||
from persistance.repository import Repository
|
||||
|
||||
|
||||
class PublicacionRepository(Repository):
|
||||
class PublicationRepository(Repository):
|
||||
"""Las siete tablas del catálogo de publicación de un dominio, en orden de llaves foráneas."""
|
||||
|
||||
def __init__(self, session_factory: Callable[[], Session], modelos: Sequence[type[SQLModel]]):
|
||||
super().__init__(session_factory, modelos[0])
|
||||
self.modelos = tuple(modelos)
|
||||
|
||||
def sincronizar(self, capas: Iterable[Iterable[SQLModel]]) -> dict[str, int]:
|
||||
def sync(self, capas: Iterable[Iterable[SQLModel]]) -> dict[str, int]:
|
||||
"""Inserta o actualiza las filas, capa por capa, y borra lo que no vino y nadie usa. Una sesión, todo o nada."""
|
||||
with self._session_factory() as sesion:
|
||||
return sincronizar_publicacion_en(sesion, capas, self.modelos)
|
||||
return sync_publication_in(sesion, capas, self.modelos)
|
||||
|
||||
|
||||
def sincronizar_publicacion_en(
|
||||
def sync_publication_in(
|
||||
sesion: Session, capas: Iterable[Iterable[SQLModel]], modelos: Sequence[type[SQLModel]]
|
||||
) -> dict[str, int]:
|
||||
"""El cuerpo de `PublicacionRepository.sincronizar`, sobre una sesión que se recibe.
|
||||
"""El cuerpo de `PublicationRepository.sincronizar`, sobre una sesión que se recibe.
|
||||
|
||||
`capas`: listas de filas, cada una con sus padres en una capa anterior. `modelos`: las tablas que se
|
||||
`capas`: listas de filas, cada una con sus padres en una capa anterior. `event_models`: las tablas que se
|
||||
sincronizan, padres antes que hijos; de ellas se borra lo que no vino, de los hijos a los padres.
|
||||
Devuelve cuántas filas llegaron, cuántas se borraron y cuántas se conservaron por estar en uso.
|
||||
"""
|
||||
@@ -42,15 +42,15 @@ def sincronizar_publicacion_en(
|
||||
try:
|
||||
for capa in capas:
|
||||
for fila in capa:
|
||||
vienen.setdefault(type(fila), set()).add(_llave(fila))
|
||||
vienen.setdefault(type(fila), set()).add(_key(fila))
|
||||
sesion.merge(fila)
|
||||
cuenta["filas"] += 1
|
||||
sesion.flush()
|
||||
for modelo in reversed(modelos):
|
||||
for fila in sesion.exec(select(modelo)).all():
|
||||
if _llave(fila) in vienen[modelo]:
|
||||
if _key(fila) in vienen[modelo]:
|
||||
continue
|
||||
if _en_uso(sesion, fila):
|
||||
if _in_use(sesion, fila):
|
||||
cuenta["en_uso"] += 1
|
||||
continue
|
||||
sesion.delete(fila)
|
||||
@@ -63,11 +63,11 @@ def sincronizar_publicacion_en(
|
||||
return cuenta
|
||||
|
||||
|
||||
def _llave(fila: SQLModel) -> tuple:
|
||||
def _key(fila: SQLModel) -> tuple:
|
||||
return tuple(getattr(fila, columna.name) for columna in type(fila).__table__.primary_key.columns)
|
||||
|
||||
|
||||
def _en_uso(sesion: Session, fila: SQLModel) -> bool:
|
||||
def _in_use(sesion: Session, fila: SQLModel) -> bool:
|
||||
"""Si alguna fila de otra tabla del mismo registro apunta a esta por una llave foránea."""
|
||||
tabla = type(fila).__table__
|
||||
for otra in tabla.metadata.tables.values():
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Plata: los catálogos, la carga del staging directo, `v_persona`, el periodo de observación, la verificación y la línea de tiempo."""
|
||||
|
||||
from persistance.edges.silver.loads import (
|
||||
LoadRepository,
|
||||
open_load,
|
||||
close_load,
|
||||
save_load_in,
|
||||
)
|
||||
from persistance.edges.silver.catalogs import CatalogRepository
|
||||
from persistance.edges.silver.observation import ObservationRepository
|
||||
from persistance.edges.silver.procedures import save_silver_in
|
||||
from persistance.edges.silver.timeline import (
|
||||
TIMELINE_COLUMNS,
|
||||
TimelineContractError,
|
||||
TimelineQuery,
|
||||
TimelineQueryMissing,
|
||||
TimelineRepository,
|
||||
)
|
||||
from persistance.edges.silver.links import LinksRepository
|
||||
from persistance.edges.silver.views import ViewsRepository
|
||||
|
||||
__all__ = [
|
||||
"LoadRepository",
|
||||
"CatalogRepository",
|
||||
"ObservationRepository",
|
||||
"TIMELINE_COLUMNS",
|
||||
"TimelineContractError",
|
||||
"TimelineQuery",
|
||||
"TimelineQueryMissing",
|
||||
"TimelineRepository",
|
||||
"LinksRepository",
|
||||
"ViewsRepository",
|
||||
"open_load",
|
||||
"close_load",
|
||||
"save_load_in",
|
||||
"save_silver_in",
|
||||
]
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
"""Plata: `catalogos`, materializar el catálogo del proyecto en `cat_estudio`, `cat_resultado` y `cat_valor`.
|
||||
"""Plata: `catalogs`, materializar el catálogo del proyecto en `cat_estudio`, `cat_resultado` y `cat_valor`.
|
||||
|
||||
Las filas llegan ya armadas (el kit lee `core/catalogos/<proyecto>.toml`). Nada se
|
||||
borra: un valor que salió del archivo pasa a `retirado`, porque lo pueden seguir
|
||||
@@ -12,7 +12,7 @@ from sqlmodel import Session, SQLModel, select
|
||||
from persistance.repository import Repository
|
||||
|
||||
|
||||
class CatalogoRepository(Repository):
|
||||
class CatalogRepository(Repository):
|
||||
"""Las tres tablas de catálogo de un dominio. `get`, `list` y `count` leen los estudios."""
|
||||
|
||||
def __init__(
|
||||
@@ -26,7 +26,7 @@ class CatalogoRepository(Repository):
|
||||
self.resultado = resultado
|
||||
self.valor = valor
|
||||
|
||||
def sincronizar(
|
||||
def sync(
|
||||
self, estudios: Iterable[SQLModel], resultados: Iterable[SQLModel], valores: Iterable[SQLModel]
|
||||
) -> dict[str, int]:
|
||||
"""Inserta o actualiza por llave y retira los valores que ya no vienen. Una sesión, todo o nada.
|
||||
+4
-4
@@ -10,13 +10,13 @@ from persistance.repository import Repository
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class VinculosRepository(Repository):
|
||||
class LinksRepository(Repository):
|
||||
"""Cuenta, con lo que calcula el kit sobre la sesión, cuántos resultados encuentran su toma."""
|
||||
|
||||
def __init__(self, session_factory):
|
||||
super().__init__(session_factory, None)
|
||||
|
||||
def verificar(self, verificar: Callable[[Session], T]) -> T:
|
||||
"""Corre `verificar(sesion)` en una sesión de solo lectura (no hace commit)."""
|
||||
def check(self, check: Callable[[Session], T]) -> T:
|
||||
"""Corre `check(sesion)` en una sesión de solo lectura (no hace commit)."""
|
||||
with self._session_factory() as sesion:
|
||||
return verificar(sesion)
|
||||
return check(sesion)
|
||||
+21
-21
@@ -2,7 +2,7 @@
|
||||
|
||||
Desde F6 (ADR-MD-009) no hay tablas de hechos por tipo ni sus versiones: el kit arma la
|
||||
plata del staging directo (`plata_desde_staging`) y aquí se escribe en una transacción
|
||||
(`guardar_carga_en`, con `guardar_plata_en`). Aquí no se sabe qué es un indicador.
|
||||
(`save_load_in`, con `save_silver_in`). Aquí no se sabe qué es un indicador.
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -13,13 +13,13 @@ from typing import TypeVar
|
||||
from core.indicadores.comunes import CargaBase, PersonaBase
|
||||
from sqlmodel import Session, SQLModel
|
||||
|
||||
from persistance.aristas.plata.procedimientos import guardar_plata_en
|
||||
from persistance.edges.silver.procedures import save_silver_in
|
||||
from persistance.repository import Repository
|
||||
|
||||
CargaT = TypeVar("CargaT", bound=CargaBase)
|
||||
LoadT = TypeVar("LoadT", bound=CargaBase)
|
||||
|
||||
|
||||
class CargaRepository(Repository[CargaT]):
|
||||
class LoadRepository(Repository[LoadT]):
|
||||
"""Las cargas de un dominio. Una carga se escribe aquí, entera.
|
||||
|
||||
`persona` es la tabla de personas del mismo dominio: la carga agrega
|
||||
@@ -30,7 +30,7 @@ class CargaRepository(Repository[CargaT]):
|
||||
def __init__(
|
||||
self,
|
||||
session_factory: Callable[[], Session],
|
||||
model: type[CargaT],
|
||||
model: type[LoadT],
|
||||
*,
|
||||
persona: type[PersonaBase],
|
||||
procedimiento: type[SQLModel] | None = None,
|
||||
@@ -41,24 +41,24 @@ class CargaRepository(Repository[CargaT]):
|
||||
self.procedimiento = procedimiento
|
||||
self.observacion = observacion
|
||||
|
||||
def guardar_carga(
|
||||
def save_load(
|
||||
self, *, fuente: str, personas: Iterable[PersonaBase], plata, codigo_sha: str | None = None
|
||||
) -> CargaT:
|
||||
"""Escribe una carga con una sola sesión y devuelve su fila de `carga` (`guardar_carga_en`)."""
|
||||
) -> LoadT:
|
||||
"""Escribe una carga con una sola sesión y devuelve su fila de `carga` (`save_load_in`)."""
|
||||
if self.procedimiento is None or self.observacion is None:
|
||||
raise ValueError("Una carga con plata necesita las tablas procedimiento, observacion.")
|
||||
with self._session_factory() as sesion:
|
||||
return guardar_carga_en(
|
||||
return save_load_in(
|
||||
sesion, carga=self.model, persona=self.persona, procedimiento=self.procedimiento,
|
||||
observacion=self.observacion, fuente=fuente, personas=personas, plata=plata,
|
||||
codigo_sha=codigo_sha,
|
||||
)
|
||||
|
||||
|
||||
def guardar_carga_en(
|
||||
def save_load_in(
|
||||
sesion: Session,
|
||||
*,
|
||||
carga: type[CargaT],
|
||||
carga: type[LoadT],
|
||||
persona: type[PersonaBase],
|
||||
procedimiento: type[SQLModel],
|
||||
observacion: type[SQLModel],
|
||||
@@ -66,7 +66,7 @@ def guardar_carga_en(
|
||||
personas: Iterable[PersonaBase],
|
||||
plata,
|
||||
codigo_sha: str | None = None,
|
||||
) -> CargaT:
|
||||
) -> LoadT:
|
||||
"""La carga del staging directo (T-20c): personas y plata, sin tablas por tipo. Una transacción.
|
||||
|
||||
Los contadores de `carga` cuentan **procedimientos** por su efecto: nuevos; cambiados, ellos o
|
||||
@@ -76,9 +76,9 @@ def guardar_carga_en(
|
||||
Se puede repetir: lo que no cambió no se toca. Todo o nada.
|
||||
"""
|
||||
try:
|
||||
fila = abrir_carga(sesion, carga, fuente=fuente, codigo_sha=codigo_sha)
|
||||
_poner_personas(sesion, persona, personas)
|
||||
cuenta = guardar_plata_en(sesion, plata, procedimiento=procedimiento, observacion=observacion,
|
||||
fila = open_load(sesion, carga, fuente=fuente, codigo_sha=codigo_sha)
|
||||
_put_persons(sesion, persona, personas)
|
||||
cuenta = save_silver_in(sesion, plata, procedimiento=procedimiento, observacion=observacion,
|
||||
carga_id=fila.carga_id)
|
||||
fila.filas_nuevas = cuenta["procedimientos_nuevos"]
|
||||
fila.filas_cambiadas = cuenta["procedimientos_tocados"]
|
||||
@@ -86,7 +86,7 @@ def guardar_carga_en(
|
||||
- cuenta["procedimientos_nuevos"] - cuenta["procedimientos_tocados"])
|
||||
descartes = {**plata.descartes, **({"huerfanos": cuenta["huerfanos"]} if cuenta["huerfanos"] else {})}
|
||||
fila.descartes = json.dumps(descartes, sort_keys=True, ensure_ascii=False) if descartes else None
|
||||
cerrar_carga(sesion, fila)
|
||||
close_load(sesion, fila)
|
||||
sesion.commit()
|
||||
except Exception:
|
||||
sesion.rollback()
|
||||
@@ -95,7 +95,7 @@ def guardar_carga_en(
|
||||
return fila
|
||||
|
||||
|
||||
def _poner_personas(sesion: Session, persona: type[PersonaBase], personas: Iterable[PersonaBase]) -> None:
|
||||
def _put_persons(sesion: Session, persona: type[PersonaBase], personas: Iterable[PersonaBase]) -> None:
|
||||
"""Agrega las personas que falten y pone al día las que ya estaban."""
|
||||
for nueva in personas:
|
||||
actual = sesion.get(persona, nueva.pac_id)
|
||||
@@ -110,9 +110,9 @@ def _poner_personas(sesion: Session, persona: type[PersonaBase], personas: Itera
|
||||
sesion.flush()
|
||||
|
||||
|
||||
def abrir_carga(
|
||||
sesion: Session, carga: type[CargaT], fuente: str, codigo_sha: str | None = None
|
||||
) -> CargaT:
|
||||
def open_load(
|
||||
sesion: Session, carga: type[LoadT], fuente: str, codigo_sha: str | None = None
|
||||
) -> LoadT:
|
||||
"""Registra el inicio de una carga y devuelve su fila, ya con `carga_id`."""
|
||||
fila = carga(fuente=fuente, inicio=datetime.now(timezone.utc), codigo_sha=codigo_sha)
|
||||
sesion.add(fila)
|
||||
@@ -120,7 +120,7 @@ def abrir_carga(
|
||||
return fila
|
||||
|
||||
|
||||
def cerrar_carga(sesion: Session, carga: CargaBase) -> None:
|
||||
def close_load(sesion: Session, carga: CargaBase) -> None:
|
||||
"""Registra el fin de una carga; los conteos ya van en la fila."""
|
||||
carga.fin = datetime.now(timezone.utc)
|
||||
sesion.add(carga)
|
||||
+4
-4
@@ -1,16 +1,16 @@
|
||||
"""Plata: `observar`, reemplazar `periodo_observacion` con las filas que se calculan en la misma sesión."""
|
||||
"""Plata: `observe`, reemplazar `periodo_observacion` con las filas que se calculan en la misma sesión."""
|
||||
|
||||
from collections.abc import Callable, Iterable
|
||||
|
||||
from sqlmodel import Session
|
||||
|
||||
from persistance.aristas.comun import RegistroRepository, reemplazar_en
|
||||
from persistance.edges.common import ReferenceRepository, replace_in
|
||||
|
||||
|
||||
class ObservacionRepository(RegistroRepository):
|
||||
class ObservationRepository(ReferenceRepository):
|
||||
"""`periodo_observacion` de un dominio."""
|
||||
|
||||
def observar(self, periodos: Callable[[Session], Iterable]) -> int:
|
||||
"""Calcula los periodos con `periodos(sesion)` y deja la tabla con exactamente esos. Devuelve cuántos."""
|
||||
with self._session_factory() as sesion:
|
||||
return reemplazar_en(sesion, self.model, periodos(sesion))
|
||||
return replace_in(sesion, self.model, periodos(sesion))
|
||||
+23
-17
@@ -16,7 +16,8 @@ Persistance lo importe:
|
||||
Un procedimiento sin `pac_id` toma el de su padre; sin `fecha`, también, si el kit lo
|
||||
marca con `fecha_del_padre` (su tabla no trae fecha: un segmento de EEG, un instrumento
|
||||
aplicado). Uno que sí trae columna de fecha y la trae vacía se queda sin fecha. Uno sin `pac_id` y sin padre (el segmento de un EEG que la
|
||||
carga descartó) no se escribe, ni sus observaciones: se cuenta en `huerfanos` y se avisa. Uno que trae `orden_numero` y no encontró su orden se liga
|
||||
carga descartó) no se escribe, ni sus observaciones: se cuenta en `huerfanos` y se avisa. An observation whose
|
||||
procedure isn't in silver (it attaches to another row's procedure, which didn't enter) isn't written either. Uno que trae `orden_numero` y no encontró su orden se liga
|
||||
a ella cuando llega, aunque sea en otro lote.
|
||||
"""
|
||||
|
||||
@@ -24,12 +25,12 @@ import logging
|
||||
|
||||
from sqlmodel import Session, SQLModel, select
|
||||
|
||||
registro = logging.getLogger(__name__)
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
LLAVE = ("fuente_tabla", "fuente_id", "estudio_id", "clase")
|
||||
KEY = ("fuente_tabla", "fuente_id", "estudio_id", "clase")
|
||||
|
||||
|
||||
def guardar_plata_en(
|
||||
def save_silver_in(
|
||||
sesion: Session, plata, *, procedimiento: type[SQLModel], observacion: type[SQLModel], carga_id: int
|
||||
) -> dict[str, int]:
|
||||
"""Escribe los procedimientos y las observaciones del lote. Devuelve cuántos se agregaron y cuántos cambiaron.
|
||||
@@ -43,18 +44,19 @@ def guardar_plata_en(
|
||||
"huerfanos"), 0
|
||||
)
|
||||
huerfanos: set = set()
|
||||
huerfanas = 0
|
||||
nuevos: set = set()
|
||||
tocados: set = set()
|
||||
existentes = {tuple(getattr(fila, c) for c in LLAVE): fila for fila in sesion.exec(select(procedimiento))}
|
||||
existentes = {tuple(getattr(fila, c) for c in KEY): fila for fila in sesion.exec(select(procedimiento))}
|
||||
ordenes: dict[int, SQLModel] = {}
|
||||
for fila in sorted(existentes.values(), key=lambda f: f.procedimiento_id):
|
||||
if fila.clase == "orden" and fila.numero_hospital is not None:
|
||||
ordenes.setdefault(fila.numero_hospital, fila)
|
||||
|
||||
for p in plata.procedimientos:
|
||||
padre = _padre(p["padres"], existentes, ordenes)
|
||||
padre = _parent(p["padres"], existentes, ordenes)
|
||||
datos = {c: v for c, v in p.items() if c not in ("llave", "padres", "fecha_del_padre")}
|
||||
datos.update(dict(zip(LLAVE, p["llave"])))
|
||||
datos.update(dict(zip(KEY, p["llave"])))
|
||||
datos["padre_id"] = None if padre is None else padre.procedimiento_id
|
||||
if datos.get("pac_id") is None:
|
||||
if padre is None:
|
||||
@@ -71,12 +73,12 @@ def guardar_plata_en(
|
||||
existentes[p["llave"]] = fila
|
||||
cuenta["procedimientos_nuevos"] += 1
|
||||
nuevos.add(p["llave"])
|
||||
elif _actualizar(fila, datos, carga_id):
|
||||
elif _update(fila, datos, carga_id):
|
||||
cuenta["procedimientos_cambiados"] += 1
|
||||
tocados.add(p["llave"])
|
||||
if fila.clase == "orden" and fila.numero_hospital is not None:
|
||||
ordenes.setdefault(fila.numero_hospital, fila)
|
||||
ligados_tarde = _ligar_con_su_orden(existentes.values(), ordenes, carga_id)
|
||||
ligados_tarde = _link_to_its_order(existentes.values(), ordenes, carga_id)
|
||||
cuenta["procedimientos_cambiados"] += ligados_tarde
|
||||
|
||||
ids = [fila.procedimiento_id for fila in existentes.values()]
|
||||
@@ -85,9 +87,11 @@ def guardar_plata_en(
|
||||
for o in sesion.exec(select(observacion).where(observacion.procedimiento_id.in_(ids)))
|
||||
} if ids else {}
|
||||
for o in plata.observaciones:
|
||||
if o["procedimiento"] in huerfanos:
|
||||
dueno = existentes.get(o["procedimiento"])
|
||||
if dueno is None:
|
||||
# Its procedure didn't enter: it was an orphan, or it's the row of another table it attaches to.
|
||||
huerfanas += 1
|
||||
continue
|
||||
dueno = existentes[o["procedimiento"]]
|
||||
datos = {c: v for c, v in o.items() if c != "procedimiento"}
|
||||
datos["procedimiento_id"] = dueno.procedimiento_id
|
||||
if datos.get("pac_id") is None:
|
||||
@@ -96,7 +100,7 @@ def guardar_plata_en(
|
||||
if fila is None:
|
||||
sesion.add(observacion.model_validate({**datos, "carga_id": carga_id}))
|
||||
cuenta["observaciones_nuevas"] += 1
|
||||
elif _actualizar(fila, datos, carga_id):
|
||||
elif _update(fila, datos, carga_id):
|
||||
cuenta["observaciones_cambiadas"] += 1
|
||||
else:
|
||||
continue
|
||||
@@ -106,16 +110,18 @@ def guardar_plata_en(
|
||||
cuenta["huerfanos"] = len(huerfanos)
|
||||
cuenta["procedimientos_tocados"] = len(tocados) + ligados_tarde
|
||||
if huerfanos:
|
||||
registro.warning("%d procedimientos sin paciente ni padre no se escribieron (p. ej. %s).",
|
||||
log.warning("%d procedimientos sin paciente ni padre no se escribieron (p. ej. %s).",
|
||||
len(huerfanos), sorted(huerfanos)[0])
|
||||
if huerfanas:
|
||||
log.warning("%d observations whose procedure isn't in silver weren't written.", huerfanas)
|
||||
return cuenta
|
||||
|
||||
|
||||
def _ligar_con_su_orden(procedimientos, ordenes: dict, carga_id: int) -> int:
|
||||
def _link_to_its_order(procedimientos, ordenes: dict, carga_id: int) -> int:
|
||||
"""Los procedimientos sin padre que traen un número de orden, ligados a la orden que ya llegó.
|
||||
|
||||
Las órdenes pueden llegar en un lote posterior al de sus tomas (en CaCu, las tomas en
|
||||
`cargar` y las órdenes en `cargar_resultados`). Devuelve cuántos se ligaron.
|
||||
`load` y las órdenes en `cargar_resultados`). Devuelve cuántos se ligaron.
|
||||
"""
|
||||
ligados = 0
|
||||
for fila in procedimientos:
|
||||
@@ -127,7 +133,7 @@ def _ligar_con_su_orden(procedimientos, ordenes: dict, carga_id: int) -> int:
|
||||
return ligados
|
||||
|
||||
|
||||
def _padre(padres, existentes: dict, ordenes: dict):
|
||||
def _parent(padres, existentes: dict, ordenes: dict):
|
||||
"""El primer padre que se encuentre: por su llave, o la orden por su número del hospital."""
|
||||
for llave in padres:
|
||||
fila = ordenes.get(llave[1]) if llave[0] == "orden" and len(llave) == 2 else existentes.get(tuple(llave))
|
||||
@@ -136,7 +142,7 @@ def _padre(padres, existentes: dict, ordenes: dict):
|
||||
return None
|
||||
|
||||
|
||||
def _actualizar(fila: SQLModel, datos: dict, carga_id: int) -> bool:
|
||||
def _update(fila: SQLModel, datos: dict, carga_id: int) -> bool:
|
||||
"""Pone en la fila lo que cambió; si algo cambió, también su `carga_id`. Devuelve si cambió."""
|
||||
cambios = {c: v for c, v in datos.items() if getattr(fila, c) != v}
|
||||
for columna, valor in cambios.items():
|
||||
+14
-9
@@ -1,8 +1,8 @@
|
||||
"""Silver: each patient's timeline of procedures and observations, under a fixed column contract.
|
||||
|
||||
The query is injected. Each domain module binds dbt's view (`persistance.aristas.dbt`); another query, such as
|
||||
the indicator kit's `linea_de_tiempo_plata`, can still be bound with `with_query`. Readers keep the same columns and
|
||||
filters.
|
||||
The query is injected. Each domain module binds dbt's view (`persistance.edges.dbt`), which the orchestration,
|
||||
the cohort builds, the models' pipelines and the measures' strata all read; a test can bind another with
|
||||
`with_query`. Readers keep the same columns and filters.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable, Iterable
|
||||
@@ -11,7 +11,7 @@ from typing import Protocol
|
||||
|
||||
from sqlalchemy import Select
|
||||
|
||||
from persistance.materializador import SesionDeLectura
|
||||
from persistance.materializer import ReadSession
|
||||
from persistance.repository import Repository
|
||||
|
||||
TIMELINE_COLUMNS = (
|
||||
@@ -48,6 +48,14 @@ class TimelineRepository(Repository):
|
||||
"""The same repository, reading through `query`."""
|
||||
return TimelineRepository(self._session_factory, query)
|
||||
|
||||
def query(self, *, patients: Iterable[int] | None = None, until: date | None = None,
|
||||
known_until: datetime | None = None) -> Select:
|
||||
"""The `select` `read` runs, for a caller that runs it on its own session (a cohort build, in its write)."""
|
||||
if self._query is None:
|
||||
raise TimelineQueryMissing("bind a timeline query with `with_query` before reading")
|
||||
return self._query(patients=None if patients is None else list(patients), until=until,
|
||||
known_until=known_until)
|
||||
|
||||
def read(self, *, patients: Iterable[int] | None = None, until: date | None = None,
|
||||
known_until: datetime | None = None) -> list[dict]:
|
||||
"""One dict per event, keyed by `TIMELINE_COLUMNS`, in the query's order.
|
||||
@@ -55,12 +63,9 @@ class TimelineRepository(Repository):
|
||||
`until` keeps events up to that clinical date; `known_until` keeps rows already loaded at that
|
||||
moment. The query runs on a read-only session.
|
||||
"""
|
||||
if self._query is None:
|
||||
raise TimelineQueryMissing("bind a timeline query with `with_query` before reading")
|
||||
query = self._query(patients=None if patients is None else list(patients), until=until,
|
||||
known_until=known_until)
|
||||
query = self.query(patients=patients, until=until, known_until=known_until)
|
||||
with self._session_factory() as session:
|
||||
result = SesionDeLectura(session).execute(query)
|
||||
result = ReadSession(session).execute(query)
|
||||
columns = tuple(result.keys())
|
||||
if columns != TIMELINE_COLUMNS:
|
||||
raise TimelineContractError(f"expected columns {TIMELINE_COLUMNS}, got {columns}")
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
"""Plata: las vistas de un dominio (desde F6, solo `v_persona`; ADR-MD-009).
|
||||
|
||||
Las define el kit, como sentencias DDL ya armadas y en orden (`indicadores_kit.esquema.ddl_de_vistas`);
|
||||
Las define el ciclo, como sentencias DDL ya armadas y en orden (`webapi.orchestration.silver.views`, dbt's views);
|
||||
aquí solo se ejecutan, en una transacción.
|
||||
"""
|
||||
|
||||
@@ -12,13 +12,13 @@ from sqlalchemy.sql.expression import Executable
|
||||
from persistance.repository import Repository
|
||||
|
||||
|
||||
class VistasRepository(Repository):
|
||||
class ViewsRepository(Repository):
|
||||
"""Las vistas no tienen modelo: se crean o reemplazan con la DDL que se recibe."""
|
||||
|
||||
def __init__(self, session_factory):
|
||||
super().__init__(session_factory, None)
|
||||
|
||||
def construir(self, ddl: Iterable[Executable]) -> list[str]:
|
||||
def build_all(self, ddl: Iterable[Executable]) -> list[str]:
|
||||
"""Ejecuta cada sentencia en orden, en una transacción. Devuelve los nombres de las vistas de la base."""
|
||||
with self._session_factory() as sesion:
|
||||
conexion = sesion.connection()
|
||||
+14
-14
@@ -1,11 +1,11 @@
|
||||
"""El materializador de MD-20 (T0; ADR-MD-009): la E/S de una transformación.
|
||||
|
||||
Una transformación es una función pura del kit que lee por una `SesionDeLectura` y devuelve
|
||||
Una transformación es una función pura del kit que lee por una `ReadSession` y devuelve
|
||||
lo que hay que escribir. El materializador abre una sola sesión, se la da a la función de
|
||||
solo lectura, escribe lo que devolvió con un **cuerpo** y hace un solo commit, el del cuerpo.
|
||||
Sin cuerpo, solo lee: es una prueba o una lectura.
|
||||
|
||||
Es lo mismo que hace cada subclase de repositorio de `persistance/aristas/`, una sola vez:
|
||||
Es lo mismo que hace cada subclase de repositorio de `persistance/edges/`, una sola vez:
|
||||
el cuerpo es lo único que cambia de una a otra. Convive con ellas hasta MD-20 T2.
|
||||
"""
|
||||
|
||||
@@ -15,18 +15,18 @@ from typing import Any, TypeVar
|
||||
from sqlmodel import Session
|
||||
|
||||
T = TypeVar("T")
|
||||
Cuerpo = Callable[[Session, Any], Any]
|
||||
Body = Callable[[Session, Any], Any]
|
||||
|
||||
|
||||
class SoloLectura(RuntimeError):
|
||||
class ReadOnly(RuntimeError):
|
||||
"""Una transformación quiso escribir por la sesión que solo le da para leer."""
|
||||
|
||||
|
||||
class SesionDeLectura:
|
||||
class ReadSession:
|
||||
"""La sesión que recibe una transformación: lee como una `Session` y no puede escribir.
|
||||
|
||||
`add`, `add_all`, `delete`, `merge`, `flush`, `commit` y un `exec`/`execute` de INSERT,
|
||||
UPDATE o DELETE lanzan `SoloLectura`. Lo demás (`exec`, `execute`, `get`, `scalar`,
|
||||
UPDATE o DELETE lanzan `ReadOnly`. Lo demás (`exec`, `execute`, `get`, `scalar`,
|
||||
`scalars`) va a la sesión de verdad.
|
||||
"""
|
||||
|
||||
@@ -37,35 +37,35 @@ class SesionDeLectura:
|
||||
self._sesion = sesion
|
||||
|
||||
def exec(self, consulta, *args, **kwargs):
|
||||
return self._sesion.exec(self._solo_lectura(consulta), *args, **kwargs)
|
||||
return self._sesion.exec(self._read_only(consulta), *args, **kwargs)
|
||||
|
||||
def execute(self, consulta, *args, **kwargs):
|
||||
return self._sesion.execute(self._solo_lectura(consulta), *args, **kwargs)
|
||||
return self._sesion.execute(self._read_only(consulta), *args, **kwargs)
|
||||
|
||||
def __getattr__(self, nombre: str):
|
||||
if nombre in self._ESCRIBEN:
|
||||
raise SoloLectura(f"Una transformación no escribe: `{nombre}` en una SesionDeLectura.")
|
||||
raise ReadOnly(f"Una transformación no escribe: `{nombre}` en una SesionDeLectura.")
|
||||
return getattr(self._sesion, nombre)
|
||||
|
||||
@staticmethod
|
||||
def _solo_lectura(consulta):
|
||||
def _read_only(consulta):
|
||||
if getattr(consulta, "is_dml", False) and not getattr(consulta, "is_select", False):
|
||||
raise SoloLectura(f"Una transformación no escribe: {type(consulta).__name__} en una SesionDeLectura.")
|
||||
raise ReadOnly(f"Una transformación no escribe: {type(consulta).__name__} en una SesionDeLectura.")
|
||||
return consulta
|
||||
|
||||
|
||||
class Materializador:
|
||||
class Materializer:
|
||||
"""La E/S de las transformaciones de un dominio: una sesión, la función, el cuerpo y un commit."""
|
||||
|
||||
def __init__(self, session_factory: Callable[[], Session]):
|
||||
self._session_factory = session_factory
|
||||
|
||||
def materializar(self, funcion: Callable[[SesionDeLectura], T], cuerpo: Cuerpo | None = None):
|
||||
def materialize(self, funcion: Callable[[ReadSession], T], cuerpo: Body | None = None):
|
||||
"""`funcion(sesion_de_lectura)` y, con `cuerpo`, `cuerpo(sesion, lo_que_devolvio)` (escribe y hace commit).
|
||||
|
||||
Devuelve lo que devuelve el cuerpo (su resumen), o lo que devolvió la función si no hay cuerpo.
|
||||
"""
|
||||
with self._session_factory() as sesion:
|
||||
datos = funcion(SesionDeLectura(sesion))
|
||||
datos = funcion(ReadSession(sesion))
|
||||
return datos if cuerpo is None else cuerpo(sesion, datos)
|
||||
|
||||
@@ -29,65 +29,67 @@ from core.tea.indicadores.models import (
|
||||
Persona,
|
||||
)
|
||||
from core.tea.models import (
|
||||
AntecedentesMaternosGestacion,
|
||||
EegEstudio,
|
||||
EegSegmento,
|
||||
EvaluacionPsicologica,
|
||||
InstrumentoAplicado,
|
||||
NotaMedica,
|
||||
Ados2,
|
||||
Eeg,
|
||||
EegMetrica,
|
||||
EegMetricaElectrodo,
|
||||
EvaluacionNeuropediatrica,
|
||||
Mchat,
|
||||
OrdenesEstudio,
|
||||
Pacientes,
|
||||
PartoNeonatal,
|
||||
PotencialesEvocadosAuditivos,
|
||||
)
|
||||
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
|
||||
from persistance.aristas.bronce import StagingRepository
|
||||
from persistance.aristas.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
from persistance.aristas.comun import RegistroRepository
|
||||
from persistance.materializador import Materializador
|
||||
from persistance.aristas.oro import CalculoRepository, CohorteRepository, MeasureReportRepository, PublicacionRepository
|
||||
from persistance.aristas.plata import (
|
||||
CargaRepository,
|
||||
CatalogoRepository,
|
||||
ObservacionRepository,
|
||||
from persistance.edges.bronze import StagingRepository
|
||||
from persistance.edges.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
from persistance.edges.common import ReferenceRepository
|
||||
from persistance.materializer import Materializer
|
||||
from persistance.edges.gold import (
|
||||
CalculationRepository,
|
||||
CohortRepository,
|
||||
MeasureHistoryRepository,
|
||||
MeasureReportRepository,
|
||||
PublicationRepository,
|
||||
)
|
||||
from persistance.edges.silver import (
|
||||
LoadRepository,
|
||||
CatalogRepository,
|
||||
ObservationRepository,
|
||||
TimelineRepository,
|
||||
VinculosRepository,
|
||||
VistasRepository,
|
||||
LinksRepository,
|
||||
ViewsRepository,
|
||||
)
|
||||
from persistance.db import get_tea_session
|
||||
from persistance.repository import Repository
|
||||
|
||||
pacientes_repository = Repository(get_tea_session, Pacientes)
|
||||
ordenes_estudio_repository = Repository(get_tea_session, OrdenesEstudio)
|
||||
nota_medica_repository = Repository(get_tea_session, NotaMedica)
|
||||
evaluacion_psicologica_repository = Repository(get_tea_session, EvaluacionPsicologica)
|
||||
potenciales_evocados_auditivos_repository = Repository(get_tea_session, PotencialesEvocadosAuditivos)
|
||||
eeg_estudio_repository = Repository(get_tea_session, EegEstudio)
|
||||
eeg_segmento_repository = Repository(get_tea_session, EegSegmento)
|
||||
antecedentes_maternos_gestacion_repository = Repository(get_tea_session, AntecedentesMaternosGestacion)
|
||||
parto_neonatal_repository = Repository(get_tea_session, PartoNeonatal)
|
||||
instrumento_aplicado_repository = Repository(get_tea_session, InstrumentoAplicado)
|
||||
mchat_repository = Repository(get_tea_session, Mchat)
|
||||
ados2_repository = Repository(get_tea_session, Ados2)
|
||||
evaluacion_neuropediatrica_repository = Repository(get_tea_session, EvaluacionNeuropediatrica)
|
||||
eeg_repository = Repository(get_tea_session, Eeg)
|
||||
eeg_metrica_repository = Repository(get_tea_session, EegMetrica)
|
||||
eeg_metrica_electrodo_repository = Repository(get_tea_session, EegMetricaElectrodo)
|
||||
|
||||
# indicadores_kit (Core/docs/ADR-004). Se leen con get/list/count; lo que
|
||||
# se escribe va por métodos de subclases (persistance/aristas, por capa).
|
||||
# se escribe va por métodos de subclases (persistance/edges, por capa).
|
||||
persona_repository = Repository(get_tea_session, Persona)
|
||||
periodo_observacion_repository = RegistroRepository(get_tea_session, PeriodoObservacion)
|
||||
carga_repository = CargaRepository(get_tea_session, Carga, persona=Persona, procedimiento=Procedimiento, observacion=Observacion)
|
||||
def_parametro_repository = RegistroRepository(get_tea_session, DefParametro)
|
||||
dim_periodo_repository = RegistroRepository(get_tea_session, DimPeriodo)
|
||||
dim_fecha_repository = RegistroRepository(get_tea_session, DimFecha)
|
||||
dim_grupo_edad_repository = RegistroRepository(get_tea_session, DimGrupoEdad)
|
||||
periodo_observacion_repository = ReferenceRepository(get_tea_session, PeriodoObservacion)
|
||||
carga_repository = LoadRepository(get_tea_session, Carga, persona=Persona, procedimiento=Procedimiento, observacion=Observacion)
|
||||
def_parametro_repository = ReferenceRepository(get_tea_session, DefParametro)
|
||||
dim_periodo_repository = ReferenceRepository(get_tea_session, DimPeriodo)
|
||||
dim_fecha_repository = ReferenceRepository(get_tea_session, DimFecha)
|
||||
dim_grupo_edad_repository = ReferenceRepository(get_tea_session, DimGrupoEdad)
|
||||
# El oro por unidad y su catálogo (§6f, MD-19): los catálogos se reemplazan enteros desde los TOML del kit.
|
||||
cat_measure_repository = RegistroRepository(get_tea_session, CatMeasure)
|
||||
cat_measure_resultado_repository = RegistroRepository(get_tea_session, CatMeasureResultado)
|
||||
cat_measure_valor_repository = RegistroRepository(get_tea_session, CatMeasureValor)
|
||||
cat_measure_grupo_repository = RegistroRepository(get_tea_session, CatMeasureGrupo)
|
||||
cat_estrato_repository = RegistroRepository(get_tea_session, CatEstrato)
|
||||
cat_estrato_valor_repository = RegistroRepository(get_tea_session, CatEstratoValor)
|
||||
cat_measure_estrato_repository = RegistroRepository(get_tea_session, CatMeasureEstrato)
|
||||
publicacion_repository = PublicacionRepository(
|
||||
cat_measure_repository = ReferenceRepository(get_tea_session, CatMeasure)
|
||||
cat_measure_resultado_repository = ReferenceRepository(get_tea_session, CatMeasureResultado)
|
||||
cat_measure_valor_repository = ReferenceRepository(get_tea_session, CatMeasureValor)
|
||||
cat_measure_grupo_repository = ReferenceRepository(get_tea_session, CatMeasureGrupo)
|
||||
cat_estrato_repository = ReferenceRepository(get_tea_session, CatEstrato)
|
||||
cat_estrato_valor_repository = ReferenceRepository(get_tea_session, CatEstratoValor)
|
||||
cat_measure_estrato_repository = ReferenceRepository(get_tea_session, CatMeasureEstrato)
|
||||
publication_repository = PublicationRepository(
|
||||
get_tea_session, (CatEstrato, CatEstratoValor, CatMeasure, CatMeasureResultado, CatMeasureValor, CatMeasureGrupo, CatMeasureEstrato)
|
||||
)
|
||||
measure_report_unidad_repository = Repository(get_tea_session, MeasureReportUnidad)
|
||||
@@ -99,20 +101,23 @@ cat_valor_repository = Repository(get_tea_session, CatValor)
|
||||
procedimiento_repository = Repository(get_tea_session, Procedimiento)
|
||||
observacion_repository = Repository(get_tea_session, Observacion)
|
||||
|
||||
# Las aristas del grafo (persistance/aristas): una sesión por operación.
|
||||
# Las aristas del grafo (persistance/edges): una sesión por operación.
|
||||
staging_repository = StagingRepository(get_tea_session)
|
||||
catalogo_repository = CatalogoRepository(get_tea_session, CatEstudio, CatResultado, CatValor)
|
||||
calculo_repository = CalculoRepository(get_tea_session, MeasureReport, periodo=DimPeriodo)
|
||||
observar_repository = ObservacionRepository(get_tea_session, PeriodoObservacion)
|
||||
vistas_repository = VistasRepository(get_tea_session)
|
||||
vinculos_repository = VinculosRepository(get_tea_session)
|
||||
catalog_repository = CatalogRepository(get_tea_session, CatEstudio, CatResultado, CatValor)
|
||||
calculation_repository = CalculationRepository(get_tea_session, MeasureReport, periodo=DimPeriodo)
|
||||
history_repository = MeasureHistoryRepository(get_tea_session, MeasureReport, unit_model=MeasureReportUnidad,
|
||||
stratum_model=MeasureReportUnidadEstrato,
|
||||
value_model=CatEstratoValor)
|
||||
observation_period_repository = ObservationRepository(get_tea_session, PeriodoObservacion)
|
||||
views_repository = ViewsRepository(get_tea_session)
|
||||
links_repository = LinksRepository(get_tea_session)
|
||||
# dbt's timeline view and compiled queries; `with_query` still binds another timeline query.
|
||||
timeline_repository = DbtTimelineRepository(get_tea_session, "tea")
|
||||
dbt_query_repository = DbtQueryRepository(get_tea_session)
|
||||
cohorte_repository = CohorteRepository(
|
||||
cohort_repository = CohortRepository(
|
||||
get_tea_session,
|
||||
TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote, EvaluacionRiesgo),
|
||||
)
|
||||
|
||||
# La E/S de las transformaciones de MD-20 (T0): una sesión, la función y un cuerpo de escritura.
|
||||
materializador = Materializador(get_tea_session)
|
||||
materializer = Materializer(get_tea_session)
|
||||
|
||||
@@ -0,0 +1,486 @@
|
||||
"""tea staging by study
|
||||
|
||||
One staging table per kind of study: `mchat`, `ados2`, `evaluacion_neuropediatrica` and `eeg`, with the EEG's
|
||||
metrics and electrode values from its analysis (`eeg_metrica`, `eeg_metrica_electrodo`). `pacientes` and
|
||||
`ordenes_estudio` keep their rows and lose the columns nothing reads; the orders' study codes move to the new
|
||||
catalog (`ADOS2`, `NEUROPEDIATRIA`, `EEG`). The psychological evaluation, instruments, EEG segments, auditory
|
||||
evoked potentials, birth, maternal history and medical notes go, with their rows: staging is reloaded from the
|
||||
source.
|
||||
|
||||
Revision ID: f2b6d1e8c934
|
||||
Revises: a3e1c7b90d12
|
||||
Create Date: 2026-11-12 13:44:52.541497
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import mysql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'f2b6d1e8c934'
|
||||
down_revision = 'a3e1c7b90d12'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
# The orders' study codes, old -> new.
|
||||
STUDY_CODES = {"EVALUACION_PSICOLOGICA_TEA": "ADOS2", "ELECTROENCEFALOGRAMA": "EEG"}
|
||||
|
||||
|
||||
def _recode(codes: dict[str, str]) -> None:
|
||||
orders = sa.table("ordenes_estudio", sa.column("ord_tipo_estudio", sa.Text()))
|
||||
for old, new in codes.items():
|
||||
op.execute(orders.update().where(orders.c.ord_tipo_estudio == old).values(ord_tipo_estudio=new))
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table('ados2',
|
||||
sa.Column('ado_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('ado_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_ord_id', sa.Text(), nullable=True),
|
||||
sa.Column('ado_fecha', sa.Date(), nullable=True),
|
||||
sa.Column('ado_modulo', sa.Text(), nullable=True),
|
||||
sa.Column('ado_algoritmo', sa.Text(), nullable=True),
|
||||
sa.Column('ado_css', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_clasificacion', sa.Text(), nullable=True),
|
||||
sa.Column('ado_sa_a2', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_a6', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_a7', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_a8', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b1', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b2', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b3', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b4', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b5', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b6', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b7', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b8', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b9', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b10', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b11', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b12', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b13', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b14', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b15', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b16b', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_sa_b18', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_rrb_a3', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_rrb_a4', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_rrb_a5', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_rrb_d1', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_rrb_d2', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_rrb_d4', sa.Integer(), nullable=True),
|
||||
sa.Column('ado_rrb_d5', sa.Integer(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('ado_id')
|
||||
)
|
||||
op.create_table('eeg',
|
||||
sa.Column('eeg_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('eeg_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_ord_id', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_id_registro_laboratorio', sa.String(length=64), nullable=True),
|
||||
sa.Column('eeg_fecha_estudio', sa.Date(), nullable=True),
|
||||
sa.Column('eeg_con_sueno', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_canales', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_duracion_min', sa.Float(), nullable=True),
|
||||
sa.Column('eeg_canales_amplitud', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_canales_alta_frecuencia', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_canales_correlacion', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_canales_sin_senal', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_ruido_linea_db', sa.Float(), nullable=True),
|
||||
sa.Column('eeg_estudio', sa.LargeBinary().with_variant(mysql.LONGBLOB(), 'mariadb').with_variant(mysql.LONGBLOB(), 'mysql'), nullable=True),
|
||||
sa.PrimaryKeyConstraint('eeg_id')
|
||||
)
|
||||
with op.batch_alter_table('eeg', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_eeg_eeg_id_registro_laboratorio'), ['eeg_id_registro_laboratorio'], unique=False)
|
||||
|
||||
op.create_table('eeg_metrica',
|
||||
sa.Column('met_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('met_eeg_id', sa.Text(), nullable=True),
|
||||
sa.Column('met_codigo', sa.Text(), nullable=True),
|
||||
sa.Column('met_valor', sa.Float(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('met_id')
|
||||
)
|
||||
op.create_table('eeg_metrica_electrodo',
|
||||
sa.Column('mel_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('mel_met_id', sa.Text(), nullable=True),
|
||||
sa.Column('mel_electrodo', sa.Text(), nullable=True),
|
||||
sa.Column('mel_valor', sa.Float(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('mel_id')
|
||||
)
|
||||
op.create_table('evaluacion_neuropediatrica',
|
||||
sa.Column('neu_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('neu_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('neu_ord_id', sa.Text(), nullable=True),
|
||||
sa.Column('neu_fecha', sa.Date(), nullable=True),
|
||||
sa.Column('neu_cie_codigo', sa.Text(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('neu_id')
|
||||
)
|
||||
op.create_table('mchat',
|
||||
sa.Column('mch_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('mch_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('mch_ord_id', sa.Text(), nullable=True),
|
||||
sa.Column('mch_fecha', sa.Date(), nullable=True),
|
||||
sa.Column('mch_puntaje', sa.Integer(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('mch_id')
|
||||
)
|
||||
op.drop_table('evaluacion_psicologica')
|
||||
with op.batch_alter_table('nota_medica', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_nota_medica_nm_id_hospital'))
|
||||
|
||||
op.drop_table('nota_medica')
|
||||
with op.batch_alter_table('eeg_estudio', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_eeg_estudio_eeg_id_registro_laboratorio'))
|
||||
|
||||
op.drop_table('eeg_estudio')
|
||||
op.drop_table('parto_neonatal')
|
||||
op.drop_table('potenciales_evocados_auditivos')
|
||||
op.drop_table('antecedentes_maternos_gestacion')
|
||||
op.drop_table('eeg_segmento')
|
||||
op.drop_table('instrumento_aplicado')
|
||||
with op.batch_alter_table('ordenes_estudio', schema=None) as batch_op:
|
||||
batch_op.drop_column('ord_nota_medica_id')
|
||||
batch_op.drop_column('ord_proveedor')
|
||||
batch_op.drop_column('ord_fecha_resultado')
|
||||
batch_op.drop_column('ord_especialidad')
|
||||
batch_op.drop_column('ord_ventana_madurativa')
|
||||
batch_op.drop_column('ord_diagnostico_asignado')
|
||||
batch_op.drop_column('ord_estatus')
|
||||
batch_op.drop_column('ord_pdf_ruta')
|
||||
batch_op.drop_column('ord_updated_at')
|
||||
batch_op.drop_column('ord_dias_vigencia')
|
||||
batch_op.drop_column('ord_fecha_realizacion')
|
||||
batch_op.drop_column('ord_fuente_sistema')
|
||||
batch_op.drop_column('ord_medico_solicitante')
|
||||
batch_op.drop_column('ord_cie_asignado')
|
||||
batch_op.drop_column('ord_fecha_vencimiento')
|
||||
batch_op.drop_column('ord_created_at')
|
||||
batch_op.drop_column('ord_dias_espera')
|
||||
batch_op.drop_column('ord_edad_meses')
|
||||
batch_op.drop_column('ord_observaciones')
|
||||
|
||||
with op.batch_alter_table('pacientes', schema=None) as batch_op:
|
||||
batch_op.drop_column('pac_fuente_sistema')
|
||||
batch_op.drop_column('pac_dependencia')
|
||||
batch_op.drop_column('pac_parentesco')
|
||||
batch_op.drop_column('pac_codigo_postal_vigente')
|
||||
batch_op.drop_column('pac_created_at')
|
||||
batch_op.drop_column('pac_sexo')
|
||||
batch_op.drop_column('pac_updated_at')
|
||||
batch_op.drop_column('pac_id_titular')
|
||||
|
||||
_recode(STUDY_CODES)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('pacientes', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('pac_id_titular', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('pac_updated_at', sa.DateTime(), nullable=True))
|
||||
batch_op.add_column(sa.Column('pac_sexo', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('pac_created_at', sa.DateTime(), nullable=True))
|
||||
batch_op.add_column(sa.Column('pac_codigo_postal_vigente', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('pac_parentesco', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('pac_dependencia', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('pac_fuente_sistema', sa.Text(), nullable=True))
|
||||
|
||||
with op.batch_alter_table('ordenes_estudio', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('ord_observaciones', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_edad_meses', sa.Float(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_dias_espera', sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_created_at', sa.DateTime(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_fecha_vencimiento', sa.Date(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_cie_asignado', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_medico_solicitante', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_fuente_sistema', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_fecha_realizacion', sa.Date(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_dias_vigencia', sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_updated_at', sa.DateTime(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_pdf_ruta', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_estatus', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_diagnostico_asignado', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_ventana_madurativa', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_especialidad', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_fecha_resultado', sa.Date(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_proveedor', sa.Text(), nullable=True))
|
||||
batch_op.add_column(sa.Column('ord_nota_medica_id', sa.Text(), nullable=True))
|
||||
|
||||
op.create_table('instrumento_aplicado',
|
||||
sa.Column('ins_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('ins_psi_id', sa.Text(), nullable=True),
|
||||
sa.Column('ins_instrumento', sa.Text(), nullable=True),
|
||||
sa.Column('ins_informante', sa.Text(), nullable=True),
|
||||
sa.Column('ins_area', sa.Text(), nullable=True),
|
||||
sa.Column('ins_interpretacion', sa.Text(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('ins_id')
|
||||
)
|
||||
op.create_table('eeg_segmento',
|
||||
sa.Column('seg_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('seg_eeg_id', sa.Text(), nullable=True),
|
||||
sa.Column('seg_estado', sa.Text(), nullable=True),
|
||||
sa.Column('seg_inicio_s', sa.Float(), nullable=True),
|
||||
sa.Column('seg_fin_s', sa.Float(), nullable=True),
|
||||
sa.Column('seg_duracion_s', sa.Float(), nullable=True),
|
||||
sa.Column('seg_fuente', sa.Text(), nullable=True),
|
||||
sa.Column('seg_frecuencia_flash_hz', sa.Float(), nullable=True),
|
||||
sa.Column('seg_n_destellos', sa.Integer(), nullable=True),
|
||||
sa.Column('seg_cobertura', sa.Float(), nullable=True),
|
||||
sa.Column('seg_rms_uv', sa.Float(), nullable=True),
|
||||
sa.Column('seg_emg', sa.Float(), nullable=True),
|
||||
sa.Column('seg_p2p_max_uv', sa.Float(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('seg_id')
|
||||
)
|
||||
op.create_table('antecedentes_maternos_gestacion',
|
||||
sa.Column('amg_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('amg_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_id_madre_seudonimo', sa.Text(), nullable=True),
|
||||
sa.Column('amg_fuente_antecedente', sa.Text(), nullable=True),
|
||||
sa.Column('amg_flag_vinculo_verificado', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_imc_pregestacional', sa.Float(), nullable=True),
|
||||
sa.Column('amg_categoria_peso_materno', sa.Text(), nullable=True),
|
||||
sa.Column('amg_tabaquismo_gestacion', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_acido_folico_preconcepcional', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_intervalo_intergenesico_meses', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_antecedente_aborto', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_embarazo_multiple', sa.Text(), nullable=True),
|
||||
sa.Column('amg_infeccion_gestacion', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_infeccion_tipo', sa.Text(), nullable=True),
|
||||
sa.Column('amg_infeccion_hospitalizacion', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_diabetes_gestacional', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_hipertension_preeclampsia', sa.Text(), nullable=True),
|
||||
sa.Column('amg_hipotiroidismo', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_hipertiroidismo', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_incompatibilidad_rh', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_crisis_convulsivas', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_proceso_proinflamatorio', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_enfermedad_autoinmune', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_migrana', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_asma', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_hipoxia_materna', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_estres_agudo', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_trastorno_neurologico', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_liquido_amniotico', sa.Text(), nullable=True),
|
||||
sa.Column('amg_medicamentos_gestacion', sa.Text(), nullable=True),
|
||||
sa.Column('amg_farmaco_riesgo_neurodesarrollo', sa.Integer(), nullable=True),
|
||||
sa.Column('amg_observaciones', sa.Text(), nullable=True),
|
||||
sa.Column('amg_ocr_confianza', sa.Float(), nullable=True),
|
||||
sa.Column('amg_nlp_version', sa.Text(), nullable=True),
|
||||
sa.Column('amg_created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('amg_updated_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('amg_fuente_sistema', sa.Text(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('amg_id')
|
||||
)
|
||||
op.create_table('potenciales_evocados_auditivos',
|
||||
sa.Column('pea_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('pea_ord_id', sa.Text(), nullable=True),
|
||||
sa.Column('pea_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('pea_fecha_estudio', sa.Date(), nullable=True),
|
||||
sa.Column('pea_medico_interpreta', sa.Text(), nullable=True),
|
||||
sa.Column('pea_umbral_od', sa.Integer(), nullable=True),
|
||||
sa.Column('pea_umbral_oi', sa.Integer(), nullable=True),
|
||||
sa.Column('pea_latencia_v_od', sa.Float(), nullable=True),
|
||||
sa.Column('pea_latencia_v_oi', sa.Float(), nullable=True),
|
||||
sa.Column('pea_interpico_i_v_od', sa.Float(), nullable=True),
|
||||
sa.Column('pea_interpico_i_v_oi', sa.Float(), nullable=True),
|
||||
sa.Column('pea_grado_hipoacusia', sa.Text(), nullable=True),
|
||||
sa.Column('pea_conclusion_texto', sa.Text(), nullable=True),
|
||||
sa.Column('pea_flag_diferencial_auditivo', sa.Integer(), nullable=True),
|
||||
sa.Column('pea_ocr_confianza', sa.Float(), nullable=True),
|
||||
sa.Column('pea_created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('pea_updated_at', sa.DateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('pea_id')
|
||||
)
|
||||
op.create_table('parto_neonatal',
|
||||
sa.Column('pnn_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('pnn_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_fuente_antecedente', sa.Text(), nullable=True),
|
||||
sa.Column('pnn_tipo_parto', sa.Text(), nullable=True),
|
||||
sa.Column('pnn_complicaciones_intraparto', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_complicacion_tipo', sa.Text(), nullable=True),
|
||||
sa.Column('pnn_peso_nacer_g', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_talla_nacer_cm', sa.Float(), nullable=True),
|
||||
sa.Column('pnn_perimetro_cefalico_nacer_cm', sa.Float(), nullable=True),
|
||||
sa.Column('pnn_edad_gestacional_sem', sa.Float(), nullable=True),
|
||||
sa.Column('pnn_clasificacion_eg', sa.Text(), nullable=True),
|
||||
sa.Column('pnn_tamano_para_eg', sa.Text(), nullable=True),
|
||||
sa.Column('pnn_peso_nacer_zscore', sa.Float(), nullable=True),
|
||||
sa.Column('pnn_apgar_1min', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_apgar_5min', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_ingreso_ucin', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_dias_ucin', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_encefalopatia_hipoxico_isquemica', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_hipotermia_nacer', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_hiperbilirrubinemia', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_fototerapia', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_hipoglucemia_neonatal', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_anoxia', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_sindrome_congenito', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_sindrome_congenito_desc', sa.Text(), nullable=True),
|
||||
sa.Column('pnn_flag_riesgo_neonatal', sa.Integer(), nullable=True),
|
||||
sa.Column('pnn_observaciones', sa.Text(), nullable=True),
|
||||
sa.Column('pnn_ocr_confianza', sa.Float(), nullable=True),
|
||||
sa.Column('pnn_nlp_version', sa.Text(), nullable=True),
|
||||
sa.Column('pnn_created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('pnn_updated_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('pnn_fuente_sistema', sa.Text(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('pnn_id')
|
||||
)
|
||||
op.create_table('eeg_estudio',
|
||||
sa.Column('eeg_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('eeg_ord_id', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_reporte_disponible', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_fuente_interpretacion', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_fecha_nacimiento_archivo', sa.Date(), nullable=True),
|
||||
sa.Column('eeg_edad_meses', sa.Float(), nullable=True),
|
||||
sa.Column('eeg_fecha_estudio', sa.Date(), nullable=True),
|
||||
sa.Column('eeg_fecha_reporte', sa.Date(), nullable=True),
|
||||
sa.Column('eeg_dias_respuesta', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_medico_interpreta', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_estado_registro', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_privacion_sueno', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_sedacion', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_sedacion_farmaco', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_duracion_min', sa.Float(), nullable=True),
|
||||
sa.Column('eeg_calidad_tecnica', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_descripcion_senal', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_ritmo_base_frecuencia', sa.Float(), nullable=True),
|
||||
sa.Column('eeg_ritmo_base_amplitud', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_simetria', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_anormalidad_presente', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_actividad_epileptiforme', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_tipo_grafoelemento', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_distribucion_anormalidad', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_localizacion', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_activacion_sueno', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_lentificacion', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_crisis_registradas', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_respuesta_fotoestimulacion', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_conclusion_texto', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_conclusion_categoria', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_id_registro_laboratorio', sa.String(length=64), nullable=True),
|
||||
sa.Column('eeg_pdf_ruta', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_ocr_confianza', sa.Float(), nullable=True),
|
||||
sa.Column('eeg_nlp_version', sa.Text(), nullable=True),
|
||||
sa.Column('eeg_utilizable', sa.Integer(), nullable=True),
|
||||
sa.Column('eeg_estudio', sa.LargeBinary().with_variant(mysql.LONGBLOB(), 'mariadb').with_variant(mysql.LONGBLOB(), 'mysql'), nullable=True),
|
||||
sa.Column('eeg_created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('eeg_updated_at', sa.DateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('eeg_id')
|
||||
)
|
||||
with op.batch_alter_table('eeg_estudio', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_eeg_estudio_eeg_id_registro_laboratorio'), ['eeg_id_registro_laboratorio'], unique=False)
|
||||
|
||||
op.create_table('nota_medica',
|
||||
sa.Column('nm_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('nm_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('nm_id_hospital', sa.String(length=64), nullable=True),
|
||||
sa.Column('nm_nota_previa_id', sa.Text(), nullable=True),
|
||||
sa.Column('nm_tipo_nota', sa.Text(), nullable=True),
|
||||
sa.Column('nm_especialidad', sa.Text(), nullable=True),
|
||||
sa.Column('nm_fecha', sa.Date(), nullable=True),
|
||||
sa.Column('nm_edad_meses', sa.Float(), nullable=True),
|
||||
sa.Column('nm_ventana_madurativa', sa.Text(), nullable=True),
|
||||
sa.Column('nm_medico_tratante', sa.Text(), nullable=True),
|
||||
sa.Column('nm_motivo_consulta', sa.Text(), nullable=True),
|
||||
sa.Column('nm_interrogatorio', sa.Text(), nullable=True),
|
||||
sa.Column('nm_regresion_referida', sa.Integer(), nullable=True),
|
||||
sa.Column('nm_antecedente_familiar_tea', sa.Integer(), nullable=True),
|
||||
sa.Column('nm_perimetro_cefalico', sa.Float(), nullable=True),
|
||||
sa.Column('nm_diagnostico_texto', sa.Text(), nullable=True),
|
||||
sa.Column('nm_cie_codigo', sa.Text(), nullable=True),
|
||||
sa.Column('nm_cie_descripcion', sa.Text(), nullable=True),
|
||||
sa.Column('nm_tratamiento_texto', sa.Text(), nullable=True),
|
||||
sa.Column('nm_receta', sa.Text(), nullable=True),
|
||||
sa.Column('nm_plan_estudios', sa.Text(), nullable=True),
|
||||
sa.Column('nm_pronostico', sa.Text(), nullable=True),
|
||||
sa.Column('nm_observaciones', sa.Text(), nullable=True),
|
||||
sa.Column('nm_masa_corporal', sa.Float(), nullable=True),
|
||||
sa.Column('nm_talla', sa.Float(), nullable=True),
|
||||
sa.Column('nm_imc_visita', sa.Float(), nullable=True),
|
||||
sa.Column('nm_frecuencia_cardiaca', sa.Integer(), nullable=True),
|
||||
sa.Column('nm_frecuencia_respiratoria', sa.Integer(), nullable=True),
|
||||
sa.Column('nm_presion_arterial_sistolica', sa.Integer(), nullable=True),
|
||||
sa.Column('nm_presion_arterial_diastolica', sa.Integer(), nullable=True),
|
||||
sa.Column('nm_temperatura', sa.Float(), nullable=True),
|
||||
sa.Column('nm_pdf_ruta', sa.Text(), nullable=True),
|
||||
sa.Column('nm_created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('nm_updated_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('nm_fuente_sistema', sa.Text(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('nm_id')
|
||||
)
|
||||
with op.batch_alter_table('nota_medica', schema=None) as batch_op:
|
||||
batch_op.create_index(batch_op.f('ix_nota_medica_nm_id_hospital'), ['nm_id_hospital'], unique=False)
|
||||
|
||||
op.create_table('evaluacion_psicologica',
|
||||
sa.Column('psi_id', sa.String(length=36), nullable=False),
|
||||
sa.Column('psi_ord_id', sa.Text(), nullable=True),
|
||||
sa.Column('psi_pac_id', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_fecha_entrevista_inicial', sa.Date(), nullable=True),
|
||||
sa.Column('psi_fecha_ados2', sa.Date(), nullable=True),
|
||||
sa.Column('psi_fecha_evaluacion', sa.Date(), nullable=True),
|
||||
sa.Column('psi_psicologo', sa.Text(), nullable=True),
|
||||
sa.Column('psi_edad_meses', sa.Float(), nullable=True),
|
||||
sa.Column('psi_ventana_madurativa', sa.Text(), nullable=True),
|
||||
sa.Column('psi_instrumento_tamizaje', sa.Text(), nullable=True),
|
||||
sa.Column('psi_tamizaje_puntaje', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_tamizaje_riesgo', sa.Text(), nullable=True),
|
||||
sa.Column('psi_ados2_modulo', sa.Text(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_a2', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_a6', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_a7', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_a8', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b1', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b2', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b3', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b4', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b5', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b6', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b7', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b8', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b9', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b10', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b11', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b12', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b13', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b14', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b15', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b16b', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa_b18', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_rrb_a3', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_rrb_a4', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_rrb_a5', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_rrb_d1', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_rrb_d2', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_rrb_d4', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_rrb_d5', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_sa', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_rrb', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_total', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_css', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_css_sa', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_css_rrb', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_ados2_clasificacion', sa.Text(), nullable=True),
|
||||
sa.Column('psi_rgd', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_cociente_desarrollo', sa.Float(), nullable=True),
|
||||
sa.Column('psi_css_umbral_aplicado', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_caso_confirmado', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_cars_total', sa.Float(), nullable=True),
|
||||
sa.Column('psi_otros_instrumentos', sa.Text(), nullable=True),
|
||||
sa.Column('psi_regresion_desarrollo', sa.Integer(), nullable=True),
|
||||
sa.Column('psi_diagnostico_texto', sa.Text(), nullable=True),
|
||||
sa.Column('psi_ocr_confianza', sa.Float(), nullable=True),
|
||||
sa.Column('psi_nlp_version', sa.Text(), nullable=True),
|
||||
sa.Column('psi_created_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('psi_updated_at', sa.DateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('psi_id')
|
||||
)
|
||||
op.drop_table('mchat')
|
||||
op.drop_table('evaluacion_neuropediatrica')
|
||||
op.drop_table('eeg_metrica_electrodo')
|
||||
op.drop_table('eeg_metrica')
|
||||
with op.batch_alter_table('eeg', schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f('ix_eeg_eeg_id_registro_laboratorio'))
|
||||
|
||||
op.drop_table('eeg')
|
||||
op.drop_table('ados2')
|
||||
|
||||
_recode({new: old for old, new in STUDY_CODES.items()})
|
||||
@@ -23,13 +23,13 @@ def _nodes(*functions, **settings):
|
||||
return driver.Builder().with_modules(module).with_config(settings).build().list_available_variables()
|
||||
|
||||
|
||||
@tag(layer="bronce", owner="externo")
|
||||
@tag(layer="bronze", owner="external")
|
||||
def staging() -> Asset:
|
||||
"""Source asset (bronze, external): what the ingestion leaves."""
|
||||
return Asset("staging")
|
||||
|
||||
|
||||
@tag(layer="plata", owner="python")
|
||||
@tag(layer="silver", owner="python")
|
||||
def hechos(staging: Asset) -> Asset:
|
||||
"""Silver asset read from `staging`."""
|
||||
return Asset("hechos", 120)
|
||||
@@ -37,19 +37,19 @@ def hechos(staging: Asset) -> Asset:
|
||||
|
||||
@config.when(registro_owner="python")
|
||||
@extract_fields({"def_parametro": Asset, "dim_periodo": Asset})
|
||||
@tag(layer="plata", owner="python")
|
||||
@tag(layer="silver", owner="python")
|
||||
def registro__python() -> dict:
|
||||
"""One function, two silver assets (`def_parametro`, `dim_periodo`), selected by `registro_owner="python"`."""
|
||||
return {"def_parametro": Asset("def_parametro"), "dim_periodo": Asset("dim_periodo")}
|
||||
|
||||
|
||||
@tag(layer="oro", owner="python")
|
||||
@tag(layer="gold", owner="python")
|
||||
def measure_report(hechos: Asset, def_parametro: Asset, dim_periodo: Asset) -> Asset:
|
||||
"""Gold asset that reads `hechos` and the two `registro` assets."""
|
||||
"""Gold asset that reads `hechos` and the two `registry` assets."""
|
||||
return Asset("measure_report", 37)
|
||||
|
||||
|
||||
@tag(layer="plata", owner="python", depends_on="measure_report")
|
||||
@tag(layer="silver", owner="python", depends_on="measure_report")
|
||||
def periodo_observacion(hechos: Asset, measure_report: Asset) -> Asset:
|
||||
"""Silver asset that reads `hechos` and waits for `measure_report` without using its data (`depends_on`)."""
|
||||
return Asset("periodo_observacion")
|
||||
@@ -101,7 +101,7 @@ def test_depends_on_must_name_a_parameter():
|
||||
|
||||
Fails if `validate` stops comparing the tag with the node's dependencies.
|
||||
"""
|
||||
@tag(layer="plata", owner="python", depends_on="measure_report")
|
||||
@tag(layer="silver", owner="python", depends_on="measure_report")
|
||||
def periodo_observacion(hechos: Asset) -> Asset:
|
||||
"""Declares `depends_on` on an asset that isn't one of its parameters."""
|
||||
return Asset("periodo_observacion")
|
||||
@@ -116,7 +116,7 @@ def test_every_problem_is_reported_at_once():
|
||||
|
||||
Fails if it raises on the first problem or changes the one-line-per-problem format.
|
||||
"""
|
||||
@tag(layer="plata")
|
||||
@tag(layer="silver")
|
||||
def cohorte_miembro(staging: Asset) -> Asset:
|
||||
"""Reads `staging`, which nobody produces, and has no owner: two problems."""
|
||||
return Asset("cohorte_miembro")
|
||||
@@ -128,14 +128,14 @@ def test_every_problem_is_reported_at_once():
|
||||
|
||||
def test_the_diagram_draws_assets_and_skips_the_functions_between_them():
|
||||
"""Pins down: `mermaid` draws one box per asset with its layer and owner, an arrow from producer to
|
||||
reader, a dotted arrow for `depends_on`, and skips functions that don't produce an asset (`registro`).
|
||||
reader, a dotted arrow for `depends_on`, and skips functions that don't produce an asset (`registry`).
|
||||
|
||||
Fails if the diagram format changes, intermediate functions appear, or the order-only arrow stops
|
||||
being dotted.
|
||||
"""
|
||||
diagram = mermaid(_nodes(*CYCLE, registro_owner="python"))
|
||||
assert diagram.startswith("flowchart LR")
|
||||
assert 'hechos["hechos<br/>plata · python"]' in diagram
|
||||
assert 'hechos["hechos<br/>silver · python"]' in diagram
|
||||
assert " staging --> hechos" in diagram
|
||||
assert " def_parametro --> measure_report" in diagram
|
||||
assert "registro" not in diagram.replace("registro_owner", "")
|
||||
@@ -144,8 +144,8 @@ def test_the_diagram_draws_assets_and_skips_the_functions_between_them():
|
||||
|
||||
|
||||
def test_enum_values_are_the_tag_values():
|
||||
"""Pins down: the enum values are the strings written in the tags (`"plata"`, `"dbt"`).
|
||||
"""Pins down: the enum values are the strings written in the tags (`"silver"`, `"dbt"`).
|
||||
|
||||
Fails if a value is renamed, which would invalidate every tag already written.
|
||||
"""
|
||||
assert Layer.SILVER == "plata" and Owner.DBT == "dbt"
|
||||
assert Layer.SILVER == "silver" and Owner.DBT == "dbt"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""What this module covers: the cohort-build reads of `CohorteRepository`: `latest_build`, `members`,
|
||||
"""What this module covers: the cohort-build reads of `CohortRepository`: `latest_build`, `members`,
|
||||
`build` and `builds`.
|
||||
|
||||
Fixtures: `repository`, an in-memory SQLite database with the CaCu tables and three builds; `_build`
|
||||
@@ -21,7 +21,7 @@ from core.cacu.indicadores.models import (
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
from sqlmodel import Session, create_engine
|
||||
|
||||
from persistance.aristas.oro import CohortBuild, CohorteRepository, CohortMember
|
||||
from persistance.edges.gold import CohortBuild, CohortRepository, CohortMember
|
||||
|
||||
TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote,
|
||||
EvaluacionRiesgo)
|
||||
@@ -59,7 +59,7 @@ def repository():
|
||||
indice_fuente_id="99"),
|
||||
])
|
||||
session.commit()
|
||||
return CohorteRepository(lambda: Session(engine), TABLES)
|
||||
return CohortRepository(lambda: Session(engine), TABLES)
|
||||
|
||||
|
||||
def test_latest_build_of_a_cohort_among_several(repository):
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
"""What this module covers: `persistance.aristas.dbt`, reading what dbt owns: the timeline from its view
|
||||
"""What this module covers: `persistance.edges.dbt`, reading what dbt owns: the timeline from its view
|
||||
(`DbtTimelineRepository`) and the queries it compiled (`DbtQueryRepository`).
|
||||
|
||||
Fixtures: `database`, an in-memory SQLite database with a table behind a `cacu_linea_de_tiempo` view holding three
|
||||
events, dates as text as dbt-sqlite leaves them, and a session factory over it.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.pool import StaticPool
|
||||
from sqlmodel import Session
|
||||
|
||||
from persistance.aristas.dbt import DbtQueryRepository, DbtRelationError, DbtTimelineRepository
|
||||
from persistance.aristas.plata import TIMELINE_COLUMNS
|
||||
from persistance.edges.dbt import DbtQueryRepository, DbtRelationError, DbtTimelineRepository
|
||||
from persistance.edges.silver import TIMELINE_COLUMNS
|
||||
|
||||
EVENTS = [
|
||||
(2, "2025-02-01", "2025-06-01 00:00:00", "procedimiento", "citologia", "citologia_cervical", None, None, "citologiacervical", "3"),
|
||||
(1, "2025-03-01", "2025-03-02 00:00:00", "medicion", "biopsia", "cin", "LIEAG", None, "biopsiacervical", "7"),
|
||||
(1, "2025-01-05", "2025-01-06 00:00:00", "procedimiento", "citologia", "citologia_cervical", "SATISFACTORIA", None, "citologiacervical", "1"),
|
||||
(2, "2025-02-01", "2025-06-01T00:00:00+00:00", "procedimiento", "citologia", "citologia_cervical", None, None, "citologiacervical", "3"),
|
||||
(1, "2025-03-01", "2025-03-02T00:00:00+00:00", "medicion", "biopsia", "cin", "LIEAG", None, "biopsiacervical", "7"),
|
||||
(1, "2025-01-05", "2025-01-06T00:00:00+00:00", "procedimiento", "citologia", "citologia_cervical", "SATISFACTORIA", None, "citologiacervical", "1"),
|
||||
]
|
||||
|
||||
|
||||
@@ -46,13 +46,14 @@ def test_timeline_comes_from_the_view_in_order_with_dates(database):
|
||||
|
||||
|
||||
def test_filters_run_in_the_query(database):
|
||||
"""Pins down: `patients`, `until` and `known_until` each narrow the rows. Fails if a filter is ignored."""
|
||||
"""Pins down: `patients`, `until` and `known_until` each narrow the rows, the last as an aware datetime against the
|
||||
load times as stored. Fails if a filter is ignored or the load time is compared as text."""
|
||||
_, session_factory = database
|
||||
repository = DbtTimelineRepository(session_factory, "cacu")
|
||||
|
||||
assert {row["pac_id"] for row in repository.read(patients=[2])} == {2}
|
||||
assert [row["fuente_id"] for row in repository.read(until=date(2025, 2, 1))] == ["1", "3"]
|
||||
assert [row["fuente_id"] for row in repository.read(known_until=datetime(2025, 3, 1))] == ["1"]
|
||||
assert [row["fuente_id"] for row in repository.read(known_until=datetime(2025, 3, 1, tzinfo=timezone.utc))] == ["1"]
|
||||
|
||||
|
||||
def test_a_missing_view_names_the_dbt_command(database):
|
||||
@@ -74,6 +75,27 @@ def test_a_compiled_query_gives_one_dict_per_row(database):
|
||||
assert rows == [{"pac_id": 1}]
|
||||
|
||||
|
||||
def test_a_query_compiled_with_placeholders_takes_its_values_and_lists(database):
|
||||
"""Pins down: a query compiled with bind placeholders runs with the values given, a list filling `in :name`, so
|
||||
one compiled query serves every period. Fails if `parameters` stops being bound or lists stop expanding."""
|
||||
_, session_factory = database
|
||||
rows = DbtQueryRepository(session_factory).read(
|
||||
"select pac_id, fecha from cacu_linea_de_tiempo where fecha >= :desde and tipo in :tipos order by fecha",
|
||||
{"desde": "2025-02-01", "tipos": ["citologia", "biopsia"]})
|
||||
|
||||
assert rows == [{"pac_id": 2, "fecha": "2025-02-01"}, {"pac_id": 1, "fecha": "2025-03-01"}]
|
||||
|
||||
|
||||
def test_an_empty_result_keeps_its_columns(database):
|
||||
"""Pins down: a query with no rows still says which columns it selects, so whoever reads it can count zero.
|
||||
Fails if `rows` builds the column names from the rows."""
|
||||
_, session_factory = database
|
||||
columns, rows = DbtQueryRepository(session_factory).rows(
|
||||
"select pac_id, tipo from cacu_linea_de_tiempo where fecha > :hasta", {"hasta": "2030-01-01"})
|
||||
|
||||
assert (columns, rows) == (["pac_id", "tipo"], [])
|
||||
|
||||
|
||||
def test_reading_writes_nothing(database):
|
||||
"""Pins down: both repositories read on a read-only session and leave the database as it was. Fails if a read
|
||||
starts committing or creating objects."""
|
||||
|
||||
@@ -2,27 +2,27 @@ import pytest
|
||||
from sqlalchemy import Column, Integer, MetaData, Table, create_engine, insert, select
|
||||
from sqlmodel import Session
|
||||
|
||||
from persistance.materializador import Materializador, SoloLectura
|
||||
from persistance.materializer import Materializer, ReadOnly
|
||||
|
||||
metadata = MetaData()
|
||||
numeros = Table("numeros", metadata, Column("n", Integer, primary_key=True))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def materializador():
|
||||
def materializer():
|
||||
engine = create_engine("sqlite://")
|
||||
metadata.create_all(engine)
|
||||
return Materializador(lambda: Session(engine))
|
||||
return Materializer(lambda: Session(engine))
|
||||
|
||||
|
||||
def test_the_function_reads_and_the_body_writes(materializador):
|
||||
def test_the_function_reads_and_the_body_writes(materializer):
|
||||
def escribir(sesion, filas):
|
||||
sesion.execute(insert(numeros), [{"n": n} for n in filas])
|
||||
sesion.commit()
|
||||
return len(filas)
|
||||
|
||||
assert materializador.materializar(lambda sesion: [1, 2, 3], escribir) == 3
|
||||
assert materializador.materializar(lambda sesion: sesion.execute(select(numeros.c.n)).scalars().all()) == [1, 2, 3]
|
||||
assert materializer.materialize(lambda sesion: [1, 2, 3], escribir) == 3
|
||||
assert materializer.materialize(lambda sesion: sesion.execute(select(numeros.c.n)).scalars().all()) == [1, 2, 3]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("escribe", [
|
||||
@@ -30,6 +30,6 @@ def test_the_function_reads_and_the_body_writes(materializador):
|
||||
lambda sesion: sesion.commit(),
|
||||
lambda sesion: sesion.execute(insert(numeros).values(n=1)),
|
||||
])
|
||||
def test_the_function_cannot_write(materializador, escribe):
|
||||
with pytest.raises(SoloLectura):
|
||||
materializador.materializar(escribe)
|
||||
def test_the_function_cannot_write(materializer, escribe):
|
||||
with pytest.raises(ReadOnly):
|
||||
materializer.materialize(escribe)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""What this module covers: the per-patient reads of `CohorteRepository` behind the risk route: `membership` (the
|
||||
"""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).
|
||||
|
||||
Fixtures: `repository`, an in-memory SQLite database with the CaCu tables: builds 1 and 2 of the surveillance cohort
|
||||
@@ -15,7 +15,7 @@ from core.cacu.indicadores.models import (CohorteArmado, CohorteExclusion, Cohor
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
from sqlmodel import Session, create_engine
|
||||
|
||||
from persistance.aristas.oro import CohorteRepository, RiskHorizon
|
||||
from persistance.edges.gold import CohortRepository, RiskHorizon
|
||||
|
||||
URL = "cacu/cohorte_vigilancia"
|
||||
TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote,
|
||||
@@ -43,11 +43,11 @@ def repository():
|
||||
session.add_all([CohorteVariable(armado_id=2, pac_id=10, variable="pap_0", valor_codigo="ASC-US"),
|
||||
CohorteVariable(armado_id=2, pac_id=10, variable="c", valor_numerico=0.0)])
|
||||
session.commit()
|
||||
return CohorteRepository(lambda: Session(engine), TABLES)
|
||||
return CohortRepository(lambda: Session(engine), TABLES)
|
||||
|
||||
|
||||
def _batch(repository, version, risks, armado_id=2):
|
||||
return repository.guardar_lote(armado_id, {**PROVENANCE, "modelo_version": version}, "cin2_12m", risks)[0]
|
||||
return repository.save_batch(armado_id, {**PROVENANCE, "modelo_version": version}, "cin2_12m", risks)[0]
|
||||
|
||||
|
||||
def test_membership_is_in_the_latest_build_with_its_variables(repository):
|
||||
@@ -73,7 +73,7 @@ def test_the_current_batch_is_the_newest_confirmed_one_with_its_horizons(reposit
|
||||
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)])
|
||||
repository.cambiar_estado(first, "final", "revisado")
|
||||
repository.change_state(first, "final", "revisado")
|
||||
_batch(repository, "2", [(10, 1.0, 0.9, None, None)])
|
||||
|
||||
risk = repository.current_risk(10)
|
||||
@@ -86,7 +86,7 @@ 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)])
|
||||
repository.cambiar_estado(first, "final", "revisado")
|
||||
repository.cambiar_estado(first, "entered-in-error", "modelo equivocado")
|
||||
repository.change_state(first, "final", "revisado")
|
||||
repository.change_state(first, "entered-in-error", "modelo equivocado")
|
||||
|
||||
assert repository.current_risk(10) is None
|
||||
|
||||
@@ -12,8 +12,8 @@ from sqlalchemy import Column, Date, DateTime, Float, Integer, MetaData, String,
|
||||
from sqlalchemy.pool import StaticPool
|
||||
from sqlmodel import Session
|
||||
|
||||
from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineContractError, TimelineQueryMissing, TimelineRepository
|
||||
from persistance.materializador import SoloLectura
|
||||
from persistance.edges.silver import TIMELINE_COLUMNS, TimelineContractError, TimelineQueryMissing, TimelineRepository
|
||||
from persistance.materializer import ReadOnly
|
||||
|
||||
metadata = MetaData()
|
||||
events = Table(
|
||||
@@ -99,7 +99,7 @@ def test_a_query_with_other_columns_breaks_the_contract(session_factory):
|
||||
|
||||
|
||||
def test_the_query_runs_on_a_read_only_session(session_factory):
|
||||
"""Pins down: the query runs on a `SesionDeLectura`, so a query that writes is rejected.
|
||||
"""Pins down: the query runs on a `ReadSession`, so a query that writes is rejected.
|
||||
|
||||
Fails if `read` uses a plain session.
|
||||
"""
|
||||
@@ -107,7 +107,7 @@ def test_the_query_runs_on_a_read_only_session(session_factory):
|
||||
"""Returns an INSERT instead of a SELECT."""
|
||||
return insert(events).values(pac_id=9)
|
||||
|
||||
with pytest.raises(SoloLectura):
|
||||
with pytest.raises(ReadOnly):
|
||||
TimelineRepository(session_factory, writing_query).read()
|
||||
|
||||
|
||||
@@ -131,7 +131,7 @@ def test_each_domain_module_reads_its_dbt_view_and_can_be_rebound(session_factor
|
||||
Fails if a domain module drops either repository, reads another domain's view, or loses `with_query`.
|
||||
"""
|
||||
from persistance import cacu, cama, tea
|
||||
from persistance.aristas.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
from persistance.edges.dbt import DbtQueryRepository, DbtTimelineRepository
|
||||
|
||||
for name, domain in (("cacu", cacu), ("cama", cama), ("tea", tea)):
|
||||
assert isinstance(domain.timeline_repository, DbtTimelineRepository)
|
||||
|
||||
@@ -15,10 +15,11 @@ operación, en [`dist/MANUAL.md`](dist/MANUAL.md).
|
||||
| `Core/` | Esquema SQLModel (tablas y vocabularios controlados) de cada padecimiento y de gobernanza. Cada dominio tiene su propio registro de SQLAlchemy. |
|
||||
| `Persistance/` | Conexión, repositorios y migraciones de Alembic (una cadena por base). Cuatro bases independientes: CaCu, CaMa, TEA y gobernanza. |
|
||||
| `Extraction/` | Lectura de documentos clínicos (PDF con texto o escaneado, imágenes) y de EEG (EDF, con MNE): OCR, separación por paciente, extracción de campos y combinación de registros. |
|
||||
| `WebApi/` (submódulo) | API REST en Flask: importación, consulta de datos, indicadores, bitácora y gobernanza. `GET /api` lista las rutas. `webapi/orquestacion/` es el ciclo de indicadores de cada dominio (staging → plata → reportes), con Hamilton. |
|
||||
| `WebApi/` (submódulo) | API REST en Flask: importación, consulta de datos, indicadores, bitácora y gobernanza. `GET /api` lista las rutas. `webapi/orchestration/` es el ciclo de indicadores de cada dominio (staging → plata → reportes), con Hamilton. |
|
||||
| `WebApp/` (submódulo) | Interfaz en Angular y Angular Material. |
|
||||
| `models/` (submódulo) | Registro de modelos en MLflow, predicciones y trabajos de OCR de reportes. |
|
||||
| `indicadores_kit/` (submódulo) | Definiciones y cálculo de los indicadores, del equipo clínico. |
|
||||
| `Transformation/` | dbt: los modelos sobre la plata genérica y las definiciones de los indicadores (capa semántica). |
|
||||
| `indicadores_kit/` (submódulo) | Ya sin código: sus indicadores están en `Transformation/`, su carga, referencias y lista de seguimiento en `WebApi/`, y sus cohortes en `models/`. |
|
||||
| `dist/` | Paquete de instalación: `docker-compose.yml`, scripts y manual. |
|
||||
|
||||
Cambiar de motor de base de datos (SQLite, MySQL/MariaDB, PostgreSQL o SQL
|
||||
@@ -48,7 +49,7 @@ uv run python main.py # http://localhost:5050
|
||||
cd WebApp && npm install && npm start # http://localhost:4200
|
||||
|
||||
# Indicadores de un dominio, después de importar datos
|
||||
cd WebApi && uv run python -m webapi.orquestacion ciclo cacu --desde 2021 --hasta 2026 --permitir-sin-definir
|
||||
cd WebApi && uv run python -m webapi.orchestration cycle cacu --from 2021 --to 2026 --allow-undecided
|
||||
```
|
||||
|
||||
Con Docker, `docker compose up --build` levanta la API (puerto 5050), el
|
||||
|
||||
@@ -6,3 +6,4 @@ uv.lock
|
||||
.user.yml
|
||||
package-lock.yml
|
||||
.venv/
|
||||
graphify-out/
|
||||
|
||||
@@ -28,6 +28,91 @@ vars:
|
||||
cie_antecedente: ["D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539"]
|
||||
horizonte_toma_reporte_dias: 60
|
||||
horizonte_toma_diagnostico_dias: 180
|
||||
# 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:
|
||||
colposcopia_evidencias: ["motivo", "cie", "diagnostico_texto", "orden_biopsia", "biopsia"]
|
||||
colposcopia_requisito: "valoracion_previa"
|
||||
biopsia_requisito: "mismo_dia_que_colposcopia"
|
||||
colposcopia_motivos: ["ACUDE A COLPOSCOPIA", "COLPOSCOPIA"]
|
||||
colposcopia_especialidades: ["CLINICA_MUJER_COLPOSCOPIA"]
|
||||
colposcopia_cie: ["R876", "N87", "N870", "N871", "N872", "N879", "B977"]
|
||||
colposcopia_diagnosticos: ["VIRUS DEL PAPILOMA HUMANO"]
|
||||
tratamiento_cie: ["D06", "D060", "D061", "D067", "D069"]
|
||||
vigilancia_especialidades: ["MEDICINA_FAMILIAR", "CLINICA_MUJER_COLPOSCOPIA"]
|
||||
# The risk estimates a band summary reads (the kit's cacu.riesgos.horizonte_banda; provisional): years from the
|
||||
# index date, 0 is prevalent.
|
||||
riesgos_horizonte_banda: 0
|
||||
# CaMa's rules (the kit's cama.*; provisional). The diagnosis rules: a note with one of `cie_diagnostico` written by
|
||||
# one of `especialidades_diagnostico` resolves a mammogram within `horizonte_toma_diagnostico_dias`; one with one
|
||||
# of `cie_antecedente` before it leaves it out. `birads_gravedad`: BI-RADS from least to most severe.
|
||||
cama:
|
||||
cie_diagnostico: ["Z123", "N60", "N600", "N601", "N602", "N603", "N604", "N608", "N609", "N61", "N62", "N63",
|
||||
"N64", "N640", "N641", "N642", "N643", "N644", "N645", "N648", "N649", "D24", "R92", "D05",
|
||||
"D050", "D051", "D057", "D059", "C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506",
|
||||
"C508", "C509"]
|
||||
cie_antecedente: ["D05", "D050", "D051", "D057", "D059", "C50", "C500", "C501", "C502", "C503", "C504", "C505",
|
||||
"C506", "C508", "C509"]
|
||||
especialidades_diagnostico: ["CIRUGIA_ONCOLOGICA"]
|
||||
horizonte_toma_diagnostico_dias: 180
|
||||
birads_gravedad: ["B1", "B2", "B3", "B0", "B4", "B4A", "B4B", "B4C", "B5", "B6"]
|
||||
# The analysis' stratifiers (models/cama/silver/cama_estratificadores.sql), from the catalog's provisional results
|
||||
# read from reports; placeholders until the domain expert validates them. `estadios`: each clinical stage's
|
||||
# group; `etapa_temprana`: the groups counted as early, the rest of the known ones advanced. The surrogate
|
||||
# molecular subtype: HER2 3+ is HER2-positive; HER2 0 or 1+ with both receptors negative, triple negative; with a
|
||||
# positive receptor, luminal A when Ki-67 is under `ki67_corte` % and progesterone positive with at least
|
||||
# `rp_corte` % (or no percentage), luminal B when Ki-67 is at least `ki67_corte` % or progesterone falls short;
|
||||
# without Ki-67, none. `tamano_t`: T by the lesion's largest diameter in mm, each up to its bound.
|
||||
# The biopsy grades that are an invasive cancer (models/cama/gold/eventos/cama_cancer_invasor.sql).
|
||||
grados_invasor: ["CARCINOMA_INVASOR"]
|
||||
estratos:
|
||||
estadios: {E0: "0", EI: "i", EIIA: "ii", EIIB: "ii", EIIIA: "iii", EIIIB: "iii", EIIIC: "iii", EIV: "iv"}
|
||||
etapa_temprana: ["0", "i", "ii"]
|
||||
her2_positivo: ["H3"]
|
||||
her2_negativo: ["H0", "H1"]
|
||||
ki67_corte: 20
|
||||
rp_corte: 20
|
||||
tamano_t: [{t: "t1", hasta_mm: 20}, {t: "t2", hasta_mm: 50}, {t: "t3", hasta_mm: null}]
|
||||
# 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.
|
||||
tea:
|
||||
edad_min_meses: 16
|
||||
edad_max_meses: 36
|
||||
dias_por_mes: 30.4375
|
||||
ventanas:
|
||||
- {clave: "16_23", desde: 16, hasta: 23}
|
||||
- {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 surveillance cohort's rules (models/cacu/cohorts/surveillance).
|
||||
surveillance_cohort:
|
||||
recruitment_start: "2024-01-01"
|
||||
|
||||
@@ -34,16 +34,18 @@ from (
|
||||
{%- set valor_codigo = as_text('null') -%}
|
||||
{%- set valor_numerico = 'cast(o.valor_numerico as ' ~ dbt.type_float() ~ ')' -%}
|
||||
{%- elif resultado -%}
|
||||
{%- set valor_codigo = as_text(
|
||||
{#- Every branch as text: SQL Server gives a CASE the type of highest precedence among its branches, so a
|
||||
number and a date in one CASE fail there. -#}
|
||||
{%- set valor_codigo =
|
||||
"case r.tipo_valor"
|
||||
~ " when 'codigo' then coalesce(o.valor_id, o.valor_fuente)"
|
||||
~ " when 'booleano' then " ~ as_integer('o.valor_numerico')
|
||||
~ " when 'numero' then o.valor_numerico"
|
||||
~ " when 'fecha' then o.valor_fecha"
|
||||
~ " else o.valor_texto end") -%}
|
||||
~ " when 'codigo' then " ~ as_text('coalesce(o.valor_id, o.valor_fuente)')
|
||||
~ " when 'booleano' then " ~ as_text(as_integer('o.valor_numerico'))
|
||||
~ " when 'numero' then " ~ as_text('o.valor_numerico')
|
||||
~ " when 'fecha' then " ~ as_text('o.valor_fecha')
|
||||
~ " else " ~ as_text('o.valor_texto') ~ " end" -%}
|
||||
{%- set valor_numerico = 'cast(null as ' ~ dbt.type_float() ~ ')' -%}
|
||||
{%- elif f.get('columna') -%}
|
||||
{%- set valor_codigo = "nullif(trim(p." ~ f['columna'] ~ "), '')" -%}
|
||||
{%- set valor_codigo = "nullif(ltrim(rtrim(p." ~ f['columna'] ~ ")), '')" -%}
|
||||
{%- set valor_numerico = 'cast(null as ' ~ dbt.type_float() ~ ')' -%}
|
||||
{%- else -%}
|
||||
{%- set valor_codigo = as_text('null') -%}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
{#
|
||||
Completed months from a number of days, as TEA counts them: days / `tea.dias_por_mes`, rounded to one decimal,
|
||||
then truncated (a child of 26.96 months is 27.0 and so 27, one of 26.94 is 26). Days are differences of
|
||||
`dim_fecha.dia_num`, never negative here.
|
||||
|
||||
Truncation is `floor`, except on SQLite, where a cast to integer truncates (PostgreSQL and MySQL round on that
|
||||
cast). PostgreSQL only rounds a numeric to a number of decimals, hence the cast to decimal first.
|
||||
#}
|
||||
{% macro tea_meses_cumplidos(dias) -%}
|
||||
{{ return(adapter.dispatch('tea_meses_cumplidos', 'isssteleon')(dias)) }}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro default__tea_meses_cumplidos(dias) -%}
|
||||
{{ as_integer('floor(round(cast(' ~ dias ~ ' as decimal(12, 4)) / ' ~ var('tea')['dias_por_mes'] ~ ', 1))') }}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro sqlite__tea_meses_cumplidos(dias) -%}
|
||||
cast(round(({{ dias }}) / {{ var('tea')['dias_por_mes'] }}, 1) as integer)
|
||||
{%- endmacro %}
|
||||
|
||||
{#
|
||||
The age group of a number of completed months: the `tea.ventanas` window it falls in, `sin_dato` when the months
|
||||
are null (no birth date), and null when it falls outside every window.
|
||||
#}
|
||||
{% macro tea_grupo_edad(meses) -%}
|
||||
case
|
||||
when {{ meses }} is null then {{ as_text("'sin_dato'") }}
|
||||
{%- for v in var('tea')['ventanas'] %}
|
||||
when {{ meses }} between {{ v['desde'] }} and {{ v['hasta'] }} then {{ as_text("'" ~ v['clave'] ~ "'") }}
|
||||
{%- endfor %}
|
||||
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] }})
|
||||
{%- endmacro %}
|
||||
|
||||
{# The later of two values when both are known, else null: a step reached after the previous one is dated by the
|
||||
later of its fact and that step. SQL Server 2016 has no GREATEST. #}
|
||||
{% macro tea_despues(previo, propio) -%}
|
||||
case when ({{ previo }}) is null or ({{ propio }}) is null then null
|
||||
when ({{ propio }}) > ({{ previo }}) then ({{ propio }}) else ({{ previo }}) end
|
||||
{%- endmacro %}
|
||||
@@ -0,0 +1,12 @@
|
||||
{# A list of strings as an SQL list: ('a', 'b'). For rules from dbt vars, which are compiled in. #}
|
||||
{% macro sql_list(valores) -%}
|
||||
({% for v in valores %}'{{ v | replace("'", "''") }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
{%- endmacro %}
|
||||
|
||||
{# A text column without accents and in upper case, to compare by containment with rules written that way. The
|
||||
accents go first: SQLite's `upper` only knows ASCII. #}
|
||||
{% macro sin_acentos_mayusculas(columna) -%}
|
||||
{%- set pares = [('Á','A'),('É','E'),('Í','I'),('Ó','O'),('Ú','U'),('Ü','U'),
|
||||
('á','a'),('é','e'),('í','i'),('ó','o'),('ú','u'),('ü','u')] -%}
|
||||
upper({% for _ in pares %}replace({% endfor %}{{ columna }}{% for con, sin in pares %}, '{{ con }}', '{{ sin }}'){% endfor %})
|
||||
{%- endmacro %}
|
||||
@@ -4,7 +4,7 @@ version: 2
|
||||
# (`--profile cacu|cama|tea`). Written by the Python load; dbt only reads them.
|
||||
sources:
|
||||
- name: silver
|
||||
schema: main
|
||||
schema: "{{ target.schema }}"
|
||||
tables:
|
||||
- name: procedimiento
|
||||
- name: observacion_clinica
|
||||
@@ -14,3 +14,13 @@ sources:
|
||||
- name: cat_resultado
|
||||
- name: cat_valor
|
||||
- name: dim_fecha
|
||||
|
||||
# Restricted gold the Python cycle writes: the cohort builds and the risk estimates scored on them. dbt only reads
|
||||
# them, like silver.
|
||||
- name: oro
|
||||
schema: "{{ target.schema }}"
|
||||
tables:
|
||||
- name: cohorte_armado
|
||||
- name: cohorte_miembro
|
||||
- name: evaluacion_riesgo_lote
|
||||
- name: evaluacion_riesgo
|
||||
|
||||
-96
@@ -1,96 +0,0 @@
|
||||
-- CACU_CONFIRMACION_CITOLOGIA: confirmación por biopsia según resultado citológico. Unidad: paciente.
|
||||
-- población: pacientes cuya última citología válida del periodo es de alto grado (citologia_alto_grado)
|
||||
-- categoría: grado más grave de biopsia originada por esa citología (ligada por toma_id);
|
||||
-- SIN_BIOPSIA si no tiene ninguna; SIN_DATO si tiene pero sin grado
|
||||
-- gravedad: orden de catalogo_biopsia, de menos a más grave
|
||||
|
||||
with citologias as (
|
||||
select * from {{ ref('cacu_citologias') }}
|
||||
),
|
||||
|
||||
biopsias as (
|
||||
select * from {{ ref('cacu_biopsias') }}
|
||||
),
|
||||
|
||||
en_periodo as (
|
||||
select *
|
||||
from citologias
|
||||
where fecha_toma >= '{{ var("periodo_inicio") }}'
|
||||
and fecha_toma < '{{ var("periodo_fin") }}'
|
||||
),
|
||||
|
||||
-- Último resultado válido por paciente, con su toma_id para ligar biopsias
|
||||
por_recientes as (
|
||||
select
|
||||
pac_id,
|
||||
procedimiento_id as toma_id,
|
||||
case when (
|
||||
resultado is not null
|
||||
and fecha_reporte <= '{{ var("fecha_corte") }}'
|
||||
and (calidad_muestra is null or calidad_muestra != '{{ var("calidad_insatisfactoria") }}')
|
||||
) then resultado end as resultado,
|
||||
row_number() over (
|
||||
partition by pac_id
|
||||
order by
|
||||
case when (
|
||||
resultado is not null
|
||||
and fecha_reporte <= '{{ var("fecha_corte") }}'
|
||||
and (calidad_muestra is null or calidad_muestra != '{{ var("calidad_insatisfactoria") }}')
|
||||
) then 1 else 0 end desc,
|
||||
fecha_toma desc,
|
||||
fuente_id desc
|
||||
) as lugar
|
||||
from en_periodo
|
||||
),
|
||||
|
||||
ultimo_resultado as (
|
||||
select pac_id, toma_id, resultado
|
||||
from por_recientes
|
||||
where lugar = 1
|
||||
),
|
||||
|
||||
de_alto_grado as (
|
||||
select pac_id, toma_id
|
||||
from ultimo_resultado
|
||||
where resultado in ({% for g in var("citologia_alto_grado") %}'{{ g }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
),
|
||||
|
||||
-- Biopsia más grave ligada a la toma de esa citología
|
||||
por_gravedad as (
|
||||
select
|
||||
d.pac_id,
|
||||
b.grado,
|
||||
row_number() over (
|
||||
partition by d.pac_id
|
||||
order by
|
||||
case b.grado
|
||||
{% for g in var("catalogo_biopsia") %}
|
||||
when '{{ g }}' then {{ loop.index }}
|
||||
{% endfor %}
|
||||
else 0
|
||||
end desc,
|
||||
b.fecha_reporte desc,
|
||||
b.fuente_id desc
|
||||
) as lugar
|
||||
from de_alto_grado d
|
||||
join biopsias b
|
||||
on b.toma_id = d.toma_id
|
||||
and b.pac_id = d.pac_id
|
||||
where b.fecha_reporte <= '{{ var("fecha_corte") }}'
|
||||
),
|
||||
|
||||
biopsia_mas_grave as (
|
||||
select pac_id, grado
|
||||
from por_gravedad
|
||||
where lugar = 1
|
||||
)
|
||||
|
||||
select
|
||||
d.pac_id as unidad_id,
|
||||
'TOTAL' as grupo,
|
||||
case
|
||||
when b.pac_id is null then 'SIN_BIOPSIA'
|
||||
else coalesce(b.grado, 'SIN_DATO')
|
||||
end as categoria
|
||||
from de_alto_grado d
|
||||
left join biopsia_mas_grave b on b.pac_id = d.pac_id
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_confirmacion_citologia
|
||||
description: "Confirmación por biopsia del resultado citológico de alto grado (C2). Población: pacientes cuya última citología válida del periodo es de alto grado."
|
||||
meta:
|
||||
measure_url: "cacu/CACU_CONFIRMACION_CITOLOGIA"
|
||||
contrato: C2
|
||||
unidad: paciente
|
||||
parametros:
|
||||
periodo_inicio: periodo_inicio
|
||||
periodo_fin: periodo_fin
|
||||
fecha_corte: fecha_corte
|
||||
calidad_insatisfactoria: cacu.calidad_insatisfactoria
|
||||
citologia_alto_grado: cacu.citologia_alto_grado
|
||||
catalogo_biopsia: cacu.catalogo_biopsia
|
||||
poblaciones:
|
||||
initial-population: "Pacientes cuya última citología válida del periodo es de alto grado"
|
||||
columns:
|
||||
- name: unidad_id
|
||||
description: "pac_id del paciente"
|
||||
- name: grupo
|
||||
description: "TOTAL"
|
||||
- name: categoria
|
||||
description: "Grado más grave de biopsia ligada a esa citología; SIN_BIOPSIA o SIN_DATO"
|
||||
@@ -1,106 +0,0 @@
|
||||
-- CACU_DIAS_TOMA_DIAGNOSTICO: días naturales de la toma de citología al diagnóstico. Unidad: examen. C3r.
|
||||
-- initial-population: citologías del periodo medibles (sin antecedente previo y con horizonte vencido o diagnóstico)
|
||||
-- measure-observation: de ellas, con diagnóstico, con los días
|
||||
--
|
||||
-- El diagnóstico es la primera nota con CIE en cie_diagnostico y especialidad en
|
||||
-- especialidades_diagnostico, posterior a la toma y dentro del horizonte.
|
||||
-- Se excluyen tomas de pacientes con nota con CIE en cie_antecedente anterior a la toma.
|
||||
-- Workaround SQLite 3.40: primer_antecedente y join a diagnosticos se calculan una vez
|
||||
-- mediante uniones, no subconsultas correlacionadas (ver consultas/tiempos.py).
|
||||
|
||||
with citologias as (
|
||||
select * from {{ ref('cacu_citologias') }}
|
||||
),
|
||||
|
||||
notas as (
|
||||
select * from {{ ref('cacu_notas') }}
|
||||
),
|
||||
|
||||
-- Notas que cuentan como diagnóstico: CIE en la lista Y especialidad conocida
|
||||
diagnosticos as (
|
||||
select n.pac_id, n.fecha
|
||||
from notas n
|
||||
where n.cie_codigo in ({% for c in var("cie_diagnostico") %}'{{ c }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
and n.especialidad in ({% for e in var("especialidades_diagnostico") %}'{{ e }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
and n.fecha <= '{{ var("fecha_corte") }}'
|
||||
),
|
||||
|
||||
-- Notas que cuentan como antecedente (incidencia previa)
|
||||
antecedentes as (
|
||||
select n.pac_id, n.fecha
|
||||
from notas n
|
||||
where n.cie_codigo in ({% for c in var("cie_antecedente") %}'{{ c }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
and n.fecha <= '{{ var("fecha_corte") }}'
|
||||
),
|
||||
|
||||
tomas_del_periodo as (
|
||||
select fuente_id, pac_id, fecha_toma as toma
|
||||
from citologias
|
||||
where fecha_toma >= '{{ var("periodo_inicio") }}'
|
||||
and fecha_toma < '{{ var("periodo_fin") }}'
|
||||
),
|
||||
|
||||
-- Primer antecedente por paciente (calculado una vez, no correlacionado)
|
||||
primer_antecedente as (
|
||||
select pac_id, min(fecha) as fecha
|
||||
from antecedentes
|
||||
group by pac_id
|
||||
),
|
||||
|
||||
-- Primer diagnóstico posterior a la toma y dentro del horizonte, por toma
|
||||
tomas_con_fechas as (
|
||||
select
|
||||
t.fuente_id,
|
||||
t.pac_id,
|
||||
t.toma,
|
||||
pa.fecha as antecedente,
|
||||
min(d.fecha) as diagnostico
|
||||
from tomas_del_periodo t
|
||||
left join primer_antecedente pa
|
||||
on pa.pac_id = t.pac_id
|
||||
left join diagnosticos d
|
||||
on d.pac_id = t.pac_id
|
||||
and d.fecha > t.toma
|
||||
and {{ dbt.datediff("t.toma", "d.fecha", "day") }}
|
||||
< {{ var("horizonte_toma_diagnostico_dias") }}
|
||||
group by t.fuente_id, t.pac_id, t.toma, pa.fecha
|
||||
),
|
||||
|
||||
-- Excluir tomas de pacientes con antecedente anterior a la toma
|
||||
tomas as (
|
||||
select fuente_id, pac_id, toma, diagnostico
|
||||
from tomas_con_fechas
|
||||
where antecedente is null or antecedente >= toma
|
||||
),
|
||||
|
||||
con_estado as (
|
||||
select
|
||||
fuente_id,
|
||||
pac_id,
|
||||
toma,
|
||||
diagnostico,
|
||||
diagnostico is null
|
||||
and {{ dbt.datediff("toma", date_literal(var("fecha_corte")), "day") }}
|
||||
< {{ var("horizonte_toma_diagnostico_dias") }} as pendiente
|
||||
from tomas
|
||||
),
|
||||
|
||||
poblacion_inicial as (
|
||||
select fuente_id as unidad_id, pac_id, 'TOTAL' as grupo
|
||||
from con_estado
|
||||
where not pendiente
|
||||
),
|
||||
|
||||
observacion as (
|
||||
select
|
||||
fuente_id as unidad_id,
|
||||
pac_id,
|
||||
'TOTAL' as grupo,
|
||||
{{ dbt.datediff("toma", "diagnostico", "day") }} as valor
|
||||
from con_estado
|
||||
where diagnostico is not null
|
||||
)
|
||||
|
||||
select 'initial-population' as poblacion, unidad_id, pac_id, grupo, null as valor from poblacion_inicial
|
||||
union all
|
||||
select 'measure-observation' as poblacion, unidad_id, pac_id, grupo, valor from observacion
|
||||
@@ -1,29 +0,0 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_dias_toma_diagnostico
|
||||
description: "Días naturales de la toma de citología al diagnóstico en nota médica (C3r). Unidad: examen. Excluye tomas de pacientes con diagnóstico previo."
|
||||
meta:
|
||||
measure_url: "cacu/CACU_DIAS_TOMA_DIAGNOSTICO"
|
||||
contrato: C3r
|
||||
unidad: examen
|
||||
parametros:
|
||||
periodo_inicio: periodo_inicio
|
||||
periodo_fin: periodo_fin
|
||||
fecha_corte: fecha_corte
|
||||
horizonte_toma_diagnostico_dias: cacu.horizontes.toma_diagnostico_dias
|
||||
especialidades_diagnostico: cacu.diagnostico.especialidades
|
||||
poblaciones:
|
||||
initial-population: "Citologías medibles: sin antecedente previo y con horizonte vencido o diagnóstico al corte"
|
||||
measure-observation: "De ellas, con primera nota de diagnóstico, con los días"
|
||||
columns:
|
||||
- name: poblacion
|
||||
description: "initial-population | measure-observation"
|
||||
- name: unidad_id
|
||||
description: "fuente_id de la citología"
|
||||
- name: pac_id
|
||||
description: "pac_id del paciente (para estratificación)"
|
||||
- name: grupo
|
||||
description: "TOTAL"
|
||||
- name: valor
|
||||
description: "Días naturales de toma a primera nota de diagnóstico (NULL en initial-population)"
|
||||
@@ -1,44 +0,0 @@
|
||||
-- CACU_EU13: pacientes tamizadas con lesión confirmada por biopsia.
|
||||
-- denominador: pacientes con citología tomada en el periodo
|
||||
-- numerador: de ellas, las que tienen biopsia reportada con grado en deteccion_grados,
|
||||
-- originada por una de sus citologías del periodo (ligada por toma_id)
|
||||
|
||||
with citologias as (
|
||||
select * from {{ ref('cacu_citologias') }}
|
||||
),
|
||||
|
||||
biopsias as (
|
||||
select * from {{ ref('cacu_biopsias') }}
|
||||
),
|
||||
|
||||
tomas_del_periodo as (
|
||||
select distinct
|
||||
procedimiento_id,
|
||||
pac_id
|
||||
from citologias
|
||||
where fecha_toma >= '{{ var("periodo_inicio") }}'
|
||||
and fecha_toma < '{{ var("periodo_fin") }}'
|
||||
),
|
||||
|
||||
poblacion_inicial as (
|
||||
select distinct pac_id as unidad_id
|
||||
from tomas_del_periodo
|
||||
),
|
||||
|
||||
denominador as (
|
||||
select unidad_id from poblacion_inicial
|
||||
),
|
||||
|
||||
numerador as (
|
||||
select distinct t.pac_id as unidad_id
|
||||
from tomas_del_periodo t
|
||||
join biopsias b
|
||||
on b.toma_id = t.procedimiento_id
|
||||
and b.pac_id = t.pac_id
|
||||
where b.fecha_reporte <= '{{ var("fecha_corte") }}'
|
||||
and b.grado in ({% for g in var("deteccion_grados") %}'{{ g }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
)
|
||||
|
||||
select 'denominador' as poblacion, unidad_id from denominador
|
||||
union all
|
||||
select 'numerador' as poblacion, unidad_id from numerador
|
||||
@@ -1,22 +0,0 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_eu13
|
||||
description: "Pacientes tamizadas con lesión confirmada por biopsia (C1). Denominador: con citología en el periodo. Numerador: con biopsia ligada a esa citología con grado en deteccion_grados."
|
||||
meta:
|
||||
measure_url: "cacu/CACU_EU13"
|
||||
contrato: C1
|
||||
unidad: paciente
|
||||
parametros:
|
||||
periodo_inicio: periodo_inicio
|
||||
periodo_fin: periodo_fin
|
||||
fecha_corte: fecha_corte
|
||||
deteccion_grados: cacu.deteccion_grados
|
||||
poblaciones:
|
||||
denominador: "Pacientes con citología tomada en el periodo"
|
||||
numerador: "De ellas, con biopsia reportada con grado en deteccion_grados"
|
||||
columns:
|
||||
- name: poblacion
|
||||
description: "denominador | numerador"
|
||||
- name: unidad_id
|
||||
description: "pac_id del paciente"
|
||||
@@ -1,49 +0,0 @@
|
||||
-- CACU_EU7: distribución de resultados citológicos por semestre. Unidad: paciente.
|
||||
-- población: pacientes con ≥1 citología tomada en el periodo
|
||||
-- resultado: último resultado válido del periodo a la fecha de corte; SIN_DATO si ninguna
|
||||
-- válida: tiene resultado, reportada al corte, calidad ≠ calidad_insatisfactoria
|
||||
|
||||
with citologias as (
|
||||
select * from {{ ref('cacu_citologias') }}
|
||||
),
|
||||
|
||||
en_periodo as (
|
||||
select *
|
||||
from citologias
|
||||
where fecha_toma >= '{{ var("periodo_inicio") }}'
|
||||
and fecha_toma < '{{ var("periodo_fin") }}'
|
||||
),
|
||||
|
||||
por_recientes as (
|
||||
select
|
||||
pac_id,
|
||||
case when (
|
||||
resultado is not null
|
||||
and fecha_reporte <= '{{ var("fecha_corte") }}'
|
||||
and (calidad_muestra is null or calidad_muestra != '{{ var("calidad_insatisfactoria") }}')
|
||||
) then resultado end as resultado,
|
||||
row_number() over (
|
||||
partition by pac_id
|
||||
order by
|
||||
case when (
|
||||
resultado is not null
|
||||
and fecha_reporte <= '{{ var("fecha_corte") }}'
|
||||
and (calidad_muestra is null or calidad_muestra != '{{ var("calidad_insatisfactoria") }}')
|
||||
) then 1 else 0 end desc,
|
||||
fecha_toma desc,
|
||||
fuente_id desc
|
||||
) as lugar
|
||||
from en_periodo
|
||||
),
|
||||
|
||||
ultimo_resultado as (
|
||||
select pac_id, resultado
|
||||
from por_recientes
|
||||
where lugar = 1
|
||||
)
|
||||
|
||||
select
|
||||
pac_id as unidad_id,
|
||||
coalesce(resultado, 'SIN_DATO') as categoria,
|
||||
'TOTAL' as grupo
|
||||
from ultimo_resultado
|
||||
@@ -1,23 +0,0 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_eu7
|
||||
description: "Distribución de resultados citológicos por semestre (C2). Último resultado válido por paciente al corte; SIN_DATO si ninguno válido."
|
||||
meta:
|
||||
measure_url: "cacu/CACU_EU7"
|
||||
contrato: C2
|
||||
unidad: paciente
|
||||
parametros:
|
||||
periodo_inicio: periodo_inicio
|
||||
periodo_fin: periodo_fin
|
||||
fecha_corte: fecha_corte
|
||||
calidad_insatisfactoria: cacu.calidad_insatisfactoria
|
||||
poblaciones:
|
||||
initial-population: "Pacientes con ≥1 citología tomada en el periodo"
|
||||
columns:
|
||||
- name: unidad_id
|
||||
description: "pac_id del paciente"
|
||||
- name: categoria
|
||||
description: "Resultado citológico (bethesda) o SIN_DATO"
|
||||
- name: grupo
|
||||
description: "TOTAL (sin desgloses por ahora)"
|
||||
@@ -0,0 +1,41 @@
|
||||
-- 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
|
||||
-- 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.
|
||||
|
||||
with recientes as (
|
||||
select
|
||||
e.lote_id,
|
||||
e.pac_id,
|
||||
e.probabilidad,
|
||||
e.estado,
|
||||
e.registrado_en,
|
||||
row_number() over (partition by e.lote_id, e.pac_id order by e.version desc) as lugar
|
||||
from {{ source('oro', 'evaluacion_riesgo') }} e
|
||||
where e.horizonte_anios = {{ var('riesgos_horizonte_banda') }}
|
||||
),
|
||||
|
||||
vigentes as (
|
||||
select lote_id, pac_id, probabilidad, registrado_en from recientes where lugar = 1 and estado = 'final'
|
||||
),
|
||||
|
||||
lote_vigente as (
|
||||
select max(l.lote_id) as lote_id
|
||||
from {{ source('oro', 'evaluacion_riesgo_lote') }} l
|
||||
join {{ source('oro', 'cohorte_armado') }} a on a.armado_id = l.armado_id
|
||||
where a.url = 'cacu/cohorte_vigilancia'
|
||||
and l.lote_id in (select lote_id from vigentes)
|
||||
)
|
||||
|
||||
select
|
||||
m.pac_id,
|
||||
m.fecha_indice,
|
||||
a.armado_en as miembro_conocido_en,
|
||||
v.probabilidad,
|
||||
v.registrado_en as evaluacion_conocida_en
|
||||
from lote_vigente lv
|
||||
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
|
||||
@@ -0,0 +1,76 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_riesgo_vigilancia
|
||||
description: "Las miembros de la cohorte de vigilancia que puntuó el lote de riesgos vigente, con su probabilidad."
|
||||
config:
|
||||
materialized: view
|
||||
|
||||
semantic_models:
|
||||
- name: cacu_riesgo_vigilancia
|
||||
description: "Surveillance cohort members scored by the current batch of risk estimates: the band summary's grain."
|
||||
model: ref('cacu_riesgo_vigilancia')
|
||||
defaults:
|
||||
agg_time_dimension: fecha_indice
|
||||
entities:
|
||||
- name: miembro
|
||||
type: primary
|
||||
expr: pac_id
|
||||
dimensions:
|
||||
- name: fecha_indice
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: miembro_conocido_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: evaluacion_conocida_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: probabilidad
|
||||
type: categorical
|
||||
measures:
|
||||
- name: miembros
|
||||
description: "Distinct members: each patient once."
|
||||
agg: count_distinct
|
||||
expr: pac_id
|
||||
|
||||
metrics:
|
||||
- name: cacu_riesgo_banda
|
||||
label: "Pacientes en vigilancia por banda de riesgo de CIN2+"
|
||||
description: >-
|
||||
Cuántas pacientes de la cohorte de vigilancia, con citología índice en el periodo, caen en cada banda de riesgo
|
||||
estimado de CIN2+. Cuenta el lote de evaluaciones vigente (confirmado). «Sin dato»: la paciente no tiene
|
||||
evaluación confirmada en ese lote.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: miembros
|
||||
config:
|
||||
meta:
|
||||
measure_url: cacu/CACU_RIESGO_BANDA
|
||||
version: 0.1.0
|
||||
scoring: composition
|
||||
basis: paciente
|
||||
grupo: TOTAL
|
||||
contrato: C2
|
||||
tipos_periodo: [semestre]
|
||||
poblaciones_fhir: [measure-observation]
|
||||
conocida_en: [miembro_conocido_en]
|
||||
parametros:
|
||||
corte_intermedio: comun.riesgos.corte_intermedio
|
||||
corte_alto: comun.riesgos.corte_alto
|
||||
# One row per member, so nothing to choose between; the category is her probability's band, by rules of the
|
||||
# question: below `corte_intermedio` BAJO, below `corte_alto` INTERMEDIO, else ALTO.
|
||||
categoria:
|
||||
valor: probabilidad
|
||||
sin_dato: SIN_DATO
|
||||
elige: ultimo_valido
|
||||
valido: "{% raw %}{{ Dimension('miembro__probabilidad') }} is not null{% endraw %}"
|
||||
conocida_en: [evaluacion_conocida_en]
|
||||
orden: [fecha_indice]
|
||||
bandas:
|
||||
- {valor: BAJO, menor_que: corte_intermedio}
|
||||
- {valor: INTERMEDIO, menor_que: corte_alto}
|
||||
- {valor: ALTO}
|
||||
@@ -0,0 +1,41 @@
|
||||
-- One row per cytology taken and each biopsy report it led to (one row with nulls when it led to none): the event
|
||||
-- grain of the measures that follow a sample to its biopsy. When the sample and the report became known are the
|
||||
-- start of the loads that wrote them. The birth date is the patient's, for strata by age. The sample's own result
|
||||
-- (with its quality and when it was known) lets a measure pick a patient's last valid sample, and `biopsia_gravedad`
|
||||
-- orders her biopsies from least to most severe by `catalogo_biopsia`: 0 for a grade the catalog doesn't know, -1 for
|
||||
-- a report without one.
|
||||
|
||||
select
|
||||
c.procedimiento_id,
|
||||
c.fuente_id,
|
||||
c.pac_id,
|
||||
c.fecha_toma,
|
||||
toma.inicio as toma_conocida_en,
|
||||
c.resultado,
|
||||
c.calidad_muestra,
|
||||
c.fecha_reporte as citologia_fecha_reporte,
|
||||
resultado.inicio as resultado_conocido_en,
|
||||
b.fuente_id as biopsia_fuente_id,
|
||||
b.fecha_reporte as biopsia_fecha_reporte,
|
||||
b.grado as biopsia_grado,
|
||||
case
|
||||
when b.procedimiento_id is null then null
|
||||
when b.grado is null then -1
|
||||
{%- for grado in var('catalogo_biopsia') %}
|
||||
when b.grado = '{{ grado }}' then {{ loop.index }}
|
||||
{%- endfor %}
|
||||
else 0
|
||||
end as biopsia_gravedad,
|
||||
reporte.inicio as biopsia_conocida_en,
|
||||
persona.fecha_nacimiento
|
||||
from {{ ref('cacu_citologias') }} c
|
||||
join {{ source('silver', 'carga') }} toma
|
||||
on toma.carga_id = c.toma_carga_id
|
||||
join {{ source('silver', 'persona') }} persona
|
||||
on persona.pac_id = c.pac_id
|
||||
left join {{ source('silver', 'carga') }} resultado
|
||||
on resultado.carga_id = c.resultado_carga_id and c.resultado is not null
|
||||
left join {{ ref('cacu_biopsias') }} b
|
||||
on b.toma_id = c.procedimiento_id and b.pac_id = c.pac_id
|
||||
left join {{ source('silver', 'carga') }} reporte
|
||||
on reporte.carga_id = b.reporte_carga_id
|
||||
@@ -0,0 +1,180 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_tomas_biopsia
|
||||
description: "Citologías tomadas y los reportes de biopsia que originaron, con cuándo se supo de cada uno."
|
||||
config:
|
||||
materialized: view
|
||||
|
||||
semantic_models:
|
||||
- name: cacu_tomas_biopsia
|
||||
description: "Cytologies taken and the biopsy reports they led to: what CaCu's detection measures count over."
|
||||
model: ref('cacu_tomas_biopsia')
|
||||
defaults:
|
||||
agg_time_dimension: fecha_toma
|
||||
entities:
|
||||
- name: toma_biopsia
|
||||
type: primary
|
||||
expr: "procedimiento_id || '-' || coalesce(biopsia_fecha_reporte, '')"
|
||||
- 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: biopsia_fecha_reporte
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: biopsia_conocida_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: fecha_nacimiento
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: biopsia_grado
|
||||
type: categorical
|
||||
- name: fuente_id
|
||||
type: categorical
|
||||
- name: resultado
|
||||
type: categorical
|
||||
- name: calidad_muestra
|
||||
type: categorical
|
||||
- name: citologia_fecha_reporte
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: resultado_conocido_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: biopsia_fuente_id
|
||||
type: categorical
|
||||
- name: biopsia_gravedad
|
||||
type: categorical
|
||||
measures:
|
||||
- name: pacientes_tamizadas
|
||||
description: "Distinct patients: each counts once per period, however many samples or biopsies."
|
||||
agg: count_distinct
|
||||
expr: pac_id
|
||||
|
||||
metrics:
|
||||
- name: cacu_eu13_denominador
|
||||
label: "EU13: pacientes tamizadas"
|
||||
type: simple
|
||||
type_params:
|
||||
measure: pacientes_tamizadas
|
||||
config:
|
||||
meta:
|
||||
poblaciones_fhir: [initial-population, denominator]
|
||||
conocida_en: [toma_conocida_en]
|
||||
- name: cacu_eu13_numerador
|
||||
label: "EU13: de ellas, con lesión confirmada por biopsia"
|
||||
type: simple
|
||||
type_params:
|
||||
measure: pacientes_tamizadas
|
||||
filter: "{{ Dimension('toma_biopsia__biopsia_grado') }} in :deteccion_grados"
|
||||
config:
|
||||
meta:
|
||||
poblaciones_fhir: [numerator]
|
||||
# The biopsy counts in its sample's period, if it was reported by the event cut-off.
|
||||
fechada_en: [biopsia_fecha_reporte]
|
||||
conocida_en: [toma_conocida_en, biopsia_conocida_en]
|
||||
- name: cacu_eu13
|
||||
label: "Tasa de detección histopatológica"
|
||||
description: >-
|
||||
De todas las mujeres tamizadas en el periodo, las que tienen una biopsia reportada con LIEAG (CIN 2 y 3),
|
||||
carcinoma in situ o carcinoma invasor, originada por una de sus citologías del periodo.
|
||||
type: ratio
|
||||
type_params:
|
||||
numerator: cacu_eu13_numerador
|
||||
denominator: cacu_eu13_denominador
|
||||
config:
|
||||
meta:
|
||||
measure_url: cacu/CACU_EU13
|
||||
version: 0.3.2
|
||||
scoring: proportion
|
||||
basis: paciente
|
||||
grupo: principal
|
||||
contrato: C1
|
||||
tipos_periodo: [semestre, mes]
|
||||
parametros:
|
||||
deteccion_grados: cacu.deteccion_grados
|
||||
estratos:
|
||||
# Age at the start of the period asked: it depends on the question, so it can't be a column of the model.
|
||||
grupo_edad:
|
||||
tipo: edad_al_inicio_del_periodo
|
||||
nacimiento: fecha_nacimiento
|
||||
# ASCCP follow-up status before the period's start: what the patient's timeline held by then (the
|
||||
# procedures cacu_procedimientos_inferidos adds to it). The first value that holds wins. INFO_INSUFICIENTE,
|
||||
# third in precedence, needs an enrolment date silver doesn't have yet, so today it's only the rest.
|
||||
estatus_seguimiento:
|
||||
tipo: linea_de_tiempo_al_inicio_del_periodo
|
||||
etiqueta: Estatus de seguimiento
|
||||
linea: cacu_linea_de_tiempo
|
||||
valores:
|
||||
- {valor: POST_TRATAMIENTO, si: [{tratamiento: true}]}
|
||||
- {valor: POST_COLPOSCOPIA, si: [{colposcopia: true}]}
|
||||
# Under surveillance, or no cytology yet: every cytology with a known specialty outside surveillance
|
||||
# takes her out.
|
||||
- {valor: PRE_COLPOSCOPIA, si: [{citologia_de_vigilancia: true}, {citologia: false}]}
|
||||
resto: INFO_INSUFICIENTE
|
||||
- name: cacu_confirmacion_citologia
|
||||
label: "Tasa de confirmación histopatológica"
|
||||
description: >-
|
||||
De las pacientes cuya última citología del periodo con resultado y calidad de espécimen satisfactoria es de alto
|
||||
grado (ASC-H, LIEAG o carcinoma in situ), cuántas tienen cada grado en la biopsia que esa citología originó, por
|
||||
resultado citológico. A la fecha de corte: sin un plazo máximo, una paciente «sin biopsia aún» puede pasar a un
|
||||
grado mientras lleguen reportes.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: pacientes_tamizadas
|
||||
config:
|
||||
meta:
|
||||
measure_url: cacu/CACU_CONFIRMACION_CITOLOGIA
|
||||
version: 0.1.2
|
||||
scoring: composition
|
||||
basis: paciente
|
||||
grupo: TOTAL
|
||||
contrato: C2
|
||||
tipos_periodo: [semestre, mes]
|
||||
poblaciones_fhir: [measure-observation]
|
||||
conocida_en: [toma_conocida_en]
|
||||
parametros:
|
||||
calidad_insatisfactoria: cacu.calidad_insatisfactoria
|
||||
citologia_alto_grado: cacu.citologia_alto_grado
|
||||
# Each patient's last valid sample of the period, as in CACU_EU7; she counts only if its result is high grade,
|
||||
# and her category is the most severe biopsy that sample led to and that was reported by the cut-off (the
|
||||
# latest, then the higher source id, among equals).
|
||||
categoria:
|
||||
valor: biopsia_grado
|
||||
sin_dato: SIN_DATO
|
||||
elige: ultimo_valido
|
||||
valido: >-
|
||||
{% raw %}{{ Dimension('toma_biopsia__resultado') }} is not null and
|
||||
({{ Dimension('toma_biopsia__calidad_muestra') }} is null
|
||||
or {{ Dimension('toma_biopsia__calidad_muestra') }} <> :calidad_insatisfactoria){% endraw %}
|
||||
fechada_en: [citologia_fecha_reporte]
|
||||
conocida_en: [resultado_conocido_en]
|
||||
orden: [fecha_toma, fuente_id]
|
||||
admite: "{% raw %}{{ Dimension('toma_biopsia__resultado') }} in :citologia_alto_grado{% endraw %}"
|
||||
seguimiento:
|
||||
existe: biopsia_fecha_reporte
|
||||
fechada_en: [biopsia_fecha_reporte]
|
||||
conocida_en: [biopsia_conocida_en]
|
||||
orden: [biopsia_gravedad, biopsia_fecha_reporte, biopsia_fuente_id]
|
||||
sin_seguimiento: SIN_BIOPSIA
|
||||
estratos:
|
||||
# The result of that same sample.
|
||||
citologia_alto_grado:
|
||||
tipo: del_elegido
|
||||
etiqueta: Citología de alto grado
|
||||
valor: resultado
|
||||
@@ -0,0 +1,71 @@
|
||||
-- One row per cytology taken: the event grain the measures are asked over. No period and no cut-off here: they're
|
||||
-- the question's. Two knowledge dates, because the sample and its result arrive in different loads: when the sample
|
||||
-- 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.
|
||||
|
||||
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
|
||||
),
|
||||
|
||||
-- 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
|
||||
),
|
||||
|
||||
primer_antecedente as (
|
||||
select pac_id, min(fecha) as fecha
|
||||
from {{ ref('cacu_linea_de_tiempo') }}
|
||||
where tipo = 'antecedente'
|
||||
group by pac_id
|
||||
)
|
||||
|
||||
|
||||
select
|
||||
c.procedimiento_id,
|
||||
c.fuente_id,
|
||||
c.pac_id,
|
||||
c.fecha_toma,
|
||||
toma.inicio as toma_conocida_en,
|
||||
c.calidad_muestra,
|
||||
c.resultado,
|
||||
c.fecha_reporte,
|
||||
resultado.inicio as resultado_conocido_en,
|
||||
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,
|
||||
dia_diagnostico.dia_num - dia_toma.dia_num as dias_toma_diagnostico,
|
||||
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
|
||||
on persona.pac_id = c.pac_id
|
||||
join {{ source('silver', 'carga') }} toma
|
||||
on toma.carga_id = c.toma_carga_id
|
||||
left join {{ source('silver', 'carga') }} resultado
|
||||
on resultado.carga_id = c.resultado_carga_id and c.resultado is not null
|
||||
-- Days as differences of `dim_fecha.dia_num`: plain arithmetic, no engine date function.
|
||||
left join {{ source('silver', 'dim_fecha') }} dia_toma
|
||||
on dia_toma.fecha = c.fecha_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
|
||||
left join {{ source('silver', 'dim_fecha') }} dia_diagnostico
|
||||
on dia_diagnostico.fecha = dx.fecha_diagnostico
|
||||
left join primer_antecedente antecedente
|
||||
on antecedente.pac_id = c.pac_id
|
||||
@@ -0,0 +1,232 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_tomas_citologia
|
||||
description: "Citologías tomadas, una fila por toma, con cuándo se supo de la toma y de su resultado."
|
||||
config:
|
||||
materialized: view
|
||||
|
||||
semantic_models:
|
||||
- name: cacu_tomas_citologia
|
||||
description: "Cytologies taken, one row each: what CaCu's cytology measures count over."
|
||||
model: ref('cacu_tomas_citologia')
|
||||
defaults:
|
||||
agg_time_dimension: fecha_toma
|
||||
entities:
|
||||
- name: toma
|
||||
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_reporte
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: fecha_nacimiento
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: resultado
|
||||
type: categorical
|
||||
- name: calidad_muestra
|
||||
type: categorical
|
||||
- name: fuente_id
|
||||
type: categorical
|
||||
- name: toma_dia
|
||||
type: categorical
|
||||
- name: dias_toma_reporte
|
||||
type: categorical
|
||||
- name: fecha_diagnostico
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: diagnostico_conocido_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: dias_toma_diagnostico
|
||||
type: categorical
|
||||
- name: con_antecedente
|
||||
type: categorical
|
||||
measures:
|
||||
- name: citologias
|
||||
description: "Distinct samples (the source's cytology id): the unit of the times from sample to result."
|
||||
agg: count_distinct
|
||||
expr: fuente_id
|
||||
- name: pacientes_con_toma
|
||||
description: "Distinct patients: each counts once per period, however many samples."
|
||||
agg: count_distinct
|
||||
expr: pac_id
|
||||
|
||||
metrics:
|
||||
- name: cacu_ind1_denominador
|
||||
label: "IND1: pacientes con citología tomada"
|
||||
type: simple
|
||||
type_params:
|
||||
measure: pacientes_con_toma
|
||||
config:
|
||||
meta:
|
||||
poblaciones_fhir: [initial-population, denominator]
|
||||
conocida_en: [toma_conocida_en]
|
||||
- name: cacu_ind1_numerador
|
||||
label: "IND1: de ellas, con algún resultado anómalo"
|
||||
type: simple
|
||||
type_params:
|
||||
measure: pacientes_con_toma
|
||||
filter: "{{ Dimension('toma__resultado') }} in :citologia_anomala"
|
||||
config:
|
||||
meta:
|
||||
poblaciones_fhir: [numerator]
|
||||
conocida_en: [toma_conocida_en, resultado_conocido_en]
|
||||
- name: cacu_ind1
|
||||
label: "Pacientes con citología anómala"
|
||||
description: >-
|
||||
Proporción de pacientes con citología tomada en el periodo con al menos un resultado anómalo: ASC-US, LIEBG,
|
||||
ASC-H, LIEAG o carcinoma in situ (sistema Bethesda). Una paciente con varias citologías cuenta una vez.
|
||||
type: ratio
|
||||
type_params:
|
||||
numerator: cacu_ind1_numerador
|
||||
denominator: cacu_ind1_denominador
|
||||
config:
|
||||
meta:
|
||||
measure_url: cacu/IND1
|
||||
version: 0.3.2
|
||||
scoring: proportion
|
||||
basis: paciente
|
||||
grupo: principal
|
||||
improvement_notation: decrease
|
||||
contrato: C1
|
||||
tipos_periodo: [semestre, mes]
|
||||
parametros:
|
||||
citologia_anomala: cacu.citologia_anomala
|
||||
- name: cacu_eu7
|
||||
label: "Distribución de resultados citológicos"
|
||||
description: >-
|
||||
Cuántas pacientes caen en cada resultado citológico en el periodo, cada una en el de su última citología con
|
||||
resultado y calidad de espécimen satisfactoria. «Sin dato»: resultado no disponible o de calidad de espécimen
|
||||
insatisfactoria a la fecha de corte.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: pacientes_con_toma
|
||||
config:
|
||||
meta:
|
||||
measure_url: cacu/CACU_EU7
|
||||
version: 0.3.3
|
||||
scoring: composition
|
||||
basis: paciente
|
||||
grupo: TOTAL
|
||||
contrato: C2
|
||||
tipos_periodo: [semestre, mes]
|
||||
poblaciones_fhir: [measure-observation]
|
||||
conocida_en: [toma_conocida_en]
|
||||
parametros:
|
||||
calidad_insatisfactoria: cacu.calidad_insatisfactoria
|
||||
# Each patient's category is the result of her last valid sample of the period asked: it depends on the
|
||||
# question (the period, the cut-offs), so it's a rule of the answer, not a column of the model.
|
||||
categoria:
|
||||
valor: resultado
|
||||
sin_dato: SIN_DATO
|
||||
elige: ultimo_valido
|
||||
# `raw`: dbt renders Jinja in `meta`; the template is the answer's to render, like a metric's `filter`.
|
||||
valido: >-
|
||||
{% raw %}{{ Dimension('toma__resultado') }} is not null and ({{ Dimension('toma__calidad_muestra') }} is null
|
||||
or {{ Dimension('toma__calidad_muestra') }} <> :calidad_insatisfactoria){% endraw %}
|
||||
fechada_en: [fecha_reporte]
|
||||
conocida_en: [resultado_conocido_en]
|
||||
orden: [fecha_toma, fuente_id]
|
||||
estratos:
|
||||
grupo_edad:
|
||||
tipo: edad_al_inicio_del_periodo
|
||||
nacimiento: fecha_nacimiento
|
||||
# ASCCP follow-up status before the period's start: what the patient's timeline held by then (the
|
||||
# procedures cacu_procedimientos_inferidos adds to it). The first value that holds wins. INFO_INSUFICIENTE,
|
||||
# third in precedence, needs an enrolment date silver doesn't have yet, so today it's only the rest.
|
||||
estatus_seguimiento:
|
||||
tipo: linea_de_tiempo_al_inicio_del_periodo
|
||||
etiqueta: Estatus de seguimiento
|
||||
linea: cacu_linea_de_tiempo
|
||||
valores:
|
||||
- {valor: POST_TRATAMIENTO, si: [{tratamiento: true}]}
|
||||
- {valor: POST_COLPOSCOPIA, si: [{colposcopia: true}]}
|
||||
# Under surveillance, or no cytology yet: every cytology with a known specialty outside surveillance
|
||||
# takes her out.
|
||||
- {valor: PRE_COLPOSCOPIA, si: [{citologia_de_vigilancia: true}, {citologia: false}]}
|
||||
resto: INFO_INSUFICIENTE
|
||||
- name: cacu_eu_tiempo_reporte
|
||||
label: "Días de la toma de la citología a su resultado"
|
||||
description: >-
|
||||
Días naturales de la toma de cada citología del periodo a su resultado, a la fecha de corte. Las que aún no
|
||||
tienen resultado y siguen dentro del horizonte no se miden; las que lo pasaron sin resultado cuentan en los
|
||||
excluidos.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: citologias
|
||||
config:
|
||||
meta:
|
||||
measure_url: cacu/CACU_EU_TIEMPO_REPORTE
|
||||
version: 0.2.1
|
||||
scoring: continuous-variable
|
||||
basis: examen
|
||||
grupo: TOTAL
|
||||
contrato: C3r
|
||||
improvement_notation: decrease
|
||||
tipos_periodo: [semestre, mes]
|
||||
poblaciones_fhir: [initial-population]
|
||||
conocida_en: [toma_conocida_en]
|
||||
parametros:
|
||||
horizonte_dias: cacu.horizontes.toma_reporte_dias
|
||||
# Each sample's number of days, if its result came by the event cut-off; a sample without one whose horizon
|
||||
# hasn't passed by then isn't measured yet (it's left out of the initial population).
|
||||
observacion:
|
||||
valor: dias_toma_reporte
|
||||
fechada_en: [fecha_reporte]
|
||||
conocida_en: [resultado_conocido_en]
|
||||
horizonte:
|
||||
regla: horizonte_dias
|
||||
dia_inicio: toma_dia
|
||||
- name: cacu_dias_toma_diagnostico
|
||||
label: "Tiempo de tamizaje a diagnóstico"
|
||||
description: >-
|
||||
Días naturales de la toma de cada citología del periodo a la primera nota médica posterior que la resuelve: un
|
||||
diagnóstico CIE-10 de la lista (normal, benigno, lesión o cáncer), escrito por una de las especialidades que
|
||||
diagnostican, 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.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: citologias
|
||||
filter: "{{ Dimension('toma__con_antecedente') }} = 0"
|
||||
config:
|
||||
meta:
|
||||
measure_url: cacu/CACU_DIAS_TOMA_DIAGNOSTICO
|
||||
version: 0.2.3
|
||||
scoring: continuous-variable
|
||||
basis: examen
|
||||
grupo: TOTAL
|
||||
contrato: C3r
|
||||
improvement_notation: decrease
|
||||
tipos_periodo: [semestre, mes]
|
||||
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
|
||||
# horizon hasn't passed by then isn't measured yet. The horizon is the one the model used to find the note.
|
||||
observacion:
|
||||
valor: dias_toma_diagnostico
|
||||
fechada_en: [fecha_diagnostico]
|
||||
conocida_en: [diagnostico_conocido_en]
|
||||
horizonte:
|
||||
dias: "{{ var('horizonte_toma_diagnostico_dias') }}"
|
||||
dia_inicio: toma_dia
|
||||
@@ -1,31 +0,0 @@
|
||||
-- CACU_IND1: pacientes tamizadas con resultado citológico anómalo. Unidad: paciente. C1.
|
||||
-- denominador: pacientes con ≥1 citología tomada en el periodo
|
||||
-- numerador: de ellas, las que tienen alguna con resultado en citologia_anomala
|
||||
|
||||
with citologias as (
|
||||
select * from {{ ref('cacu_citologias') }}
|
||||
),
|
||||
|
||||
tomas_del_periodo as (
|
||||
select
|
||||
pac_id,
|
||||
resultado
|
||||
from citologias
|
||||
where fecha_toma >= '{{ var("periodo_inicio") }}'
|
||||
and fecha_toma < '{{ var("periodo_fin") }}'
|
||||
),
|
||||
|
||||
denominador as (
|
||||
select distinct pac_id as unidad_id
|
||||
from tomas_del_periodo
|
||||
),
|
||||
|
||||
numerador as (
|
||||
select distinct pac_id as unidad_id
|
||||
from tomas_del_periodo
|
||||
where resultado in ({% for r in var("citologia_anomala") %}'{{ r }}'{% if not loop.last %}, {% endif %}{% endfor %})
|
||||
)
|
||||
|
||||
select 'denominador' as poblacion, unidad_id from denominador
|
||||
union all
|
||||
select 'numerador' as poblacion, unidad_id from numerador
|
||||
@@ -1,21 +0,0 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_ind1
|
||||
description: "Pacientes tamizadas con resultado citológico anómalo (C1). Denominador: con ≥1 citología en el periodo. Numerador: con algún resultado en citologia_anomala."
|
||||
meta:
|
||||
measure_url: "cacu/CACU_IND1"
|
||||
contrato: C1
|
||||
unidad: paciente
|
||||
parametros:
|
||||
periodo_inicio: periodo_inicio
|
||||
periodo_fin: periodo_fin
|
||||
citologia_anomala: cacu.citologia_anomala
|
||||
poblaciones:
|
||||
denominador: "Pacientes con ≥1 citología tomada en el periodo"
|
||||
numerador: "De ellas, con algún resultado en citologia_anomala"
|
||||
columns:
|
||||
- name: poblacion
|
||||
description: "denominador | numerador"
|
||||
- name: unidad_id
|
||||
description: "pac_id del paciente"
|
||||
@@ -1,66 +0,0 @@
|
||||
-- CACU_TIEMPO_REPORTE: días naturales de la toma de citología a su resultado. Unidad: examen. C3r.
|
||||
-- initial-population: citologías tomadas en el periodo que ya se pueden medir
|
||||
-- (con resultado al corte o con el horizonte ya vencido)
|
||||
-- measure-observation: de ellas, las que tienen resultado, con sus días
|
||||
|
||||
with citologias as (
|
||||
select * from {{ ref('cacu_citologias') }}
|
||||
),
|
||||
|
||||
tomas as (
|
||||
select
|
||||
fuente_id,
|
||||
pac_id,
|
||||
fecha_toma as toma,
|
||||
case
|
||||
when fecha_reporte <= '{{ var("fecha_corte") }}' then fecha_reporte
|
||||
end as reporte
|
||||
from citologias
|
||||
where fecha_toma >= '{{ var("periodo_inicio") }}'
|
||||
and fecha_toma < '{{ var("periodo_fin") }}'
|
||||
),
|
||||
|
||||
con_estado as (
|
||||
select
|
||||
fuente_id,
|
||||
pac_id,
|
||||
toma,
|
||||
reporte,
|
||||
reporte is null
|
||||
and {{ dbt.datediff("toma", date_literal(var("fecha_corte")), "day") }}
|
||||
< {{ var("horizonte_toma_reporte_dias") }} as pendiente
|
||||
from tomas
|
||||
),
|
||||
|
||||
poblacion_inicial as (
|
||||
select fuente_id as unidad_id, pac_id, 'TOTAL' as grupo
|
||||
from con_estado
|
||||
where not pendiente
|
||||
),
|
||||
|
||||
observacion as (
|
||||
select
|
||||
fuente_id as unidad_id,
|
||||
pac_id,
|
||||
'TOTAL' as grupo,
|
||||
{{ dbt.datediff("toma", "reporte", "day") }} as valor
|
||||
from con_estado
|
||||
where reporte is not null
|
||||
)
|
||||
|
||||
-- Typed output: the same columns and types on every engine (and SQLite reports no type for an untyped literal).
|
||||
select
|
||||
{{ as_text("'initial-population'") }} as poblacion,
|
||||
{{ as_text("unidad_id") }} as unidad_id,
|
||||
{{ as_integer("pac_id") }} as pac_id,
|
||||
{{ as_text("grupo") }} as grupo,
|
||||
{{ as_integer("null") }} as valor
|
||||
from poblacion_inicial
|
||||
union all
|
||||
select
|
||||
{{ as_text("'measure-observation'") }},
|
||||
{{ as_text("unidad_id") }},
|
||||
{{ as_integer("pac_id") }},
|
||||
{{ as_text("grupo") }},
|
||||
{{ as_integer("valor") }}
|
||||
from observacion
|
||||
@@ -1,64 +0,0 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_tiempo_reporte
|
||||
description: "Días naturales de la toma de citología a su resultado (C3r). Unidad: examen."
|
||||
meta:
|
||||
measure_url: "cacu/CACU_TIEMPO_REPORTE"
|
||||
contrato: C3r
|
||||
unidad: examen
|
||||
parametros:
|
||||
periodo_inicio: periodo_inicio
|
||||
periodo_fin: periodo_fin
|
||||
fecha_corte: fecha_corte
|
||||
horizonte_toma_reporte_dias: cacu.horizontes.toma_reporte_dias
|
||||
poblaciones:
|
||||
initial-population: "Citologías del periodo medibles al corte (con resultado o con horizonte vencido)"
|
||||
measure-observation: "De ellas, las que tienen resultado, con los días de toma a reporte"
|
||||
columns:
|
||||
- name: poblacion
|
||||
description: "initial-population | measure-observation"
|
||||
- name: unidad_id
|
||||
description: "fuente_id de la citología"
|
||||
- name: pac_id
|
||||
description: "pac_id del paciente (para estratificación)"
|
||||
- name: grupo
|
||||
description: "TOTAL"
|
||||
- name: valor
|
||||
description: "Días naturales de toma a reporte (NULL en initial-population)"
|
||||
|
||||
unit_tests:
|
||||
- name: tiempo_reporte_counts_days_with_the_engine_s_datediff
|
||||
description: >
|
||||
Pins down: days from sample to report are whole calendar days, across a month boundary (A, 30) and
|
||||
across the end of February (B, 10); a sample without a report still inside the horizon is pending and
|
||||
left out (C, 44 days < 60); one past the horizon counts in the population without a value (D). On
|
||||
SQLite this goes through the project's `sqlite__datediff`. Fails if `datediff` counts anything but
|
||||
whole days, takes its arguments in another order, or the horizon check changes side.
|
||||
model: cacu_tiempo_reporte
|
||||
overrides:
|
||||
vars:
|
||||
periodo_inicio: "2025-01-01"
|
||||
periodo_fin: "2025-07-01"
|
||||
fecha_corte: "2025-07-15"
|
||||
horizonte_toma_reporte_dias: 60
|
||||
given:
|
||||
- input: ref('cacu_citologias')
|
||||
format: sql
|
||||
rows: |
|
||||
select 1 as procedimiento_id, 'citologiacervical' as fuente_tabla, 'A' as fuente_id, 1 as pac_id,
|
||||
'2025-01-10' as fecha_toma, null as orden_numero, null as calidad_muestra, null as resultado,
|
||||
'2025-02-09' as fecha_reporte, null as vph, null as genotipo_16_18
|
||||
union all
|
||||
select 2, 'citologiacervical', 'B', 2, '2025-02-20', null, null, null, '2025-03-02', null, null
|
||||
union all
|
||||
select 3, 'citologiacervical', 'C', 3, '2025-06-01', null, null, null, null, null, null
|
||||
union all
|
||||
select 4, 'citologiacervical', 'D', 4, '2025-03-01', null, null, null, null, null, null
|
||||
expect:
|
||||
rows:
|
||||
- {poblacion: initial-population, unidad_id: A, pac_id: 1, grupo: TOTAL, valor: null}
|
||||
- {poblacion: initial-population, unidad_id: B, pac_id: 2, grupo: TOTAL, valor: null}
|
||||
- {poblacion: initial-population, unidad_id: D, pac_id: 4, grupo: TOTAL, valor: null}
|
||||
- {poblacion: measure-observation, unidad_id: A, pac_id: 1, grupo: TOTAL, valor: 30}
|
||||
- {poblacion: measure-observation, unidad_id: B, pac_id: 2, grupo: TOTAL, valor: 10}
|
||||
@@ -16,12 +16,13 @@ SELECT
|
||||
p_rep.fuente_id,
|
||||
p_rep.pac_id,
|
||||
p_rep.fecha AS fecha_reporte,
|
||||
o_grado.valor_id AS grado,
|
||||
coalesce(o_grado.valor_id, o_grado.valor_fuente) AS grado,
|
||||
p_ord.fecha AS fecha_solicitud,
|
||||
p_ord.orden_numero,
|
||||
p_toma.procedimiento_id AS toma_id,
|
||||
p_toma.pac_id AS toma_pac_id,
|
||||
p_toma.fecha AS fecha_toma
|
||||
p_toma.fecha AS fecha_toma,
|
||||
coalesce(o_grado.carga_id, p_rep.carga_id) AS reporte_carga_id
|
||||
FROM {{ source('silver', 'procedimiento') }} p_rep
|
||||
LEFT JOIN {{ source('silver', 'observacion_clinica') }} o_grado
|
||||
ON o_grado.procedimiento_id = p_rep.procedimiento_id
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
Los tres procedimientos (toma, reporte-citología, reporte-vph) comparten
|
||||
fuente_id = cit_id porque los tres vienen de la misma fila de citologia_cervical.
|
||||
|
||||
Equivalente dbt de plata.py::citologias().
|
||||
Equivalente dbt de plata.py::citologias(). A code the catalog doesn't know comes as it arrived
|
||||
(`coalesce(valor_id, valor_fuente)`), as the timeline reads it.
|
||||
*/
|
||||
|
||||
SELECT
|
||||
@@ -13,11 +14,13 @@ SELECT
|
||||
p_toma.pac_id,
|
||||
p_toma.fecha AS fecha_toma,
|
||||
p_toma.orden_numero,
|
||||
o_cal.valor_id AS calidad_muestra,
|
||||
o_beth.valor_id AS resultado,
|
||||
coalesce(o_cal.valor_id, o_cal.valor_fuente) AS calidad_muestra,
|
||||
coalesce(o_beth.valor_id, o_beth.valor_fuente) AS resultado,
|
||||
p_rep.fecha AS fecha_reporte,
|
||||
o_vph.valor_id AS vph,
|
||||
o_vph_g.valor_numerico AS genotipo_16_18
|
||||
coalesce(o_vph.valor_id, o_vph.valor_fuente) AS vph,
|
||||
o_vph_g.valor_numerico AS genotipo_16_18,
|
||||
p_toma.carga_id AS toma_carga_id,
|
||||
coalesce(o_beth.carga_id, p_rep.carga_id) AS resultado_carga_id
|
||||
FROM {{ source('silver', 'procedimiento') }} p_toma
|
||||
LEFT JOIN {{ source('silver', 'procedimiento') }} p_rep
|
||||
ON p_rep.fuente_tabla = p_toma.fuente_tabla
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
{# A view, not ephemeral like the other silver models: cohorts query it. Its sources: cacu_linea_de_tiempo.yml. #}
|
||||
{# 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. #}
|
||||
{{ 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') }}
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
{{ config(materialized = 'view') }}
|
||||
-- The procedures the notes, orders and biopsies imply but silver doesn't hold as such, in the timeline's shape
|
||||
-- (`cacu_linea_de_tiempo` adds them to each patient's timeline):
|
||||
-- colposcopia a colposcopy: a colposcopy note (by its reason, its ICD-10 or its diagnosis text), a
|
||||
-- biopsy order, or a reported biopsy
|
||||
-- tratamiento a note with a treatment ICD-10 after the patient's first colposcopy
|
||||
-- citologia_de_vigilancia a cytology whose order's specialty is unknown or one of the surveillance ones
|
||||
-- diagnostico a note that can resolve a cytology: a diagnosis ICD-10 (`cie_diagnostico`) written by
|
||||
-- a diagnosing specialty (`especialidades_diagnostico`)
|
||||
-- antecedente a note with a cervical cancer ICD-10 (`cie_antecedente`), whoever wrote it
|
||||
-- Every rule is a dbt var (`seguimiento`, and the diagnosis rules shared with CACU_DIAS_TOMA_DIAGNOSTICO), so
|
||||
-- changing one is recompiling, not reloading.
|
||||
{% set s = var('seguimiento') %}
|
||||
|
||||
with nota as (
|
||||
select
|
||||
p.pac_id,
|
||||
p.fecha,
|
||||
p.fuente_tabla,
|
||||
p.fuente_id,
|
||||
c.inicio as conocida_en,
|
||||
max(case when o.resultado_id = 'nota_medica.diagnostico' then o.valor_texto end) as cie_codigo,
|
||||
max(case when o.resultado_id = 'nota_medica.especialidad' then o.valor_id end) as especialidad,
|
||||
max(case when o.resultado_id = 'nota_medica.motivo' then o.valor_texto end) as motivo,
|
||||
max(case when o.resultado_id = 'nota_medica.diagnostico_texto' then o.valor_texto end) as diagnostico_texto
|
||||
from {{ source('silver', 'procedimiento') }} p
|
||||
join {{ source('silver', 'carga') }} c on c.carga_id = p.carga_id
|
||||
left join {{ source('silver', 'observacion_clinica') }} o on o.procedimiento_id = p.procedimiento_id
|
||||
where p.estudio_id = 'nota_medica' and p.clase = 'encuentro'
|
||||
group by p.procedimiento_id, p.pac_id, p.fecha, p.fuente_tabla, p.fuente_id, c.inicio
|
||||
),
|
||||
|
||||
toma as (
|
||||
select t.pac_id, t.fecha, t.fuente_tabla, t.fuente_id, c.inicio as conocida_en, o.valor_id as especialidad
|
||||
from {{ source('silver', 'procedimiento') }} t
|
||||
join {{ source('silver', 'carga') }} c on c.carga_id = t.carga_id
|
||||
left join {{ source('silver', 'procedimiento') }} orden
|
||||
on orden.procedimiento_id = t.padre_id and orden.estudio_id = 'citologia' and orden.clase = 'orden'
|
||||
left join {{ source('silver', 'observacion_clinica') }} o
|
||||
on o.procedimiento_id = orden.procedimiento_id and o.resultado_id = 'orden.especialidad'
|
||||
where t.estudio_id = 'citologia' and t.clase = 'toma'
|
||||
),
|
||||
|
||||
diagnostico as (
|
||||
select * from nota
|
||||
where cie_codigo in {{ sql_list(var('cie_diagnostico')) }}
|
||||
and especialidad in {{ sql_list(var('especialidades_diagnostico')) }}
|
||||
),
|
||||
|
||||
-- The valuation visit: the first diagnosis that resolves one of her cytologies, after it and within the horizon,
|
||||
-- as CACU_DIAS_TOMA_DIAGNOSTICO reads it. Days are differences of `dim_fecha.dia_num`.
|
||||
valoracion as (
|
||||
select n.pac_id, min(n.fecha) as primera
|
||||
from diagnostico n
|
||||
join toma t on t.pac_id = n.pac_id
|
||||
join {{ source('silver', 'dim_fecha') }} dn on dn.fecha = n.fecha
|
||||
join {{ source('silver', 'dim_fecha') }} dt on dt.fecha = t.fecha
|
||||
where n.fecha > t.fecha
|
||||
and dn.dia_num - dt.dia_num < {{ var('horizonte_toma_diagnostico_dias') }}
|
||||
group by n.pac_id
|
||||
),
|
||||
|
||||
-- A colposcopy note: of a colposcopy specialty and, by rule, after the first valuation visit.
|
||||
nota_de_colposcopia as (
|
||||
select n.*
|
||||
from nota n
|
||||
{% if s['colposcopia_requisito'] == 'valoracion_previa' %}
|
||||
join valoracion v on v.pac_id = n.pac_id and n.fecha > v.primera
|
||||
{% endif %}
|
||||
where n.especialidad in {{ sql_list(s['colposcopia_especialidades']) }}
|
||||
),
|
||||
|
||||
-- What counts as a colposcopy. A biopsy order, and a reported biopsy's request, count by rule only on the day of a
|
||||
-- colposcopy note: the colposcopy is the biopsy's parent.
|
||||
colposcopia as (
|
||||
select pac_id, fecha, conocida_en, fuente_tabla, fuente_id from nota_de_colposcopia where 1 = 0
|
||||
{% if 'motivo' in s['colposcopia_evidencias'] %}{% for m in s['colposcopia_motivos'] %}
|
||||
union all
|
||||
select pac_id, fecha, conocida_en, fuente_tabla, fuente_id from nota_de_colposcopia where {{ sin_acentos_mayusculas('motivo') }} like '%{{ m }}%'
|
||||
{% endfor %}{% endif %}
|
||||
{% if 'cie' in s['colposcopia_evidencias'] %}
|
||||
union all
|
||||
select pac_id, fecha, conocida_en, fuente_tabla, fuente_id from nota_de_colposcopia where cie_codigo in {{ sql_list(s['colposcopia_cie']) }}
|
||||
{% endif %}
|
||||
{% if 'diagnostico_texto' in s['colposcopia_evidencias'] %}{% for d in s['colposcopia_diagnosticos'] %}
|
||||
union all
|
||||
select pac_id, fecha, conocida_en, fuente_tabla, fuente_id from nota_de_colposcopia
|
||||
where {{ sin_acentos_mayusculas('diagnostico_texto') }} like '%{{ d }}%'
|
||||
{% endfor %}{% endif %}
|
||||
{% if 'orden_biopsia' in s['colposcopia_evidencias'] %}
|
||||
union all
|
||||
select o.pac_id, o.fecha, c.inicio, o.fuente_tabla, o.fuente_id
|
||||
from {{ source('silver', 'procedimiento') }} o
|
||||
join {{ source('silver', 'carga') }} c on c.carga_id = o.carga_id
|
||||
where o.estudio_id = 'biopsia' and o.clase = 'orden'
|
||||
{% if s['biopsia_requisito'] == 'mismo_dia_que_colposcopia' %}
|
||||
and exists (select 1 from nota_de_colposcopia v where v.pac_id = o.pac_id and v.fecha = o.fecha)
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% if 'biopsia' in s['colposcopia_evidencias'] %}
|
||||
union all
|
||||
select b.pac_id, b.fecha_reporte, c.inicio, b.fuente_tabla, b.fuente_id
|
||||
from {{ ref('cacu_biopsias') }} b
|
||||
join {{ source('silver', 'carga') }} c on c.carga_id = b.reporte_carga_id
|
||||
where 1 = 1
|
||||
{% if s['biopsia_requisito'] == 'mismo_dia_que_colposcopia' %}
|
||||
and exists (select 1 from nota_de_colposcopia v where v.pac_id = b.pac_id and v.fecha = b.fecha_solicitud)
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
),
|
||||
|
||||
primera_colposcopia as (
|
||||
select pac_id, min(fecha) as primera from colposcopia group by pac_id
|
||||
),
|
||||
|
||||
inferidos as (
|
||||
select pac_id, fecha, conocida_en, 'colposcopia' as tipo, fuente_tabla, fuente_id from colposcopia
|
||||
union all
|
||||
select n.pac_id, n.fecha, n.conocida_en, 'tratamiento', n.fuente_tabla, n.fuente_id
|
||||
from nota n
|
||||
join primera_colposcopia pc on pc.pac_id = n.pac_id and n.fecha > pc.primera
|
||||
where n.cie_codigo in {{ sql_list(s['tratamiento_cie']) }}
|
||||
union all
|
||||
select pac_id, fecha, conocida_en, 'diagnostico', fuente_tabla, fuente_id from diagnostico
|
||||
union all
|
||||
select pac_id, fecha, conocida_en, 'antecedente', fuente_tabla, fuente_id from nota
|
||||
where cie_codigo in {{ sql_list(var('cie_antecedente')) }}
|
||||
union all
|
||||
select pac_id, fecha, conocida_en, 'citologia_de_vigilancia', fuente_tabla, fuente_id from toma
|
||||
where especialidad is null or especialidad in {{ sql_list(s['vigilancia_especialidades']) }}
|
||||
)
|
||||
|
||||
select
|
||||
pac_id,
|
||||
fecha,
|
||||
conocida_en,
|
||||
{{ as_text("'procedimiento'") }} 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,
|
||||
fuente_tabla,
|
||||
fuente_id
|
||||
from inferidos
|
||||
where fecha is not null
|
||||
@@ -0,0 +1,23 @@
|
||||
-- One row per biopsy report with an invasive cancer (`vars.cama.grados_invasor`), dated by the report, with the
|
||||
-- BI-RADS of the mammogram that led to it (null when none was found or it has no report): the grain of the measures
|
||||
-- that describe the cancers found. When the report became known: the start of the load that wrote it. The birth date
|
||||
-- is the patient's, for strata by age; the tumour's stratifiers come from cama_estratificadores.
|
||||
|
||||
select
|
||||
b.procedimiento_id,
|
||||
b.fuente_id,
|
||||
b.pac_id,
|
||||
b.fecha_reporte,
|
||||
b.grado,
|
||||
m.birads,
|
||||
c.inicio as reporte_conocido_en,
|
||||
persona.fecha_nacimiento
|
||||
from {{ ref('cama_biopsias') }} b
|
||||
join {{ source('silver', 'carga') }} c
|
||||
on c.carga_id = b.reporte_carga_id
|
||||
join {{ source('silver', 'persona') }} persona
|
||||
on persona.pac_id = b.pac_id
|
||||
left join {{ ref('cama_mastografias') }} m
|
||||
on m.procedimiento_id = b.toma_id and m.pac_id = b.pac_id and m.birads is not null
|
||||
where b.fecha_reporte is not null
|
||||
and b.grado in {{ sql_list(var('cama')['grados_invasor']) }}
|
||||
@@ -0,0 +1,122 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cama_cancer_invasor
|
||||
description: "Reportes de biopsia con cáncer invasor, con el BI-RADS de la mastografía que los originó."
|
||||
config:
|
||||
materialized: view
|
||||
|
||||
semantic_models:
|
||||
- name: cama_cancer_invasor
|
||||
description: "Biopsy reports with an invasive cancer and the BI-RADS that led to them: what the cancers found count."
|
||||
model: ref('cama_cancer_invasor')
|
||||
defaults:
|
||||
agg_time_dimension: fecha_reporte
|
||||
entities:
|
||||
- name: cancer
|
||||
type: primary
|
||||
expr: procedimiento_id
|
||||
- name: paciente
|
||||
type: foreign
|
||||
expr: pac_id
|
||||
dimensions:
|
||||
- name: fecha_reporte
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: reporte_conocido_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: fecha_nacimiento
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: birads
|
||||
type: categorical
|
||||
- name: fuente_id
|
||||
type: categorical
|
||||
measures:
|
||||
- name: pacientes_con_cancer_invasor
|
||||
description: "Distinct patients: each counts once per period, however many reports."
|
||||
agg: count_distinct
|
||||
expr: pac_id
|
||||
|
||||
metrics:
|
||||
- name: cama_birads_cancer_invasor
|
||||
label: "BI-RADS de los cánceres invasores"
|
||||
description: >-
|
||||
De las pacientes con una biopsia reportada en el periodo con carcinoma invasor, cuántas tenían cada BI-RADS en la
|
||||
mastografía que originó su biopsia más reciente, por edad y por las características del tumor: estadio clínico,
|
||||
etapa, subtipo molecular y tamaño. Las características vienen de los reportes leídos por texto y son
|
||||
provisionales. «Sin dato»: la biopsia no se ligó a una mastografía con BI-RADS.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: pacientes_con_cancer_invasor
|
||||
config:
|
||||
meta:
|
||||
measure_url: cama/CAMA_BIRADS_CANCER_INVASOR
|
||||
version: 0.1.0
|
||||
scoring: composition
|
||||
basis: paciente
|
||||
grupo: TOTAL
|
||||
contrato: C2
|
||||
tipos_periodo: [semestre, mes]
|
||||
poblaciones_fhir: [measure-observation]
|
||||
conocida_en: [reporte_conocido_en]
|
||||
# Each patient's latest report of the period with a BI-RADS; one without it counts as SIN_DATO.
|
||||
categoria:
|
||||
valor: birads
|
||||
sin_dato: SIN_DATO
|
||||
elige: ultimo_valido
|
||||
valido: "{% raw %}{{ Dimension('cancer__birads') }} is not null{% endraw %}"
|
||||
orden: [fecha_reporte, fuente_id]
|
||||
# The tumour's stratifiers: what cama_estratificadores held by the event cut-off (the stage or the subtype
|
||||
# is usually written after the biopsy). The first value that holds wins: the most advanced, or for the
|
||||
# subtype the one with the worst prognosis, when the reports disagree.
|
||||
estratos:
|
||||
grupo_edad:
|
||||
tipo: edad_al_inicio_del_periodo
|
||||
nacimiento: fecha_nacimiento
|
||||
estadio:
|
||||
tipo: linea_de_tiempo_al_corte
|
||||
etiqueta: Estadio clínico
|
||||
linea: cama_estratificadores
|
||||
valores:
|
||||
- {valor: IV, etiqueta: Estadio IV, si: [{estadio_iv: true}]}
|
||||
- {valor: III, etiqueta: Estadio III, si: [{estadio_iii: true}]}
|
||||
- {valor: II, etiqueta: Estadio II, si: [{estadio_ii: true}]}
|
||||
- {valor: I, etiqueta: Estadio I, si: [{estadio_i: true}]}
|
||||
- {valor: "0", etiqueta: Estadio 0, si: [{estadio_0: true}]}
|
||||
resto: SIN_DATO
|
||||
resto_etiqueta: Sin dato
|
||||
etapa:
|
||||
tipo: linea_de_tiempo_al_corte
|
||||
etiqueta: Etapa
|
||||
linea: cama_estratificadores
|
||||
valores:
|
||||
- {valor: AVANZADA, etiqueta: Avanzada (III a IV), si: [{etapa_avanzada: true}]}
|
||||
- {valor: TEMPRANA, etiqueta: Temprana (0 a II), si: [{etapa_temprana: true}]}
|
||||
resto: SIN_DATO
|
||||
resto_etiqueta: Sin dato
|
||||
clasificacion:
|
||||
tipo: linea_de_tiempo_al_corte
|
||||
etiqueta: Subtipo molecular
|
||||
linea: cama_estratificadores
|
||||
valores:
|
||||
- {valor: TN, etiqueta: Triple negativo, si: [{subtipo_triple_negativo: true}]}
|
||||
- {valor: HER2, etiqueta: HER2 positivo, si: [{subtipo_her2: true}]}
|
||||
- {valor: LUM_B, etiqueta: Luminal B, si: [{subtipo_luminal_b: true}]}
|
||||
- {valor: LUM_A, etiqueta: Luminal A, si: [{subtipo_luminal_a: true}]}
|
||||
resto: SIN_DATO
|
||||
resto_etiqueta: Sin dato
|
||||
tamano:
|
||||
tipo: linea_de_tiempo_al_corte
|
||||
etiqueta: Tamaño tumoral (T)
|
||||
linea: cama_estratificadores
|
||||
valores:
|
||||
- {valor: T3, etiqueta: "> 5 cm (T3)", si: [{tamano_t3: true}]}
|
||||
- {valor: T2, etiqueta: "> 2 a 5 cm (T2)", si: [{tamano_t2: true}]}
|
||||
- {valor: T1, etiqueta: "≤ 2 cm (T1)", si: [{tamano_t1: true}]}
|
||||
resto: SIN_DATO
|
||||
resto_etiqueta: Sin dato
|
||||
@@ -0,0 +1,14 @@
|
||||
-- One row per biopsy report, dated by the report: what CaMa's biopsy distribution counts. Its grade as it arrived;
|
||||
-- when it became known, the start of the load that wrote it.
|
||||
|
||||
select
|
||||
b.procedimiento_id,
|
||||
b.fuente_id,
|
||||
b.pac_id,
|
||||
b.fecha_reporte,
|
||||
b.grado,
|
||||
c.inicio as reporte_conocido_en
|
||||
from {{ ref('cama_biopsias') }} b
|
||||
join {{ source('silver', 'carga') }} c
|
||||
on c.carga_id = b.reporte_carga_id
|
||||
where b.fecha_reporte is not null
|
||||
@@ -0,0 +1,67 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cama_reportes_biopsia
|
||||
description: "Reportes de biopsia de mama, uno por fila, fechados por el reporte."
|
||||
config:
|
||||
materialized: view
|
||||
|
||||
semantic_models:
|
||||
- name: cama_reportes_biopsia
|
||||
description: "Breast biopsy reports, dated by the report: what CaMa's biopsy distribution counts."
|
||||
model: ref('cama_reportes_biopsia')
|
||||
defaults:
|
||||
agg_time_dimension: fecha_reporte
|
||||
entities:
|
||||
- name: biopsia
|
||||
type: primary
|
||||
expr: procedimiento_id
|
||||
- name: paciente
|
||||
type: foreign
|
||||
expr: pac_id
|
||||
dimensions:
|
||||
- name: fecha_reporte
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: reporte_conocido_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: grado
|
||||
type: categorical
|
||||
- name: fuente_id
|
||||
type: categorical
|
||||
measures:
|
||||
- name: biopsias
|
||||
description: "Distinct biopsy reports: each biopsy counts, not each patient."
|
||||
agg: count_distinct
|
||||
expr: fuente_id
|
||||
|
||||
metrics:
|
||||
- name: cama_biopsias
|
||||
label: "Distribución de resultados de biopsia"
|
||||
description: >-
|
||||
Cuántas biopsias reportadas en el semestre caen en cada grado histológico. Se cuenta cada biopsia, no cada
|
||||
paciente. «Sin dato»: el reporte no trae grado.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: biopsias
|
||||
config:
|
||||
meta:
|
||||
measure_url: cama/CAMA_BIOPSIAS
|
||||
version: 0.2.0
|
||||
scoring: composition
|
||||
basis: examen
|
||||
grupo: TOTAL
|
||||
contrato: C2
|
||||
tipos_periodo: [semestre, mes]
|
||||
poblaciones_fhir: [measure-observation]
|
||||
conocida_en: [reporte_conocido_en]
|
||||
# One row per report: its grade.
|
||||
categoria:
|
||||
valor: grado
|
||||
sin_dato: SIN_DATO
|
||||
elige: ultimo_valido
|
||||
valido: "{% raw %}{{ Dimension('biopsia__grado') }} is not null{% endraw %}"
|
||||
orden: [fecha_reporte]
|
||||
@@ -0,0 +1,24 @@
|
||||
-- One row per mammogram's report and each biopsy report it led to (one row with nulls when it led to none): the grain
|
||||
-- of the measures that follow a suspicious mammogram to its biopsy. A biopsy counts for the mammogram that led to it,
|
||||
-- of the same patient. When each became known: the start of the loads that wrote them.
|
||||
|
||||
select
|
||||
m.procedimiento_id,
|
||||
m.fuente_id,
|
||||
m.pac_id,
|
||||
m.fecha_toma,
|
||||
toma.inicio as toma_conocida_en,
|
||||
m.fecha_reporte,
|
||||
m.birads,
|
||||
reporte.inicio as reporte_conocido_en,
|
||||
b.fecha_reporte as biopsia_fecha_reporte,
|
||||
biopsia.inicio as biopsia_conocida_en
|
||||
from {{ ref('cama_mastografias') }} m
|
||||
join {{ source('silver', 'carga') }} toma
|
||||
on toma.carga_id = m.toma_carga_id
|
||||
left join {{ source('silver', 'carga') }} reporte
|
||||
on reporte.carga_id = m.reporte_carga_id and m.reporte_id is not null
|
||||
left join {{ ref('cama_biopsias') }} b
|
||||
on b.toma_id = m.procedimiento_id and b.pac_id = m.pac_id
|
||||
left join {{ source('silver', 'carga') }} biopsia
|
||||
on biopsia.carga_id = b.reporte_carga_id
|
||||
@@ -0,0 +1,102 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cama_tomas_biopsia
|
||||
description: "Mastografías con su reporte y los reportes de biopsia que originaron, con cuándo se supo de cada uno."
|
||||
config:
|
||||
materialized: view
|
||||
|
||||
semantic_models:
|
||||
- name: cama_tomas_biopsia
|
||||
description: "Mammograms and the biopsy reports they led to: the episode a suspicious mammogram opens."
|
||||
model: ref('cama_tomas_biopsia')
|
||||
defaults:
|
||||
agg_time_dimension: fecha_toma
|
||||
entities:
|
||||
- name: episodio
|
||||
type: primary
|
||||
expr: "procedimiento_id || '-' || coalesce(fecha_reporte, '') || '-' || coalesce(biopsia_fecha_reporte, '')"
|
||||
- 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: fecha_reporte
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: reporte_conocido_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: biopsia_fecha_reporte
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: biopsia_conocida_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: birads
|
||||
type: categorical
|
||||
measures:
|
||||
- name: episodios
|
||||
description: "Distinct mammograms: an episode counts once, however many biopsies."
|
||||
agg: count_distinct
|
||||
expr: fuente_id
|
||||
|
||||
metrics:
|
||||
- name: cama_confirmacion_birads45_denominador
|
||||
label: "Mastografías de sospecha"
|
||||
type: simple
|
||||
type_params:
|
||||
measure: episodios
|
||||
filter: "{{ Dimension('episodio__birads') }} in :birads_sospecha"
|
||||
config:
|
||||
meta:
|
||||
poblaciones_fhir: [initial-population, denominator]
|
||||
# A BI-RADS reported after the cut-off doesn't exist yet.
|
||||
fechada_en: [fecha_reporte]
|
||||
conocida_en: [toma_conocida_en, reporte_conocido_en]
|
||||
- name: cama_confirmacion_birads45_numerador
|
||||
label: "De ellas, con biopsia reportada"
|
||||
type: simple
|
||||
type_params:
|
||||
measure: episodios
|
||||
filter: "{{ Dimension('episodio__birads') }} in :birads_sospecha"
|
||||
config:
|
||||
meta:
|
||||
poblaciones_fhir: [numerator]
|
||||
fechada_en: [fecha_reporte, biopsia_fecha_reporte]
|
||||
conocida_en: [toma_conocida_en, reporte_conocido_en, biopsia_conocida_en]
|
||||
- name: cama_confirmacion_birads45
|
||||
# dbt wants labels unique in the project; the title on screen is `meta.titulo`.
|
||||
label: "CaMa: tasa de confirmación histopatológica"
|
||||
description: >-
|
||||
De las mastografías del semestre con BI-RADS de sospecha, las que tienen una biopsia reportada originada por esa
|
||||
mastografía. A la fecha de corte: sin un plazo máximo, el valor puede subir mientras lleguen reportes. No dice si
|
||||
la biopsia confirmó cáncer.
|
||||
type: ratio
|
||||
type_params:
|
||||
numerator: cama_confirmacion_birads45_numerador
|
||||
denominator: cama_confirmacion_birads45_denominador
|
||||
config:
|
||||
meta:
|
||||
measure_url: cama/CAMA_CONFIRMACION_BIRADS45
|
||||
titulo: "Tasa de confirmación histopatológica"
|
||||
version: 0.2.0
|
||||
scoring: proportion
|
||||
basis: episodio
|
||||
grupo: principal
|
||||
contrato: C1
|
||||
improvement_notation: increase
|
||||
tipos_periodo: [semestre, mes]
|
||||
parametros:
|
||||
birads_sospecha: cama.birads_sospecha
|
||||
@@ -0,0 +1,73 @@
|
||||
-- One row per mammogram taken and each report that hangs from it: the event grain CaMa's mammography measures are
|
||||
-- asked over. No period and no cut-off here: they're the question's. When the sample and its report became known are
|
||||
-- the start of the loads that wrote them. `birads_gravedad` orders BI-RADS from least to most severe by
|
||||
-- `cama.birads_gravedad` (0 for one the catalog doesn't know). From the patient's timeline: the first note that
|
||||
-- resolves the mammogram (a `diagnostico` after it, within the horizon), with its days and when it was known, and
|
||||
-- whether a breast cancer note (`antecedente`) came before it. Days are differences of `dim_fecha.dia_num`.
|
||||
{% set r = var('cama') %}
|
||||
|
||||
with resuelve as (
|
||||
select m.procedimiento_id, min(l.fecha) as fecha_diagnostico
|
||||
from (select distinct procedimiento_id, pac_id, fecha_toma from {{ ref('cama_mastografias') }}) m
|
||||
join {{ ref('cama_linea_de_tiempo') }} l
|
||||
on l.pac_id = m.pac_id and l.tipo = 'diagnostico' and l.fecha > m.fecha_toma
|
||||
join {{ source('silver', 'dim_fecha') }} dl on dl.fecha = l.fecha
|
||||
join {{ source('silver', 'dim_fecha') }} dt on dt.fecha = m.fecha_toma
|
||||
where dl.dia_num - dt.dia_num < {{ r['horizonte_toma_diagnostico_dias'] }}
|
||||
group by m.procedimiento_id
|
||||
),
|
||||
|
||||
diagnostico as (
|
||||
select r.procedimiento_id, r.fecha_diagnostico, min(l.conocida_en) as diagnostico_conocido_en
|
||||
from resuelve r
|
||||
join (select distinct procedimiento_id, pac_id from {{ ref('cama_mastografias') }}) m
|
||||
on m.procedimiento_id = r.procedimiento_id
|
||||
join {{ ref('cama_linea_de_tiempo') }} l
|
||||
on l.pac_id = m.pac_id and l.tipo = 'diagnostico' and l.fecha = r.fecha_diagnostico
|
||||
group by r.procedimiento_id, r.fecha_diagnostico
|
||||
),
|
||||
|
||||
primer_antecedente as (
|
||||
select pac_id, min(fecha) as fecha
|
||||
from {{ ref('cama_linea_de_tiempo') }}
|
||||
where tipo = 'antecedente'
|
||||
group by pac_id
|
||||
)
|
||||
|
||||
select
|
||||
m.procedimiento_id,
|
||||
m.fuente_id,
|
||||
m.pac_id,
|
||||
m.fecha_toma,
|
||||
toma.inicio as toma_conocida_en,
|
||||
m.calidad_imagen,
|
||||
m.fecha_reporte,
|
||||
m.birads,
|
||||
case
|
||||
{%- for b in r['birads_gravedad'] %}
|
||||
when m.birads = '{{ b }}' then {{ loop.index }}
|
||||
{%- endfor %}
|
||||
else 0
|
||||
end as birads_gravedad,
|
||||
reporte.inicio as reporte_conocido_en,
|
||||
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,
|
||||
dia_diagnostico.dia_num - dia_toma.dia_num as dias_toma_diagnostico,
|
||||
case when antecedente.fecha < m.fecha_toma then 1 else 0 end as con_antecedente
|
||||
from {{ ref('cama_mastografias') }} m
|
||||
join {{ source('silver', 'carga') }} toma
|
||||
on toma.carga_id = m.toma_carga_id
|
||||
left join {{ source('silver', 'carga') }} reporte
|
||||
on reporte.carga_id = m.reporte_carga_id and m.reporte_id is not null
|
||||
left join {{ source('silver', 'dim_fecha') }} dia_toma
|
||||
on dia_toma.fecha = m.fecha_toma
|
||||
left join {{ source('silver', 'dim_fecha') }} dia_reporte
|
||||
on dia_reporte.fecha = m.fecha_reporte
|
||||
left join diagnostico dx
|
||||
on dx.procedimiento_id = m.procedimiento_id
|
||||
left join {{ source('silver', 'dim_fecha') }} dia_diagnostico
|
||||
on dia_diagnostico.fecha = dx.fecha_diagnostico
|
||||
left join primer_antecedente antecedente
|
||||
on antecedente.pac_id = m.pac_id
|
||||
@@ -0,0 +1,215 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cama_tomas_mastografia
|
||||
description: "Mastografías tomadas, una fila por toma y reporte, con cuándo se supo de cada uno."
|
||||
config:
|
||||
materialized: view
|
||||
|
||||
semantic_models:
|
||||
- name: cama_tomas_mastografia
|
||||
description: "Mammograms taken, with their reports: what CaMa's mammography measures count over."
|
||||
model: ref('cama_tomas_mastografia')
|
||||
defaults:
|
||||
agg_time_dimension: fecha_toma
|
||||
entities:
|
||||
- name: mastografia
|
||||
type: primary
|
||||
expr: "procedimiento_id || '-' || coalesce(fecha_reporte, '')"
|
||||
- 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: fecha_reporte
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: reporte_conocido_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: fecha_diagnostico
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: diagnostico_conocido_en
|
||||
type: time
|
||||
type_params:
|
||||
time_granularity: day
|
||||
- name: birads
|
||||
type: categorical
|
||||
- name: birads_gravedad
|
||||
type: categorical
|
||||
- name: calidad_imagen
|
||||
type: categorical
|
||||
- name: fuente_id
|
||||
type: categorical
|
||||
- name: toma_dia
|
||||
type: categorical
|
||||
- name: dias_toma_reporte
|
||||
type: categorical
|
||||
- name: dias_toma_diagnostico
|
||||
type: categorical
|
||||
- name: con_antecedente
|
||||
type: categorical
|
||||
measures:
|
||||
- name: mastografias
|
||||
description: "Distinct mammograms (the source's id): the unit of the exam-based measures."
|
||||
agg: count_distinct
|
||||
expr: fuente_id
|
||||
- name: pacientes_con_mastografia
|
||||
description: "Distinct patients: each counts once per period, however many mammograms."
|
||||
agg: count_distinct
|
||||
expr: pac_id
|
||||
|
||||
metrics:
|
||||
- name: cama_birads
|
||||
label: "Distribución de BI-RADS"
|
||||
description: >-
|
||||
Cuántas pacientes caen en cada categoría de BI-RADS en el semestre, cada una en la más grave de sus mastografías.
|
||||
«Sin dato»: ninguna de sus mastografías tiene reporte con BI-RADS.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: pacientes_con_mastografia
|
||||
config:
|
||||
meta: &birads_por_paciente
|
||||
measure_url: cama/CAMA_BIRADS
|
||||
version: 0.2.0
|
||||
scoring: composition
|
||||
basis: paciente
|
||||
grupo: TOTAL
|
||||
contrato: C2
|
||||
tipos_periodo: [semestre, mes]
|
||||
poblaciones_fhir: [measure-observation]
|
||||
conocida_en: [toma_conocida_en]
|
||||
# Each patient's most severe BI-RADS among her mammograms of the period reported by the cut-off; one without a
|
||||
# report doesn't count against one with it.
|
||||
categoria:
|
||||
valor: birads
|
||||
sin_dato: SIN_DATO
|
||||
elige: mas_grave
|
||||
valido: "{% raw %}{{ Dimension('mastografia__birads') }} is not null{% endraw %}"
|
||||
fechada_en: [fecha_reporte]
|
||||
conocida_en: [reporte_conocido_en]
|
||||
orden: [birads_gravedad, fuente_id]
|
||||
- name: cama_birads_456_paciente
|
||||
label: "Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6"
|
||||
description: >-
|
||||
Cuántas pacientes tienen como BI-RADS más grave del periodo un 4, 5 o 6, cada una en la más grave de sus
|
||||
mastografías.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: pacientes_con_mastografia
|
||||
config:
|
||||
meta:
|
||||
<<: *birads_por_paciente
|
||||
measure_url: cama/CAMA_BIRADS456_PACIENTE
|
||||
parametros:
|
||||
birads_4_a_6: cama.birads_4_a_6
|
||||
categoria:
|
||||
valor: birads
|
||||
sin_dato: SIN_DATO
|
||||
elige: mas_grave
|
||||
valido: "{% raw %}{{ Dimension('mastografia__birads') }} is not null{% endraw %}"
|
||||
fechada_en: [fecha_reporte]
|
||||
conocida_en: [reporte_conocido_en]
|
||||
orden: [birads_gravedad, fuente_id]
|
||||
# After choosing the most severe: a patient with B6 and B4 counts in B6.
|
||||
admite: "{% raw %}{{ Dimension('mastografia__birads') }} in :birads_4_a_6{% endraw %}"
|
||||
- name: cama_birads_456_mastografia
|
||||
label: "Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6"
|
||||
description: "Cuántas mastografías tomadas en el periodo tienen BI-RADS 4, 5 o 6, cada una con su categoría."
|
||||
type: simple
|
||||
type_params:
|
||||
measure: mastografias
|
||||
filter: "{{ Dimension('mastografia__birads') }} in :birads_4_a_6"
|
||||
config:
|
||||
meta:
|
||||
measure_url: cama/CAMA_BIRADS456_MASTOGRAFIA
|
||||
version: 0.2.0
|
||||
scoring: composition
|
||||
basis: examen
|
||||
grupo: TOTAL
|
||||
contrato: C2
|
||||
tipos_periodo: [semestre, mes]
|
||||
poblaciones_fhir: [measure-observation]
|
||||
conocida_en: [toma_conocida_en]
|
||||
parametros:
|
||||
birads_4_a_6: cama.birads_4_a_6
|
||||
categoria:
|
||||
valor: birads
|
||||
sin_dato: SIN_DATO
|
||||
elige: ultimo_valido
|
||||
valido: "{% raw %}{{ Dimension('mastografia__birads') }} is not null{% endraw %}"
|
||||
fechada_en: [fecha_reporte]
|
||||
conocida_en: [reporte_conocido_en]
|
||||
orden: [birads_gravedad]
|
||||
- name: cama_eu38a
|
||||
label: "Días de la toma de la mastografía a su resultado"
|
||||
description: >-
|
||||
Días naturales de la toma de cada mastografía del semestre a su resultado, a la fecha de corte. Las que aún no
|
||||
tienen resultado y siguen dentro del horizonte no se miden; las que lo pasaron sin resultado cuentan en los
|
||||
excluidos.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: mastografias
|
||||
config:
|
||||
meta:
|
||||
measure_url: cama/CAMA_EU38A
|
||||
version: 0.2.1
|
||||
scoring: continuous-variable
|
||||
basis: examen
|
||||
grupo: TOTAL
|
||||
contrato: C3r
|
||||
improvement_notation: decrease
|
||||
tipos_periodo: [semestre, mes]
|
||||
poblaciones_fhir: [initial-population]
|
||||
conocida_en: [toma_conocida_en]
|
||||
parametros:
|
||||
horizonte_dias: cama.horizontes.toma_reporte_dias
|
||||
observacion:
|
||||
valor: dias_toma_reporte
|
||||
fechada_en: [fecha_reporte]
|
||||
conocida_en: [reporte_conocido_en]
|
||||
horizonte:
|
||||
regla: horizonte_dias
|
||||
dia_inicio: toma_dia
|
||||
- name: cama_dias_toma_diagnostico
|
||||
label: "CaMa: tiempo de tamizaje a diagnóstico"
|
||||
description: >-
|
||||
Días naturales de la toma de cada mastografía del semestre a la primera nota médica posterior que la resuelve: un
|
||||
diagnóstico CIE-10 de la lista (normal, benigno, lesión o cáncer), escrito por una de las especialidades que
|
||||
diagnostican, dentro del horizonte y a la fecha de corte. Entran todas las mastografías, sean de tamizaje o no;
|
||||
se excluyen las de pacientes con un diagnóstico de cáncer de mama anterior a la toma.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: mastografias
|
||||
filter: "{{ Dimension('mastografia__con_antecedente') }} = 0"
|
||||
config:
|
||||
meta:
|
||||
measure_url: cama/CAMA_DIAS_TOMA_DIAGNOSTICO
|
||||
titulo: "Tiempo de tamizaje a diagnóstico"
|
||||
version: 0.2.2
|
||||
scoring: continuous-variable
|
||||
basis: examen
|
||||
grupo: TOTAL
|
||||
contrato: C3r
|
||||
improvement_notation: decrease
|
||||
tipos_periodo: [semestre, mes]
|
||||
poblaciones_fhir: [initial-population]
|
||||
conocida_en: [toma_conocida_en]
|
||||
observacion:
|
||||
valor: dias_toma_diagnostico
|
||||
fechada_en: [fecha_diagnostico]
|
||||
conocida_en: [diagnostico_conocido_en]
|
||||
horizonte:
|
||||
dias: "{{ var('cama')['horizonte_toma_diagnostico_dias'] }}"
|
||||
dia_inicio: toma_dia
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
One row per biopsy report with its grade, its order and the mammogram that led to it, if found:
|
||||
mammogram (toma) -> biopsy order -> biopsy report, by `padre_id`.
|
||||
*/
|
||||
|
||||
select
|
||||
r.procedimiento_id,
|
||||
r.fuente_tabla,
|
||||
r.fuente_id,
|
||||
r.pac_id,
|
||||
r.fecha as fecha_reporte,
|
||||
coalesce(o_gr.valor_id, o_gr.valor_fuente) as grado,
|
||||
orden.fecha as fecha_solicitud,
|
||||
t.procedimiento_id as toma_id,
|
||||
coalesce(o_gr.carga_id, r.carga_id) as reporte_carga_id
|
||||
from {{ source('silver', 'procedimiento') }} r
|
||||
left join {{ source('silver', 'observacion_clinica') }} o_gr
|
||||
on o_gr.procedimiento_id = r.procedimiento_id and o_gr.resultado_id = 'biopsia.grado'
|
||||
left join {{ source('silver', 'procedimiento') }} orden
|
||||
on orden.procedimiento_id = r.padre_id and orden.estudio_id = 'biopsia' and orden.clase = 'orden'
|
||||
left join {{ source('silver', 'procedimiento') }} t
|
||||
on t.procedimiento_id = orden.padre_id and t.estudio_id = 'mastografia' and t.clase = 'toma'
|
||||
where r.estudio_id = 'biopsia' and r.clase = 'reporte'
|
||||
@@ -0,0 +1,82 @@
|
||||
{# Each patient's stratifiers for the analysis, as timeline facts (`pac_id`, `tipo`, `fecha`, `conocida_en`): what a
|
||||
measure's `linea_de_tiempo_*` strata ask about. Derived from cama_linea_de_tiempo's lines read from reports, by the
|
||||
rules in `vars.cama.estratos`: the clinical stage's group and early or advanced stage (from a note), the surrogate
|
||||
molecular subtype (from one pathology report's receptors, HER2 and Ki-67 together) and the lesion's T (from a
|
||||
mammography report). A fact is dated and known as the lines it comes from. A view, like the timeline. #}
|
||||
{{ config(materialized = 'view') }}
|
||||
{%- set e = var('cama')['estratos'] -%}
|
||||
|
||||
with linea as (
|
||||
select pac_id, fecha, conocida_en, tipo, valor_codigo, valor_numerico, fuente_tabla, fuente_id
|
||||
from {{ ref('cama_linea_de_tiempo') }}
|
||||
),
|
||||
|
||||
estadio as (
|
||||
select
|
||||
pac_id, fecha, conocida_en,
|
||||
case valor_codigo
|
||||
{%- for codigo, grupo in e['estadios'].items() %}
|
||||
when '{{ codigo }}' then 'estadio_{{ grupo }}'
|
||||
{%- endfor %}
|
||||
end as estadio,
|
||||
case valor_codigo
|
||||
{%- for codigo, grupo in e['estadios'].items() %}
|
||||
when '{{ codigo }}' then '{{ 'etapa_temprana' if grupo in e['etapa_temprana'] else 'etapa_avanzada' }}'
|
||||
{%- endfor %}
|
||||
end as etapa
|
||||
from linea
|
||||
where tipo = 'estadio_clinico'
|
||||
),
|
||||
|
||||
reporte as (
|
||||
select
|
||||
pac_id, fecha, fuente_tabla, fuente_id,
|
||||
max(conocida_en) as conocida_en,
|
||||
max(case when tipo = 'receptor_estrogeno' then valor_codigo end) as re,
|
||||
max(case when tipo = 'receptor_progesterona' then valor_codigo end) as rp,
|
||||
max(case when tipo = 'receptor_progesterona_pct' then valor_numerico end) as rp_pct,
|
||||
max(case when tipo = 'her2' then valor_codigo end) as her2,
|
||||
max(case when tipo = 'ki67_pct' then valor_numerico end) as ki67
|
||||
from linea
|
||||
where tipo in ('receptor_estrogeno', 'receptor_progesterona', 'receptor_progesterona_pct', 'her2', 'ki67_pct')
|
||||
group by pac_id, fecha, fuente_tabla, fuente_id
|
||||
),
|
||||
|
||||
subtipo as (
|
||||
select
|
||||
pac_id, fecha, conocida_en,
|
||||
case
|
||||
when her2 in {{ sql_list(e['her2_positivo']) }} then 'subtipo_her2'
|
||||
when her2 not in {{ sql_list(e['her2_negativo']) }} or her2 is null then null
|
||||
when re = 'NEGATIVO' and rp = 'NEGATIVO' then 'subtipo_triple_negativo'
|
||||
when re = 'POSITIVO' or rp = 'POSITIVO' then
|
||||
case
|
||||
when ki67 is null then null
|
||||
when ki67 < {{ e['ki67_corte'] }} and rp = 'POSITIVO'
|
||||
and (rp_pct is null or rp_pct >= {{ e['rp_corte'] }}) then 'subtipo_luminal_a'
|
||||
else 'subtipo_luminal_b'
|
||||
end
|
||||
end as subtipo
|
||||
from reporte
|
||||
),
|
||||
|
||||
tamano as (
|
||||
select
|
||||
pac_id, fecha, conocida_en,
|
||||
case
|
||||
{%- for t in e['tamano_t'] if t['hasta_mm'] is not none %}
|
||||
when valor_numerico <= {{ t['hasta_mm'] }} then 'tamano_{{ t['t'] }}'
|
||||
{%- endfor %}
|
||||
else 'tamano_{{ (e['tamano_t'] | last)['t'] }}'
|
||||
end as t
|
||||
from linea
|
||||
where tipo = 'tamano_lesion_mm' and valor_numerico is not null
|
||||
)
|
||||
|
||||
select pac_id, estadio as tipo, fecha, conocida_en from estadio where estadio is not null
|
||||
union all
|
||||
select pac_id, etapa as tipo, fecha, conocida_en from estadio where etapa is not null
|
||||
union all
|
||||
select pac_id, subtipo as tipo, fecha, conocida_en from subtipo where subtipo is not null
|
||||
union all
|
||||
select pac_id, t as tipo, fecha, conocida_en from tamano
|
||||
@@ -1,4 +1,8 @@
|
||||
{# A view, not ephemeral like the other silver models: cohorts query it. Its sources: cama_linea_de_tiempo.yml. #}
|
||||
{# A view, not ephemeral like the other silver models: cohorts query it. Its sources: cama_linea_de_tiempo.yml;
|
||||
the procedures silver doesn't hold but its notes imply (diagnosis, antecedent): cama_procedimientos_inferidos. #}
|
||||
{{ 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('cama_procedimientos_inferidos') }}
|
||||
|
||||
@@ -17,5 +17,17 @@ models:
|
||||
- {estudio_id: "mastografia", clase: "toma", resultado_id: "mastografia.calidad_imagen", clase_de_linea: "procedimiento", tipo: "mastografia", codigo: "mastografia"}
|
||||
- {estudio_id: "mastografia", clase: "reporte", resultado_id: "mastografia.birads", clase_de_linea: "medicion", tipo: "birads", codigo: "birads"}
|
||||
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.grado", clase_de_linea: "medicion", tipo: "biopsia", codigo: "grado_histologico"}
|
||||
# Read from the reports' text (provisional catalog results): the stratifiers of the analysis.
|
||||
- {estudio_id: "mastografia", clase: "reporte", resultado_id: "mastografia.densidad", clase_de_linea: "medicion", tipo: "densidad_mamaria"}
|
||||
- {estudio_id: "mastografia", clase: "reporte", resultado_id: "mastografia.tamano_lesion_mm", clase_de_linea: "medicion", tipo: "tamano_lesion_mm", valor: "numerico"}
|
||||
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.tipo_histologico", clase_de_linea: "medicion", tipo: "tipo_histologico"}
|
||||
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.grado_nottingham", clase_de_linea: "medicion", tipo: "grado_nottingham"}
|
||||
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.receptor_estrogeno", clase_de_linea: "medicion", tipo: "receptor_estrogeno"}
|
||||
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.receptor_estrogeno_pct", clase_de_linea: "medicion", tipo: "receptor_estrogeno_pct", valor: "numerico"}
|
||||
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.receptor_progesterona", clase_de_linea: "medicion", tipo: "receptor_progesterona"}
|
||||
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.receptor_progesterona_pct", clase_de_linea: "medicion", tipo: "receptor_progesterona_pct", valor: "numerico"}
|
||||
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.her2", clase_de_linea: "medicion", tipo: "her2"}
|
||||
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.ki67_pct", clase_de_linea: "medicion", tipo: "ki67_pct", valor: "numerico"}
|
||||
- {estudio_id: "nota_medica", clase: "encuentro", resultado_id: "nota_medica.estadio_clinico", clase_de_linea: "medicion", tipo: "estadio_clinico"}
|
||||
- {estudio_id: null, clase: "orden", resultado_id: null, clase_de_linea: "orden", tipo: "orden", columna: "codigo_fuente"}
|
||||
- {estudio_id: "nota_medica", clase: "encuentro", resultado_id: "nota_medica.diagnostico", clase_de_linea: "diagnostico", tipo: "nota_medica"}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
One row per mammogram taken and each report that hangs from it (`padre_id`; one row with nulls when it has none),
|
||||
with its image quality and BI-RADS. A code the catalog doesn't know comes as it arrived
|
||||
(`coalesce(valor_id, valor_fuente)`), as the timeline reads it.
|
||||
*/
|
||||
|
||||
select
|
||||
t.procedimiento_id,
|
||||
t.fuente_tabla,
|
||||
t.fuente_id,
|
||||
t.pac_id,
|
||||
t.fecha as fecha_toma,
|
||||
coalesce(o_cal.valor_id, o_cal.valor_fuente) as calidad_imagen,
|
||||
r.procedimiento_id as reporte_id,
|
||||
r.fecha as fecha_reporte,
|
||||
coalesce(o_bi.valor_id, o_bi.valor_fuente) as birads,
|
||||
t.carga_id as toma_carga_id,
|
||||
coalesce(o_bi.carga_id, r.carga_id) as reporte_carga_id
|
||||
from {{ source('silver', 'procedimiento') }} t
|
||||
left join {{ source('silver', 'observacion_clinica') }} o_cal
|
||||
on o_cal.procedimiento_id = t.procedimiento_id and o_cal.resultado_id = 'mastografia.calidad_imagen'
|
||||
left join {{ source('silver', 'procedimiento') }} r
|
||||
on r.padre_id = t.procedimiento_id and r.estudio_id = 'mastografia' and r.clase = 'reporte'
|
||||
left join {{ source('silver', 'observacion_clinica') }} o_bi
|
||||
on o_bi.procedimiento_id = r.procedimiento_id and o_bi.resultado_id = 'mastografia.birads'
|
||||
where t.estudio_id = 'mastografia' and t.clase = 'toma'
|
||||
@@ -0,0 +1,46 @@
|
||||
{{ config(materialized = 'view') }}
|
||||
-- The procedures CaMa's notes imply, in the timeline's shape (`cama_linea_de_tiempo` adds them to each patient's
|
||||
-- timeline):
|
||||
-- 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
|
||||
{% set r = var('cama') %}
|
||||
|
||||
with nota as (
|
||||
select
|
||||
p.pac_id,
|
||||
p.fecha,
|
||||
p.fuente_tabla,
|
||||
p.fuente_id,
|
||||
c.inicio as conocida_en,
|
||||
max(case when o.resultado_id = 'nota_medica.diagnostico' then o.valor_texto end) as cie_codigo,
|
||||
max(case when o.resultado_id = 'nota_medica.especialidad' then o.valor_id end) as especialidad
|
||||
from {{ source('silver', 'procedimiento') }} p
|
||||
join {{ source('silver', 'carga') }} c on c.carga_id = p.carga_id
|
||||
left join {{ source('silver', 'observacion_clinica') }} o on o.procedimiento_id = p.procedimiento_id
|
||||
where p.estudio_id = 'nota_medica' and p.clase = 'encuentro'
|
||||
group by p.procedimiento_id, p.pac_id, p.fecha, p.fuente_tabla, p.fuente_id, c.inicio
|
||||
),
|
||||
|
||||
inferidos as (
|
||||
select pac_id, fecha, conocida_en, 'diagnostico' as tipo, fuente_tabla, fuente_id 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 from nota
|
||||
where cie_codigo in {{ sql_list(r['cie_antecedente']) }}
|
||||
)
|
||||
|
||||
select
|
||||
pac_id,
|
||||
fecha,
|
||||
conocida_en,
|
||||
{{ as_text("'procedimiento'") }} 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,
|
||||
fuente_tabla,
|
||||
fuente_id
|
||||
from inferidos
|
||||
where fecha is not null
|
||||
@@ -0,0 +1,2 @@
|
||||
-- The semantic layer's calendar: one row per day, from the `dim_fecha` each domain's cycle loads.
|
||||
select fecha as date_day from {{ source('silver', 'dim_fecha') }}
|
||||
@@ -0,0 +1,12 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: metricflow_time_spine
|
||||
description: "The calendar the semantic layer requires; dbt only validates against it."
|
||||
config:
|
||||
materialized: view
|
||||
time_spine:
|
||||
standard_granularity_column: date_day
|
||||
columns:
|
||||
- name: date_day
|
||||
granularity: day
|
||||
@@ -0,0 +1,21 @@
|
||||
-- One row per child of the cohort with a good EEG and knowledge version (`conocida_en`): the first good EEG known
|
||||
-- by then (the study's) and, from its
|
||||
-- metrics, whether it has any alteration and which. Later EEGs, good or bad, don't change them; each alteration
|
||||
-- counts once per child and a child can have several. What M30 counts, by the period of that EEG.
|
||||
|
||||
select
|
||||
h.pac_id,
|
||||
h.grupo_edad,
|
||||
h.eeg_estudio_id as procedimiento_id,
|
||||
h.fecha_eeg_estudio as fecha_eeg,
|
||||
h.conocida_en,
|
||||
max(case when m.estado in ('aumentado', 'disminuido') then 1 else 0 end) as con_alteracion,
|
||||
max(case when m.metrica = 'ritmo_posterior' and m.estado in ('aumentado', 'disminuido') then 1 else 0 end) as alt_ritmo_posterior,
|
||||
max(case when m.metrica = 'husos_sueno_n2' and m.estado in ('aumentado', 'disminuido') then 1 else 0 end) as alt_husos_sueno_n2,
|
||||
max(case when m.metrica = 'husos_sueno_n3' and m.estado in ('aumentado', 'disminuido') then 1 else 0 end) as alt_husos_sueno_n3,
|
||||
max(case when m.metrica = 'picos_paroxisticos' and m.estado in ('aumentado', 'disminuido') then 1 else 0 end) as alt_picos_paroxisticos,
|
||||
max(case when m.metrica = 'gradiente_anteroposterior' and m.estado in ('aumentado', 'disminuido') then 1 else 0 end) as alt_gradiente_anteroposterior
|
||||
from {{ ref('tea_hitos') }} h
|
||||
left join {{ ref('tea_eeg_metricas') }} m on m.procedimiento_id = h.eeg_estudio_id
|
||||
where h.eeg_estudio_id is not null
|
||||
group by h.pac_id, h.grupo_edad, h.eeg_estudio_id, h.fecha_eeg_estudio, h.conocida_en
|
||||
@@ -0,0 +1,89 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: tea_alteraciones
|
||||
description: "Niños de la cohorte con un EEG de buena calidad: el primero y las alteraciones que tiene."
|
||||
config:
|
||||
materialized: view
|
||||
|
||||
semantic_models:
|
||||
- name: tea_alteraciones
|
||||
description: "Each child's first good EEG and its alterations: what the EEG result measure counts over."
|
||||
model: ref('tea_alteraciones')
|
||||
defaults:
|
||||
agg_time_dimension: fecha_eeg
|
||||
entities:
|
||||
- name: eeg_estudio
|
||||
type: primary
|
||||
expr: pac_id
|
||||
dimensions:
|
||||
- {name: fecha_eeg, type: time, type_params: {time_granularity: day}}
|
||||
- {name: conocida_en, type: time, type_params: {time_granularity: day}}
|
||||
- {name: con_alteracion, type: categorical}
|
||||
- {name: alt_ritmo_posterior, type: categorical}
|
||||
- {name: alt_husos_sueno_n2, type: categorical}
|
||||
- {name: alt_husos_sueno_n3, type: categorical}
|
||||
- {name: alt_picos_paroxisticos, type: categorical}
|
||||
- {name: alt_gradiente_anteroposterior, type: categorical}
|
||||
- {name: grupo_edad, type: categorical}
|
||||
measures:
|
||||
- name: ninos_con_eeg
|
||||
description: "Distinct children whose first good EEG falls in the period."
|
||||
agg: count_distinct
|
||||
expr: pac_id
|
||||
|
||||
metrics:
|
||||
- name: tea_m30_con_eeg
|
||||
label: "TEA M30: niños con su primer EEG bueno"
|
||||
type: simple
|
||||
type_params:
|
||||
measure: ninos_con_eeg
|
||||
config:
|
||||
meta:
|
||||
poblaciones_fhir: [denominator]
|
||||
- name: tea_m30_con_alteracion
|
||||
label: "TEA M30: con alguna alteración"
|
||||
type: simple
|
||||
type_params:
|
||||
measure: ninos_con_eeg
|
||||
filter: "{{ Dimension('eeg_estudio__con_alteracion') }} = 1"
|
||||
config:
|
||||
meta:
|
||||
poblaciones_fhir: [numerator]
|
||||
- name: tea_resultado_eeg
|
||||
label: "Porcentaje de EEG normal y anormal"
|
||||
description: >-
|
||||
De los niños de la cohorte cuyo primer EEG de buena calidad cae en el periodo, cuántos tienen alguna alteración
|
||||
en él; un grupo por alteración, y un niño cuenta en cada una que tenga, así que no suman. Las alteraciones se
|
||||
miden contra los rangos de referencia por grupo de edad al EEG, pendientes de validar.
|
||||
type: ratio
|
||||
type_params:
|
||||
numerator: tea_m30_con_alteracion
|
||||
denominator: tea_m30_con_eeg
|
||||
config:
|
||||
meta:
|
||||
measure_url: tea/M30_resultado_eeg
|
||||
version_conocida: conocida_en
|
||||
version: 1.0.0
|
||||
basis: paciente
|
||||
grupo: TOTAL
|
||||
contrato: C1
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c1_barras_alteracion]
|
||||
requiere_validacion: alteraciones
|
||||
grupos:
|
||||
- grupo: ritmo_posterior
|
||||
etiqueta: "Ritmo posterior"
|
||||
filtro: "{% raw %}{{ Dimension('eeg_estudio__alt_ritmo_posterior') }} = 1{% endraw %}"
|
||||
- grupo: husos_sueno_n2
|
||||
etiqueta: "Husos de sueño N2"
|
||||
filtro: "{% raw %}{{ Dimension('eeg_estudio__alt_husos_sueno_n2') }} = 1{% endraw %}"
|
||||
- grupo: husos_sueno_n3
|
||||
etiqueta: "Husos de sueño N3"
|
||||
filtro: "{% raw %}{{ Dimension('eeg_estudio__alt_husos_sueno_n3') }} = 1{% endraw %}"
|
||||
- grupo: picos_paroxisticos
|
||||
etiqueta: "Picos paroxísticos"
|
||||
filtro: "{% raw %}{{ Dimension('eeg_estudio__alt_picos_paroxisticos') }} = 1{% endraw %}"
|
||||
- grupo: gradiente_anteroposterior
|
||||
etiqueta: "Gradiente anteroposterior"
|
||||
filtro: "{% raw %}{{ Dimension('eeg_estudio__alt_gradiente_anteroposterior') }} = 1{% endraw %}"
|
||||
@@ -0,0 +1,21 @@
|
||||
-- One row per child of the cohort and knowledge version (`conocida_en`): the date of each step and the days
|
||||
-- between them, from differences of `dim_fecha.dia_num`. What the day counts are asked over: the children in the
|
||||
-- screening during the period, whose interval ended by its end.
|
||||
|
||||
select
|
||||
h.pac_id,
|
||||
h.conocida_en,
|
||||
h.grupo_edad,
|
||||
h.fecha_mchat as ingreso,
|
||||
h.mchat_dia as ingreso_dia,
|
||||
h.fecha_eeg as salida,
|
||||
h.fecha_psicologia,
|
||||
h.fecha_neuropediatria,
|
||||
h.fecha_tea,
|
||||
dp.dia_num - h.mchat_dia as dias_mchat_ados2,
|
||||
dn.dia_num - dp.dia_num as dias_ados2_diagnostico,
|
||||
dt.dia_num - h.mchat_dia as dias_mchat_diagnostico
|
||||
from {{ ref('tea_hitos') }} h
|
||||
left join {{ source('silver', 'dim_fecha') }} dp on dp.fecha = h.fecha_psicologia
|
||||
left join {{ source('silver', 'dim_fecha') }} dn on dn.fecha = h.fecha_neuropediatria
|
||||
left join {{ source('silver', 'dim_fecha') }} dt on dt.fecha = h.fecha_tea
|
||||
@@ -0,0 +1,130 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: tea_casos
|
||||
description: "Cada niño de la cohorte con la fecha de cada paso y los días entre ellos."
|
||||
config:
|
||||
materialized: view
|
||||
|
||||
semantic_models:
|
||||
- name: tea_casos
|
||||
description: "The children of the cohort, with the days between their steps: what the day counts are asked over."
|
||||
model: ref('tea_casos')
|
||||
defaults:
|
||||
agg_time_dimension: ingreso
|
||||
entities:
|
||||
- name: caso
|
||||
type: primary
|
||||
expr: pac_id
|
||||
dimensions:
|
||||
- {name: ingreso, type: time, type_params: {time_granularity: day}}
|
||||
- {name: conocida_en, type: time, type_params: {time_granularity: day}}
|
||||
- {name: salida, type: time, type_params: {time_granularity: day}}
|
||||
- {name: fecha_psicologia, type: time, type_params: {time_granularity: day}}
|
||||
- {name: fecha_neuropediatria, type: time, type_params: {time_granularity: day}}
|
||||
- {name: fecha_tea, type: time, type_params: {time_granularity: day}}
|
||||
- {name: ingreso_dia, type: categorical}
|
||||
- {name: dias_mchat_ados2, type: categorical}
|
||||
- {name: dias_ados2_diagnostico, type: categorical}
|
||||
- {name: dias_mchat_diagnostico, type: categorical}
|
||||
- {name: grupo_edad, type: categorical}
|
||||
measures:
|
||||
- name: ninos
|
||||
description: "Distinct children of the cohort."
|
||||
agg: count_distinct
|
||||
expr: pac_id
|
||||
|
||||
metrics:
|
||||
- name: tea_dias_mchat_ados2
|
||||
label: "Días de M-CHAT a ADOS-2"
|
||||
description: >-
|
||||
Días naturales del primer M-CHAT a la nota de psicología con el ADOS-2, de los niños de la cohorte en el tamizaje durante el periodo cuyo intervalo terminó a más tardar al
|
||||
cierre. Los demás cuentan como sin evento.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: ninos
|
||||
config:
|
||||
meta:
|
||||
measure_url: tea/M26_dias_mchat_ados2
|
||||
version_conocida: conocida_en
|
||||
version: 1.0.0
|
||||
scoring: continuous-variable
|
||||
basis: paciente
|
||||
grupo: TOTAL
|
||||
contrato: C3r
|
||||
improvement_notation: decrease
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c3r_caja]
|
||||
poblaciones_fhir: [initial-population]
|
||||
poblacion:
|
||||
tipo: estado_al_fin_del_periodo
|
||||
ingreso: ingreso
|
||||
salida: salida
|
||||
observacion:
|
||||
valor: dias_mchat_ados2
|
||||
fechada_en: [fecha_psicologia]
|
||||
horizonte:
|
||||
dias: 0
|
||||
dia_inicio: ingreso_dia
|
||||
- name: tea_dias_ados2_diagnostico
|
||||
label: "Días de ADOS-2 a diagnóstico"
|
||||
description: >-
|
||||
Días naturales de la nota de psicología a la nota de neuropediatría, de los niños de la cohorte en el tamizaje durante el periodo cuyo intervalo terminó a más tardar al
|
||||
cierre. Los demás cuentan como sin evento.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: ninos
|
||||
config:
|
||||
meta:
|
||||
measure_url: tea/M27_dias_ados2_diagnostico
|
||||
version_conocida: conocida_en
|
||||
version: 1.0.0
|
||||
scoring: continuous-variable
|
||||
basis: paciente
|
||||
grupo: TOTAL
|
||||
contrato: C3r
|
||||
improvement_notation: decrease
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c3r_caja]
|
||||
poblaciones_fhir: [initial-population]
|
||||
poblacion:
|
||||
tipo: estado_al_fin_del_periodo
|
||||
ingreso: ingreso
|
||||
salida: salida
|
||||
observacion:
|
||||
valor: dias_ados2_diagnostico
|
||||
fechada_en: [fecha_neuropediatria]
|
||||
horizonte:
|
||||
dias: 0
|
||||
dia_inicio: ingreso_dia
|
||||
- name: tea_dias_mchat_diagnostico
|
||||
label: "Días de M-CHAT a diagnóstico positivo"
|
||||
description: >-
|
||||
Días naturales del primer M-CHAT a la nota de neuropediatría con F84.0, de los niños de la cohorte en el tamizaje durante el periodo cuyo intervalo terminó a más tardar al
|
||||
cierre. Los demás cuentan como sin evento.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: ninos
|
||||
config:
|
||||
meta:
|
||||
measure_url: tea/M25_dias_mchat_diagnostico
|
||||
version_conocida: conocida_en
|
||||
version: 1.0.0
|
||||
scoring: continuous-variable
|
||||
basis: paciente
|
||||
grupo: TOTAL
|
||||
contrato: C3r
|
||||
improvement_notation: decrease
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c3r_caja]
|
||||
poblaciones_fhir: [initial-population]
|
||||
poblacion:
|
||||
tipo: estado_al_fin_del_periodo
|
||||
ingreso: ingreso
|
||||
salida: salida
|
||||
observacion:
|
||||
valor: dias_mchat_diagnostico
|
||||
fechada_en: [fecha_tea]
|
||||
horizonte:
|
||||
dias: 0
|
||||
dia_inicio: ingreso_dia
|
||||
@@ -0,0 +1,25 @@
|
||||
-- One row per child of the cohort, knowledge version (`conocida_en`) and diagnostic result reached: in process from the M-CHAT, without TEA from a
|
||||
-- neuropediatrics note without F84.0, confirmed from one with it; ordered so a confirmation is final. A note
|
||||
-- counts from the psychology step on, and the child enters and leaves the screening as in `tea_pasos`. `fecha_eeg`: the step that
|
||||
-- completes the chain, for the confirmed with or without a good EEG.
|
||||
|
||||
{% set estados = [
|
||||
('EN_PROCESO', 1, 'fecha_mchat'),
|
||||
('SIN_TEA', 2, 'fecha_sin_tea'),
|
||||
('CONFIRMADO', 3, 'fecha_tea')] %}
|
||||
|
||||
{% for estado, orden, fecha in estados %}
|
||||
{{ 'union all' if not loop.first }}
|
||||
select
|
||||
h.pac_id,
|
||||
{{ as_text("'" ~ estado ~ "'") }} as estado,
|
||||
{{ orden }} as estado_orden,
|
||||
h.{{ fecha }} as fecha,
|
||||
h.conocida_en,
|
||||
h.grupo_edad,
|
||||
h.fecha_mchat as ingreso,
|
||||
h.fecha_eeg as salida,
|
||||
h.fecha_eeg
|
||||
from {{ ref('tea_hitos') }} h
|
||||
where h.{{ fecha }} is not null
|
||||
{%- endfor %}
|
||||
@@ -0,0 +1,208 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: tea_diagnosticos
|
||||
description: "Resultado diagnóstico de cada niño de la cohorte: en proceso, sin TEA o confirmado, con su fecha."
|
||||
config:
|
||||
materialized: view
|
||||
|
||||
semantic_models:
|
||||
- name: tea_diagnosticos
|
||||
description: "The diagnostic results each child of the cohort reached: what M23, M24, M21 and M22 count over."
|
||||
model: ref('tea_diagnosticos')
|
||||
defaults:
|
||||
agg_time_dimension: fecha
|
||||
entities:
|
||||
- name: resultado_diagnostico
|
||||
type: primary
|
||||
expr: "pac_id || '-' || estado"
|
||||
- name: paciente
|
||||
type: foreign
|
||||
expr: pac_id
|
||||
dimensions:
|
||||
- {name: fecha, type: time, type_params: {time_granularity: day}}
|
||||
- {name: conocida_en, type: time, type_params: {time_granularity: day}}
|
||||
- {name: ingreso, type: time, type_params: {time_granularity: day}}
|
||||
- {name: salida, type: time, type_params: {time_granularity: day}}
|
||||
- {name: fecha_eeg, type: time, type_params: {time_granularity: day}}
|
||||
- {name: estado, type: categorical}
|
||||
- {name: estado_orden, type: categorical}
|
||||
- {name: grupo_edad, type: categorical}
|
||||
measures:
|
||||
- name: ninos_por_diagnostico
|
||||
description: "Distinct children, each at its diagnostic result at the period's end."
|
||||
agg: count_distinct
|
||||
expr: pac_id
|
||||
|
||||
metrics:
|
||||
- name: tea_pacientes_evaluados
|
||||
label: "Pacientes evaluados por resultado diagnóstico"
|
||||
description: >-
|
||||
Niños de la cohorte en el tamizaje durante el periodo por su resultado al cierre: confirmados (una nota de
|
||||
neuropediatría con F84.0) y en proceso (sin nota de neuropediatría todavía). Una nota sin F84.0 no cuenta.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: ninos_por_diagnostico
|
||||
config:
|
||||
meta:
|
||||
measure_url: tea/M23_pacientes_evaluados
|
||||
version_conocida: conocida_en
|
||||
version: 1.0.0
|
||||
scoring: composition
|
||||
basis: paciente
|
||||
grupo: TOTAL
|
||||
contrato: C2
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c2_barras]
|
||||
poblaciones_fhir: [measure-observation]
|
||||
poblacion: &diagnostico_al_fin
|
||||
tipo: estado_al_fin_del_periodo
|
||||
ingreso: ingreso
|
||||
salida: salida
|
||||
orden: estado_orden
|
||||
categoria:
|
||||
valor: estado
|
||||
sin_dato: SIN_DATO
|
||||
valido: "{% raw %}{{ Dimension('resultado_diagnostico__estado') }} is not null{% endraw %}"
|
||||
orden: [estado_orden]
|
||||
admite: "{% raw %}{{ Dimension('resultado_diagnostico__estado') }} in ('CONFIRMADO', 'EN_PROCESO'){% endraw %}"
|
||||
etiquetas:
|
||||
CONFIRMADO: {etiqueta: "Diagnóstico confirmado", color: "#A8C243"}
|
||||
EN_PROCESO: {etiqueta: "En proceso", color: "#B8433A"}
|
||||
|
||||
# M24: confirmed out of confirmed plus in process, by age group.
|
||||
- name: tea_m24_confirmados
|
||||
label: "TEA M24: confirmados"
|
||||
type: simple
|
||||
type_params:
|
||||
measure: ninos_por_diagnostico
|
||||
filter: "{{ Dimension('resultado_diagnostico__estado') }} = 'CONFIRMADO'"
|
||||
config:
|
||||
meta:
|
||||
poblaciones_fhir: [numerator]
|
||||
- name: tea_m24_evaluados
|
||||
label: "TEA M24: confirmados y en proceso"
|
||||
type: simple
|
||||
type_params:
|
||||
measure: ninos_por_diagnostico
|
||||
filter: "{{ Dimension('resultado_diagnostico__estado') }} in ('CONFIRMADO', 'EN_PROCESO')"
|
||||
config:
|
||||
meta:
|
||||
poblaciones_fhir: [denominator]
|
||||
- name: tea_m24_sin_tea
|
||||
label: "TEA M24: notas sin F84.0"
|
||||
type: simple
|
||||
type_params:
|
||||
measure: ninos_por_diagnostico
|
||||
filter: "{{ Dimension('resultado_diagnostico__estado') }} = 'SIN_TEA'"
|
||||
config:
|
||||
meta:
|
||||
poblaciones_fhir: [denominator-exclusion]
|
||||
- name: tea_confirmacion_diagnostico
|
||||
label: "Porcentaje de confirmación diagnóstica"
|
||||
description: >-
|
||||
De los niños de la cohorte en el tamizaje durante el periodo, confirmados o en proceso al cierre, cuántos tienen
|
||||
el diagnóstico confirmado (F84.0 en la nota de neuropediatría). Por grupo de edad al primer M-CHAT. Los que
|
||||
tienen una nota sin F84.0 quedan fuera.
|
||||
type: ratio
|
||||
type_params:
|
||||
numerator: tea_m24_confirmados
|
||||
denominator: tea_m24_evaluados
|
||||
config:
|
||||
meta: &m24
|
||||
measure_url: tea/M24_confirmacion_diagnostico
|
||||
version_conocida: conocida_en
|
||||
version: 1.0.0
|
||||
basis: paciente
|
||||
grupo: TOTAL
|
||||
contrato: C1
|
||||
improvement_notation: increase
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c1_barras_apiladas_edad]
|
||||
exclusion: tea_m24_sin_tea
|
||||
poblacion: *diagnostico_al_fin
|
||||
estratos: &por_grupo_de_edad
|
||||
grupo_edad:
|
||||
tipo: columna
|
||||
columna: grupo_edad
|
||||
etiqueta: "Grupo de edad"
|
||||
valores:
|
||||
"16_23": "16 a 23 meses"
|
||||
"24_29": "24 a 29 meses"
|
||||
"30_36": "30 a 36 meses"
|
||||
sin_dato: "Sin dato"
|
||||
|
||||
# M21 and M22: of the confirmed, those with and without a good EEG by the period's end.
|
||||
- name: tea_m21_confirmados
|
||||
label: "TEA M21: confirmados"
|
||||
type: simple
|
||||
type_params:
|
||||
measure: ninos_por_diagnostico
|
||||
filter: "{{ Dimension('resultado_diagnostico__estado') }} = 'CONFIRMADO'"
|
||||
config:
|
||||
meta:
|
||||
poblaciones_fhir: [denominator]
|
||||
- name: tea_m21_con_eeg
|
||||
label: "TEA M21: confirmados con EEG"
|
||||
type: simple
|
||||
type_params:
|
||||
measure: ninos_por_diagnostico
|
||||
filter: "{{ Dimension('resultado_diagnostico__estado') }} = 'CONFIRMADO'"
|
||||
config:
|
||||
meta:
|
||||
poblaciones_fhir: [numerator]
|
||||
al_fin: [{fecha: fecha_eeg, alcanzada: true}]
|
||||
- name: tea_m22_sin_eeg
|
||||
label: "TEA M22: confirmados sin EEG"
|
||||
type: simple
|
||||
type_params:
|
||||
measure: ninos_por_diagnostico
|
||||
filter: "{{ Dimension('resultado_diagnostico__estado') }} = 'CONFIRMADO'"
|
||||
config:
|
||||
meta:
|
||||
poblaciones_fhir: [numerator]
|
||||
al_fin: [{fecha: fecha_eeg, alcanzada: false}]
|
||||
- name: tea_diagnosticados_con_eeg
|
||||
label: "Porcentaje de pacientes con diagnóstico de TEA con EEG"
|
||||
description: >-
|
||||
De los niños con diagnóstico confirmado al cierre del periodo, cuántos tienen ya un EEG de buena calidad. Por
|
||||
grupo de edad al primer M-CHAT.
|
||||
type: ratio
|
||||
type_params:
|
||||
numerator: tea_m21_con_eeg
|
||||
denominator: tea_m21_confirmados
|
||||
config:
|
||||
meta:
|
||||
measure_url: tea/M21_diagnosticados_con_eeg
|
||||
version_conocida: conocida_en
|
||||
version: 1.0.0
|
||||
basis: paciente
|
||||
grupo: TOTAL
|
||||
contrato: C1
|
||||
improvement_notation: increase
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c1_barras_edad]
|
||||
poblacion: *diagnostico_al_fin
|
||||
estratos: *por_grupo_de_edad
|
||||
- name: tea_diagnosticados_sin_eeg
|
||||
label: "Porcentaje de pacientes con diagnóstico de TEA sin EEG"
|
||||
description: >-
|
||||
De los niños con diagnóstico confirmado al cierre del periodo, cuántos no tienen todavía un EEG de buena
|
||||
calidad: el complemento de M21. Por grupo de edad al primer M-CHAT.
|
||||
type: ratio
|
||||
type_params:
|
||||
numerator: tea_m22_sin_eeg
|
||||
denominator: tea_m21_confirmados
|
||||
config:
|
||||
meta:
|
||||
measure_url: tea/M22_diagnosticados_sin_eeg
|
||||
version_conocida: conocida_en
|
||||
version: 1.0.0
|
||||
basis: paciente
|
||||
grupo: TOTAL
|
||||
contrato: C1
|
||||
improvement_notation: decrease
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c1_barras_edad]
|
||||
poblacion: *diagnostico_al_fin
|
||||
estratos: *por_grupo_de_edad
|
||||
@@ -0,0 +1,14 @@
|
||||
-- One row per EEG of a child of the cohort: its date, when it became known and its quality (good, bad, or not yet
|
||||
-- analysed). What M29 counts, by exam.
|
||||
|
||||
select
|
||||
e.procedimiento_id,
|
||||
e.fuente_id,
|
||||
e.pac_id,
|
||||
e.fecha_eeg,
|
||||
c.inicio as conocida_en,
|
||||
e.calidad
|
||||
from {{ ref('tea_eegs') }} e
|
||||
join {{ source('silver', 'carga') }} c on c.carga_id = e.carga_id
|
||||
join {{ ref('tea_cohorte') }} k on k.pac_id = e.pac_id
|
||||
where k.vigente = 1 and k.en_cohorte = 1 and e.fecha_eeg is not null
|
||||
@@ -0,0 +1,62 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: tea_eegs_periodo
|
||||
description: "EEG de los niños de la cohorte, con su calidad: buena, mala o sin analizar."
|
||||
config:
|
||||
materialized: view
|
||||
|
||||
semantic_models:
|
||||
- name: tea_eegs_periodo
|
||||
description: "The EEGs of the cohort's children: what the quality measure counts, by exam."
|
||||
model: ref('tea_eegs_periodo')
|
||||
defaults:
|
||||
agg_time_dimension: fecha_eeg
|
||||
entities:
|
||||
- name: eeg
|
||||
type: primary
|
||||
expr: fuente_id
|
||||
- name: paciente
|
||||
type: foreign
|
||||
expr: pac_id
|
||||
dimensions:
|
||||
- {name: fecha_eeg, type: time, type_params: {time_granularity: day}}
|
||||
- {name: conocida_en, type: time, type_params: {time_granularity: day}}
|
||||
- {name: calidad, type: categorical}
|
||||
- {name: fuente_id, type: categorical}
|
||||
measures:
|
||||
- name: eegs
|
||||
description: "Distinct EEGs (the source's id): the unit of the exam-based measure."
|
||||
agg: count_distinct
|
||||
expr: fuente_id
|
||||
|
||||
metrics:
|
||||
- name: tea_calidad_eeg
|
||||
label: "Calidad del EEG"
|
||||
description: >-
|
||||
EEG realizados en el periodo a niños de la cohorte, por su calidad: bueno si todos sus criterios de calidad
|
||||
están dentro de su umbral, malo si alguno no. Los que su análisis no ha calificado cuentan como sin analizar.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: eegs
|
||||
config:
|
||||
meta:
|
||||
measure_url: tea/M29_calidad_eeg
|
||||
version: 1.0.0
|
||||
scoring: composition
|
||||
basis: examen
|
||||
grupo: TOTAL
|
||||
contrato: C2
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c2_barras]
|
||||
poblaciones_fhir: [measure-observation]
|
||||
conocida_en: [conocida_en]
|
||||
categoria:
|
||||
valor: calidad
|
||||
sin_dato: SIN_DATO
|
||||
valido: "{% raw %}{{ Dimension('eeg__calidad') }} is not null{% endraw %}"
|
||||
orden: [fecha_eeg]
|
||||
etiquetas:
|
||||
BUENO: {etiqueta: "Bueno", color: "#A8C243"}
|
||||
MALO: {etiqueta: "Malo", color: "#B8433A"}
|
||||
SIN_ANALIZAR: {etiqueta: "Sin analizar", color: "#C9CDD2"}
|
||||
@@ -0,0 +1,27 @@
|
||||
-- One row per child of the cohort and step of the screening reached (M-CHAT, psychology, neuropediatrics, EEG),
|
||||
-- with its order and its date, in each knowledge version of the child (`conocida_en`: what was known of them from
|
||||
-- that load on): the grain the status measures are asked over. A child is in
|
||||
-- the screening from the M-CHAT (`ingreso`) and leaves after the period of the step that completes the chain, the
|
||||
-- first good EEG (`salida`). Without it they never leave. No period here: each child's stage at a period's end is
|
||||
-- the question's.
|
||||
|
||||
{% set pasos = [
|
||||
('SOLO_MCHAT', 1, 'fecha_mchat'),
|
||||
('PSICOLOGIA', 2, 'fecha_psicologia'),
|
||||
('NEUROPEDIATRIA', 3, 'fecha_neuropediatria'),
|
||||
('EEG', 4, 'fecha_eeg')] %}
|
||||
|
||||
{% for paso, orden, fecha in pasos %}
|
||||
{{ 'union all' if not loop.first }}
|
||||
select
|
||||
h.pac_id,
|
||||
{{ as_text("'" ~ paso ~ "'") }} as paso,
|
||||
{{ orden }} as paso_orden,
|
||||
h.{{ fecha }} as fecha,
|
||||
h.conocida_en,
|
||||
h.grupo_edad,
|
||||
h.fecha_mchat as ingreso,
|
||||
h.fecha_eeg as salida
|
||||
from {{ ref('tea_hitos') }} h
|
||||
where h.{{ fecha }} is not null
|
||||
{%- endfor %}
|
||||
@@ -0,0 +1,72 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: tea_pasos
|
||||
description: "Pasos del tamizaje que alcanzó cada niño de la cohorte, con su fecha y cuándo se supo."
|
||||
config:
|
||||
materialized: view
|
||||
|
||||
semantic_models:
|
||||
- name: tea_pasos
|
||||
description: "The steps of the screening each child of the cohort reached: what the stage measure counts over."
|
||||
model: ref('tea_pasos')
|
||||
defaults:
|
||||
agg_time_dimension: fecha
|
||||
entities:
|
||||
- name: paso_alcanzado
|
||||
type: primary
|
||||
expr: "pac_id || '-' || paso"
|
||||
- name: paciente
|
||||
type: foreign
|
||||
expr: pac_id
|
||||
dimensions:
|
||||
- {name: fecha, type: time, type_params: {time_granularity: day}}
|
||||
- {name: conocida_en, type: time, type_params: {time_granularity: day}}
|
||||
- {name: ingreso, type: time, type_params: {time_granularity: day}}
|
||||
- {name: salida, type: time, type_params: {time_granularity: day}}
|
||||
- {name: paso, type: categorical}
|
||||
- {name: paso_orden, type: categorical}
|
||||
- {name: grupo_edad, type: categorical}
|
||||
measures:
|
||||
- name: ninos_en_tamizaje
|
||||
description: "Distinct children: each counts once per period, at its stage at the period's end."
|
||||
agg: count_distinct
|
||||
expr: pac_id
|
||||
|
||||
metrics:
|
||||
- name: tea_casos_por_estado
|
||||
label: "Casos por estatus"
|
||||
description: >-
|
||||
Niños de la cohorte en el tamizaje durante el periodo (entraron con su primer M-CHAT a más tardar al cierre y no
|
||||
lo terminaron antes del inicio), por la etapa más avanzada que alcanzaron al cierre del periodo. Un niño sale
|
||||
después del periodo de su primer EEG de buena calidad.
|
||||
type: simple
|
||||
type_params:
|
||||
measure: ninos_en_tamizaje
|
||||
config:
|
||||
meta:
|
||||
measure_url: tea/M28_casos_por_estado
|
||||
version_conocida: conocida_en
|
||||
version: 1.0.0
|
||||
scoring: composition
|
||||
basis: paciente
|
||||
grupo: TOTAL
|
||||
contrato: C2
|
||||
tipos_periodo: [semestre, mes]
|
||||
figuras: [fig_c2_barras]
|
||||
poblaciones_fhir: [measure-observation]
|
||||
poblacion: &al_fin_del_periodo
|
||||
tipo: estado_al_fin_del_periodo
|
||||
ingreso: ingreso
|
||||
salida: salida
|
||||
orden: paso_orden
|
||||
categoria:
|
||||
valor: paso
|
||||
sin_dato: SIN_DATO
|
||||
valido: "{% raw %}{{ Dimension('paso_alcanzado__paso') }} is not null{% endraw %}"
|
||||
orden: [paso_orden]
|
||||
etiquetas:
|
||||
SOLO_MCHAT: {etiqueta: "Solo M-CHAT", color: "#B8433A"}
|
||||
PSICOLOGIA: {etiqueta: "Hasta evaluación psicológica", color: "#D0B778"}
|
||||
NEUROPEDIATRIA: {etiqueta: "Hasta evaluación neuropediátrica", color: "#7184A2"}
|
||||
EEG: {etiqueta: "Con EEG", color: "#A8C243"}
|
||||
@@ -0,0 +1,19 @@
|
||||
version: 2
|
||||
|
||||
# Views the WebApi reads, not measures: the cycle creates them with the event models (`lee_la_webapi`).
|
||||
models:
|
||||
- name: tea_seguimiento
|
||||
description: "Cada niño de la cohorte con las fechas de sus pasos, su M-CHAT y su ADOS-2: la lista de seguimiento."
|
||||
config: {materialized: view, meta: {lee_la_webapi: true}}
|
||||
- name: tea_paciente_ados2
|
||||
description: "Cada ADOS-2 con sus reactivos: el resumen del paciente."
|
||||
config: {materialized: view, meta: {lee_la_webapi: true}}
|
||||
- name: tea_paciente_eegs
|
||||
description: "Cada EEG con su calidad: el EEG del estudio a una fecha de corte."
|
||||
config: {materialized: view, meta: {lee_la_webapi: true}}
|
||||
- name: tea_paciente_eeg_metricas
|
||||
description: "Cada métrica de cada EEG contra su referencia."
|
||||
config: {materialized: view, meta: {lee_la_webapi: true}}
|
||||
- name: tea_paciente_eeg_electrodos
|
||||
description: "El puntaje z de cada métrica en cada electrodo."
|
||||
config: {materialized: view, meta: {lee_la_webapi: true}}
|
||||
@@ -0,0 +1,18 @@
|
||||
-- One row per ADOS-2 and scored item, with the ADOS-2's module, algorithm, CSS and classification on each: what the
|
||||
-- patient summary draws its domains and items from. An ADOS-2 without items gives one row without an item.
|
||||
|
||||
select
|
||||
a.procedimiento_id,
|
||||
a.pac_id,
|
||||
a.fecha_ados2,
|
||||
a.modulo,
|
||||
a.algoritmo,
|
||||
a.css,
|
||||
a.clasificacion,
|
||||
r.dominio,
|
||||
r.reactivo,
|
||||
r.etiqueta,
|
||||
r.puntaje,
|
||||
r.puntaje_algoritmo
|
||||
from {{ ref('tea_ados2') }} a
|
||||
left join {{ ref('tea_ados2_reactivos') }} r on r.procedimiento_id = a.procedimiento_id
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user