Compare commits

..

33 Commits

Author SHA1 Message Date
Angel Capetillo Zavala 360d2f7ab0 Merge feature/tea-eeg-analysis into dev (TEA age norm and ADOS-2 relation) 2026-11-21 12:23:54 -06:00
alberto cf1213e280 chore: WebApi and WebApp follow the TEA patient view's age norm and ADOS-2 relation 2026-11-21 11:18:08 -06:00
alberto 6d87071756 feat(tea): gold view of the ADOS-2 association model with the observed ADOS-2 outcome 2026-11-21 11:18:08 -06:00
alberto 4366a9cb67 feat(tea): the age at the EEG and each metric's baseline label through silver to the gold views 2026-11-21 11:18:08 -06:00
alberto fe767dae21 feat(tea): tables for the ADOS-2 association model and its per-patient values 2026-11-21 11:18:08 -06:00
Angel Capetillo Zavala 5fdb23a28e Pin WebApi and WebApp with CaCu's category groups and stratified views 2026-11-21 01:29:46 -06:00
Angel Capetillo Zavala ba99bbd311 feat(cacu): declare the category groups of EU7 and the confirmation, and the status captions 2026-11-21 01:29:39 -06:00
Angel Capetillo Zavala f7a5693455 feat(cacu): declare the figures and category captions of CaCu's measures 2026-11-21 01:29:39 -06:00
Angel Capetillo Zavala f01dcbbde5 Update WebApp with the TEA EEG follow-up fixes 2026-11-20 21:57:47 -06:00
AlbertoPMDM 26cf87a49a WebApp: one card per TEA EEG metric and the electrode map within its column 2026-11-20 19:56:08 -06:00
Angel Capetillo Zavala 4b363b9c97 Pin WebApp with the full domain names and CaMa's summary layout shared by CaCu and TEA 2026-11-20 19:54:46 -06:00
Angel Capetillo Zavala ab82a4c805 Pin WebApi with the tea library declared as its own dependency 2026-11-20 16:56:55 -06:00
Angel Capetillo Zavala 9a3f9f2813 Merge feature/tea-eeg-analysis into dev (TEA candidate composition) 2026-11-20 14:45:03 -06:00
angel 315ad3b269 Merge pull request 'Pin WebApp with the CaMa selective rollback' (#16) from chore/pin-webapp-cama-reversion into dev 2026-11-20 10:04:42 -06:00
Angel Capetillo Zavala 1bbf5d4877 Pin WebApp with the CaMa selective rollback 2026-11-20 10:02:50 -06:00
AlbertoPMDM 65e153aae8 Merge feature/tea-eeg-analysis into feature/tea-eeg-baseline-bundles 2026-11-20 09:40:20 -06:00
AlbertoPMDM ea316a6d59 models: TEA EEG baselines trained on a local cohort and moved as a bundle 2026-11-20 09:36:41 -06:00
AlbertoPMDM ea4b8ef235 models: loading a TEA EEG baseline leaves sys.path as it was 2026-11-20 09:33:21 -06:00
angel 13e8c4fd87 Merge pull request 'Pin WebApp with final CaMa demo changes' (#15) from feature/cama-clasificacion-histologica-webapp-pin into dev 2026-11-20 00:53:52 -06:00
Angel Capetillo Zavala 70f10e57d1 Pin WebApp with final CaMa demo changes 2026-11-20 00:52:04 -06:00
AlbertoPMDM 752495bbc8 models: TEA EEG baselines keep their artifacts under MLFLOW_ARTIFACT_ROOT 2026-11-19 23:17:42 -06:00
AlbertoPMDM 59de353672 WebApi: lock the tea library at 0.2.0 2026-11-19 20:34:09 -06:00
angel ef0cdff393 Merge pull request 'Pin WebApp with the CaMa BI-RADS and histopathology updates' (#14) from feature/cama-histopathology-webapp-pin into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/14
2026-11-19 19:48:36 -06:00
Angel Capetillo Zavala 746ad93c4e Pin WebApp with the CaMa BI-RADS and histopathology updates 2026-11-19 19:45:33 -06:00
AlbertoPMDM a67eaa0646 models: the TEA EEG analysis takes the age from the EDF header 2026-11-19 19:20:29 -06:00
angel 1a8bad2815 Merge pull request 'Pin WebApp with the CaMa diagnosis-to-treatment card' (#13) from feature/cama-diagnosis-treatment-webapp-pin into dev 2026-11-19 17:52:06 -06:00
Angel Capetillo Zavala 8e43dccfe0 Pin WebApp with the CaMa diagnosis-to-treatment card 2026-11-19 17:50:26 -06:00
Angel Capetillo Zavala b8f58585ad Update WebApp pin for CaMa BI-RADS charts 2026-11-19 16:07:01 -06:00
AlbertoPMDM 2144d60d06 feat(tea): tables and dbt models for the EEG analysis's output; submodules on the TEA EEG analysis 2026-11-19 15:43:27 -06:00
Angel Capetillo Zavala 6bd3f40a6c Pin WebApp with visual login test fixes 2026-11-19 11:44:47 -06:00
Erick ivan 87cfae3969 chore(submodules): bump WebApi and WebApp with the front-only login
WebApi drops the session login and stays open for the data service; WebApp keeps the login and the per-account domains in the browser. .env.example no longer documents the session variables.
2026-11-19 10:32:44 -06:00
Erick ivan 47046eaea7 chore(submodules): bump WebApi and WebApp with the session login
WebApi brings /auth and the per-domain scope; WebApp brings the sign-in screen, the route guard and the domain filtering in the import workspace and governance. .env.example documents WEBAPI_USUARIOS and the session key.
2026-11-19 09:37:30 -06:00
angel b81c626013 Merge pull request 'chore(submodules): update WebApp with the CI spec fixes' (#12) from fix/ci-spec-contracts into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/12
2026-11-19 00:11:39 -06:00
35 changed files with 1159 additions and 179 deletions
+330 -25
View File
@@ -196,13 +196,40 @@ etiqueta = "Diagnóstico"
tipo_valor = "externo"
sistema = "CIE-10"
# The EEG: what its analysis writes. On the recording (`toma`), the sleep, channels, duration, the five quality
# criteria and each metric's measured value; on each electrode (`parte`, `codigo_fuente` the electrode), the metric's
# z-score there, under the same result.
# The EEG: what its analysis (the `tea` library) writes. On the recording (`toma`): the verdict, triage level, clean
# fraction, sleep, channels, duration and line noise; each study-wide quality check (`calidad_<check>`, with
# `_anormal`, `_decisivo` and its limit, `_bajo` or `_alto`); and each metric's value with, against its age baseline, its z
# (`_z`), -1/0/+1 (`_fuera`), the curve's p5, median and p95 there and the registered label of the baseline that curve
# belongs to (`_modelo`). On each bad channel (`parte`, `codigo_fuente` the electrode): the check that flagged it, with
# the library's reason. On each electrode of a metric (`parte`, `codigo_fuente` the electrode): the metric's value and z
# there, under the same results.
[eeg]
etiqueta = "Electroencefalograma"
codigos_hospital = ["EEG"]
[eeg.resultados.valido]
etiqueta = "EEG válido para el estudio"
tipo_valor = "booleano"
[eeg.resultados.nivel]
etiqueta = "Nivel de triaje"
tipo_valor = "texto"
[eeg.resultados.fraccion_limpia]
etiqueta = "Fracción del registro limpia"
tipo_valor = "numero"
unidad = "fracción"
[eeg.resultados.canales_malos]
etiqueta = "Canales malos"
tipo_valor = "numero"
unidad = "canales"
[eeg.resultados.edad_meses]
etiqueta = "Edad al estudio"
tipo_valor = "numero"
unidad = "meses"
[eeg.resultados.con_sueno]
etiqueta = "Registro con sueño"
tipo_valor = "booleano"
@@ -217,55 +244,333 @@ etiqueta = "Duración del registro"
tipo_valor = "numero"
unidad = "min"
[eeg.resultados.calidad_amplitud]
etiqueta = "Canales con amplitud extrema"
tipo_valor = "numero"
unidad = "canales"
[eeg.resultados.calidad_alta_frecuencia]
etiqueta = "Ruido de alta frecuencia"
tipo_valor = "numero"
unidad = "canales"
[eeg.resultados.calidad_correlacion]
etiqueta = "Baja correlación entre canales"
tipo_valor = "numero"
unidad = "canales"
[eeg.resultados.calidad_sin_senal]
etiqueta = "Canales planos o sin señal"
tipo_valor = "numero"
unidad = "canales"
[eeg.resultados.calidad_linea]
[eeg.resultados.ruido_linea]
etiqueta = "Ruido de la línea eléctrica"
tipo_valor = "numero"
unidad = "dB"
[eeg.resultados.calidad_clean_windows]
etiqueta = "Ventanas limpias"
tipo_valor = "numero"
unidad = "%"
[eeg.resultados.calidad_clean_windows_anormal]
etiqueta = "Ventanas limpias: fuera de rango"
tipo_valor = "booleano"
[eeg.resultados.calidad_clean_windows_decisivo]
etiqueta = "Ventanas limpias: basta para invalidar el EEG"
tipo_valor = "booleano"
[eeg.resultados.calidad_clean_windows_bajo]
etiqueta = "Ventanas limpias: límite inferior"
tipo_valor = "numero"
unidad = "%"
[eeg.resultados.calidad_internal_coverage]
etiqueta = "Cobertura interna"
tipo_valor = "numero"
unidad = "fracción"
[eeg.resultados.calidad_internal_coverage_anormal]
etiqueta = "Cobertura interna: fuera de rango"
tipo_valor = "booleano"
[eeg.resultados.calidad_internal_coverage_decisivo]
etiqueta = "Cobertura interna: basta para invalidar el EEG"
tipo_valor = "booleano"
[eeg.resultados.calidad_internal_coverage_bajo]
etiqueta = "Cobertura interna: límite inferior"
tipo_valor = "numero"
unidad = "fracción"
[eeg.resultados.calidad_bad_scalp_triage]
etiqueta = "Electrodos del cuero cabelludo inservibles"
tipo_valor = "numero"
unidad = "electrodos"
[eeg.resultados.calidad_bad_scalp_triage_anormal]
etiqueta = "Electrodos del cuero cabelludo inservibles: fuera de rango"
tipo_valor = "booleano"
[eeg.resultados.calidad_bad_scalp_triage_decisivo]
etiqueta = "Electrodos del cuero cabelludo inservibles: basta para invalidar el EEG"
tipo_valor = "booleano"
[eeg.resultados.calidad_bad_scalp_triage_alto]
etiqueta = "Electrodos del cuero cabelludo inservibles: límite superior"
tipo_valor = "numero"
unidad = "electrodos"
[eeg.resultados.calidad_usable_scalp]
etiqueta = "Electrodos del cuero cabelludo útiles"
tipo_valor = "numero"
unidad = "electrodos"
[eeg.resultados.calidad_usable_scalp_anormal]
etiqueta = "Electrodos del cuero cabelludo útiles: fuera de rango"
tipo_valor = "booleano"
[eeg.resultados.calidad_usable_scalp_decisivo]
etiqueta = "Electrodos del cuero cabelludo útiles: basta para invalidar el EEG"
tipo_valor = "booleano"
[eeg.resultados.calidad_usable_scalp_bajo]
etiqueta = "Electrodos del cuero cabelludo útiles: límite inferior"
tipo_valor = "numero"
unidad = "electrodos"
[eeg.resultados.calidad_triage_level]
etiqueta = "Nivel de triaje"
tipo_valor = "texto"
[eeg.resultados.calidad_triage_level_anormal]
etiqueta = "Nivel de triaje: fuera de rango"
tipo_valor = "booleano"
[eeg.resultados.calidad_triage_level_decisivo]
etiqueta = "Nivel de triaje: basta para invalidar el EEG"
tipo_valor = "booleano"
[eeg.resultados.calidad_line_noise]
etiqueta = "Ruido de la línea eléctrica"
tipo_valor = "numero"
unidad = "dB"
[eeg.resultados.calidad_line_noise_anormal]
etiqueta = "Ruido de la línea eléctrica: fuera de rango"
tipo_valor = "booleano"
[eeg.resultados.calidad_line_noise_decisivo]
etiqueta = "Ruido de la línea eléctrica: basta para invalidar el EEG"
tipo_valor = "booleano"
[eeg.resultados.calidad_line_noise_alto]
etiqueta = "Ruido de la línea eléctrica: límite superior"
tipo_valor = "numero"
unidad = "dB"
[eeg.resultados.calidad_file]
etiqueta = "Archivo EDF"
tipo_valor = "texto"
[eeg.resultados.calidad_file_anormal]
etiqueta = "Archivo EDF: fuera de rango"
tipo_valor = "booleano"
[eeg.resultados.calidad_file_decisivo]
etiqueta = "Archivo EDF: basta para invalidar el EEG"
tipo_valor = "booleano"
[eeg.resultados.calidad_dead_channel]
etiqueta = "Canal muerto"
tipo_valor = "texto"
[eeg.resultados.calidad_frozen]
etiqueta = "Señal congelada"
tipo_valor = "texto"
[eeg.resultados.calidad_saturated]
etiqueta = "Señal saturada"
tipo_valor = "texto"
[eeg.resultados.calidad_inf_values]
etiqueta = "Valores infinitos"
tipo_valor = "texto"
[eeg.resultados.calidad_own_gaps]
etiqueta = "Huecos propios"
tipo_valor = "texto"
[eeg.resultados.calidad_bridge]
etiqueta = "Puente con otro electrodo"
tipo_valor = "texto"
[eeg.resultados.calidad_amplitude]
etiqueta = "Amplitud anómala frente al cuero cabelludo"
tipo_valor = "texto"
[eeg.resultados.calidad_aux_amplitude]
etiqueta = "Amplitud fuera de rango (canal auxiliar)"
tipo_valor = "texto"
[eeg.resultados.calidad_does_not_correlate]
etiqueta = "Sin correlación con sus vecinos"
tipo_valor = "texto"
[eeg.resultados.calidad_intermittent_contact]
etiqueta = "Contacto intermitente"
tipo_valor = "texto"
[eeg.resultados.calidad_intermittent_bursts]
etiqueta = "Contacto intermitente por ráfagas"
tipo_valor = "texto"
[eeg.resultados.ritmo_posterior]
etiqueta = "Ritmo posterior"
tipo_valor = "numero"
unidad = "Hz"
[eeg.resultados.ritmo_posterior_z]
etiqueta = "Ritmo posterior: puntaje z"
tipo_valor = "numero"
unidad = "z"
[eeg.resultados.ritmo_posterior_fuera]
etiqueta = "Ritmo posterior: fuera de la referencia (-1, 0, +1)"
tipo_valor = "numero"
[eeg.resultados.ritmo_posterior_p5]
etiqueta = "Ritmo posterior: percentil 5 de la referencia"
tipo_valor = "numero"
unidad = "Hz"
[eeg.resultados.ritmo_posterior_mediana]
etiqueta = "Ritmo posterior: mediana de la referencia"
tipo_valor = "numero"
unidad = "Hz"
[eeg.resultados.ritmo_posterior_p95]
etiqueta = "Ritmo posterior: percentil 95 de la referencia"
tipo_valor = "numero"
unidad = "Hz"
[eeg.resultados.ritmo_posterior_modelo]
etiqueta = "Ritmo posterior: modelo de la referencia"
tipo_valor = "texto"
[eeg.resultados.husos_sueno_n2]
etiqueta = "Husos de sueño N2"
tipo_valor = "numero"
unidad = "husos/min"
[eeg.resultados.husos_sueno_n2_z]
etiqueta = "Husos de sueño N2: puntaje z"
tipo_valor = "numero"
unidad = "z"
[eeg.resultados.husos_sueno_n2_fuera]
etiqueta = "Husos de sueño N2: fuera de la referencia (-1, 0, +1)"
tipo_valor = "numero"
[eeg.resultados.husos_sueno_n2_p5]
etiqueta = "Husos de sueño N2: percentil 5 de la referencia"
tipo_valor = "numero"
unidad = "husos/min"
[eeg.resultados.husos_sueno_n2_mediana]
etiqueta = "Husos de sueño N2: mediana de la referencia"
tipo_valor = "numero"
unidad = "husos/min"
[eeg.resultados.husos_sueno_n2_p95]
etiqueta = "Husos de sueño N2: percentil 95 de la referencia"
tipo_valor = "numero"
unidad = "husos/min"
[eeg.resultados.husos_sueno_n2_modelo]
etiqueta = "Husos de sueño N2: modelo de la referencia"
tipo_valor = "texto"
[eeg.resultados.husos_sueno_n3]
etiqueta = "Husos de sueño N3"
tipo_valor = "numero"
unidad = "husos/min"
[eeg.resultados.husos_sueno_n3_z]
etiqueta = "Husos de sueño N3: puntaje z"
tipo_valor = "numero"
unidad = "z"
[eeg.resultados.husos_sueno_n3_fuera]
etiqueta = "Husos de sueño N3: fuera de la referencia (-1, 0, +1)"
tipo_valor = "numero"
[eeg.resultados.husos_sueno_n3_p5]
etiqueta = "Husos de sueño N3: percentil 5 de la referencia"
tipo_valor = "numero"
unidad = "husos/min"
[eeg.resultados.husos_sueno_n3_mediana]
etiqueta = "Husos de sueño N3: mediana de la referencia"
tipo_valor = "numero"
unidad = "husos/min"
[eeg.resultados.husos_sueno_n3_p95]
etiqueta = "Husos de sueño N3: percentil 95 de la referencia"
tipo_valor = "numero"
unidad = "husos/min"
[eeg.resultados.husos_sueno_n3_modelo]
etiqueta = "Husos de sueño N3: modelo de la referencia"
tipo_valor = "texto"
[eeg.resultados.picos_paroxisticos]
etiqueta = "Picos paroxísticos"
tipo_valor = "numero"
unidad = "picos/min"
[eeg.resultados.picos_paroxisticos_z]
etiqueta = "Picos paroxísticos: puntaje z"
tipo_valor = "numero"
unidad = "z"
[eeg.resultados.picos_paroxisticos_fuera]
etiqueta = "Picos paroxísticos: fuera de la referencia (-1, 0, +1)"
tipo_valor = "numero"
[eeg.resultados.picos_paroxisticos_p5]
etiqueta = "Picos paroxísticos: percentil 5 de la referencia"
tipo_valor = "numero"
unidad = "picos/min"
[eeg.resultados.picos_paroxisticos_mediana]
etiqueta = "Picos paroxísticos: mediana de la referencia"
tipo_valor = "numero"
unidad = "picos/min"
[eeg.resultados.picos_paroxisticos_p95]
etiqueta = "Picos paroxísticos: percentil 95 de la referencia"
tipo_valor = "numero"
unidad = "picos/min"
[eeg.resultados.picos_paroxisticos_modelo]
etiqueta = "Picos paroxísticos: modelo de la referencia"
tipo_valor = "texto"
[eeg.resultados.gradiente_anteroposterior]
etiqueta = "Gradiente anteroposterior"
tipo_valor = "numero"
unidad = "razón posterior/anterior"
unidad = "pendiente"
[eeg.resultados.gradiente_anteroposterior_z]
etiqueta = "Gradiente anteroposterior: puntaje z"
tipo_valor = "numero"
unidad = "z"
[eeg.resultados.gradiente_anteroposterior_fuera]
etiqueta = "Gradiente anteroposterior: fuera de la referencia (-1, 0, +1)"
tipo_valor = "numero"
[eeg.resultados.gradiente_anteroposterior_p5]
etiqueta = "Gradiente anteroposterior: percentil 5 de la referencia"
tipo_valor = "numero"
unidad = "pendiente"
[eeg.resultados.gradiente_anteroposterior_mediana]
etiqueta = "Gradiente anteroposterior: mediana de la referencia"
tipo_valor = "numero"
unidad = "pendiente"
[eeg.resultados.gradiente_anteroposterior_p95]
etiqueta = "Gradiente anteroposterior: percentil 95 de la referencia"
tipo_valor = "numero"
unidad = "pendiente"
[eeg.resultados.gradiente_anteroposterior_modelo]
etiqueta = "Gradiente anteroposterior: modelo de la referencia"
tipo_valor = "texto"
# An order (procedure of class `orden`): its `estudio_id` is the study it asks for, from `codigos_hospital`.
[orden]
+28
View File
@@ -54,6 +54,34 @@ class MetricaEeg(str, Enum):
GRADIENTE_ANTEROPOSTERIOR = "GRADIENTE_ANTEROPOSTERIOR"
class NivelRelacionAdos2(str, Enum):
"""rel_nivel and rel_tipo in table relacion_ados2: what the model relates, an ADOS-2 item or a domain."""
ITEM = "item"
DOMINIO = "dominio"
class CriterioEeg(str, Enum):
"""cri_codigo in table eeg_criterio: the EEG analysis's check codes, channel reasons without their numbers."""
ARCHIVO = "file"
VENTANAS_LIMPIAS = "clean-windows"
COBERTURA_INTERNA = "internal-coverage"
CUERO_CABELLUDO_MALO = "bad-scalp-triage"
CUERO_CABELLUDO_UTIL = "usable-scalp"
NIVEL_TRIAJE = "triage-level"
RUIDO_LINEA = "line-noise"
CANAL_MUERTO = "dead-channel"
CONGELADO = "frozen"
SATURADO = "saturated"
VALORES_INF = "inf-values"
HUECOS_PROPIOS = "own-gaps"
PUENTE = "bridge"
AMPLITUD = "amplitude"
AMPLITUD_AUXILIAR = "aux-amplitude"
SIN_CORRELACION = "does-not-correlate"
CONTACTO_INTERMITENTE = "intermittent-contact"
CONTACTO_POR_RAFAGAS = "intermittent-bursts"
# The electrodes of the 10-20 system an electrode value can name (mel_electrodo).
ELECTRODOS_10_20 = (
"Fp1", "Fp2", "F7", "F3", "Fz", "F4", "F8", "T3", "C3", "Cz", "C4", "T4",
+86 -8
View File
@@ -1,14 +1,15 @@
"""TEA staging tables (data dictionary: spec/tablas_TEA.md).
One table per kind of study: the M-CHAT, the ADOS-2, the neuropediatrics note and the EEG, with the patients and
the orders. The EEG's quality criteria, channels, duration, sleep, metrics and electrode values are written by the
EEG analysis from the stored EDF.
the orders. The EEG's verdict, quality checks, channels, duration, sleep, metrics and electrode values are written
by the EEG analysis (the `tea` library) from the stored EDF. The ADOS-2 association model's cohort odds ratios and
per-patient z and probability land in relacion_ados2 and relacion_ados2_paciente.
Permissive storage: every domain field is optional so a load never rejects a row; booleans are INTEGER and enums
TEXT. Coercion and validation happen in the import schemas (WebApi/webapi/imports/schemas/tea).
"""
import uuid
from datetime import date
from datetime import date, datetime
from typing import Optional
import sqlalchemy as sa
@@ -49,6 +50,10 @@ def _date() -> Field:
return Field(default=None, sa_column=sa.Column(sa.Date))
def _datetime() -> Field:
return Field(default=None, sa_column=sa.Column(sa.DateTime))
class Pacientes(TeaModel, table=True):
__tablename__ = "pacientes"
@@ -152,13 +157,37 @@ class Eeg(TeaModel, table=True):
eeg_con_sueno: Optional[int] = _int()
eeg_canales: Optional[int] = _int()
eeg_duracion_min: Optional[float] = _float()
# Quality criteria: channels flagged by each one, and the line noise. An EEG is bad when any criterion is.
eeg_canales_amplitud: Optional[int] = _int()
eeg_canales_alta_frecuencia: Optional[int] = _int()
eeg_canales_correlacion: Optional[int] = _int()
eeg_canales_sin_senal: Optional[int] = _int()
eeg_ruido_linea_db: Optional[float] = _float()
eeg_estudio: Optional[bytes] = Field(default=None, sa_column=sa.Column(FileBlob)) # the EDF
# The analysis's verdict: 1 valid, 0 not valid, null not analysed yet. Its checks are rows of eeg_criterio.
eeg_valido: Optional[int] = _int()
eeg_nivel: Optional[str] = _text() # triage level: completo, sin_referencia_auricular, parcial, no_analizable
eeg_fraccion_limpia: Optional[float] = _float()
eeg_canales_malos: Optional[int] = _int()
eeg_edad_meses: Optional[float] = _float() # the age the analysis compared the metrics at
# What produced the analysis, so a new plan or module version analyses the EEG again.
eeg_plan_hash: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(16)))
eeg_versiones: Optional[str] = _text()
eeg_analizado_en: Optional[datetime] = _datetime()
eeg_error: Optional[str] = _text()
class EegCriterio(TeaModel, table=True):
"""One quality check the EEG analysis evaluated on an EEG: a study rule, or a bad channel with its electrode."""
__tablename__ = "eeg_criterio"
cri_id: Optional[str] = _id()
cri_eeg_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(36), index=True))
cri_codigo: Optional[str] = _text() # CriterioEeg
cri_electrodo: Optional[str] = _text()
cri_valor: Optional[float] = _float()
cri_valor_texto: Optional[str] = _text()
cri_unidad: Optional[str] = _text()
cri_bajo: Optional[float] = _float() # out of range below this
cri_alto: Optional[float] = _float() # out of range above this
cri_decisivo: Optional[int] = _int() # this check alone can make the EEG not valid
cri_anormal: Optional[int] = _int()
class EegMetrica(TeaModel, table=True):
@@ -170,6 +199,13 @@ class EegMetrica(TeaModel, table=True):
met_eeg_id: Optional[str] = _text()
met_codigo: Optional[str] = _text() # MetricaEeg
met_valor: Optional[float] = _float()
# Against the age baseline at eeg_edad_meses: z, -1/0/+1 below p5 / within / above p95, and the curve there.
met_z: Optional[float] = _float()
met_fuera: Optional[int] = _int()
met_p5: Optional[float] = _float()
met_mediana: Optional[float] = _float()
met_p95: Optional[float] = _float()
met_modelo: Optional[str] = _text() # the baseline's registered model version
class EegMetricaElectrodo(TeaModel, table=True):
@@ -181,3 +217,45 @@ class EegMetricaElectrodo(TeaModel, table=True):
mel_met_id: Optional[str] = _text()
mel_electrodo: Optional[str] = _text()
mel_valor: Optional[float] = _float()
mel_z: Optional[float] = _float()
class RelacionAdos2(TeaModel, table=True):
"""One association of an EEG alteration in a scalp zone with an ADOS-2 outcome, per fitted model version."""
__tablename__ = "relacion_ados2"
__table_args__ = (
sa.UniqueConstraint("rel_version", "rel_biomarcador", "rel_zona", "rel_resultado", name="uq_relacion_ados2"),
)
rel_id: Optional[str] = _id()
# Bounded: the natural key the import layer and the tea library merge model rows on is a unique index.
rel_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32), index=True))
rel_nivel: Optional[str] = _text() # NivelRelacionAdos2: the model's level
rel_validado: Optional[int] = _int() # 1 validated by the domain expert, 0 pending
rel_n_cohorte: Optional[int] = _int()
rel_biomarcador: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32))) # MetricaEeg
rel_zona: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32))) # scalp zone code from the tea library
rel_tipo: Optional[str] = _text() # NivelRelacionAdos2: the level this association relates
rel_resultado: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32))) # ADOS-2 item or domain code
rel_evento: Optional[str] = _text() # the outcome event, e.g. "score >= 2"
rel_or: Optional[float] = _float()
rel_ic_inf: Optional[float] = _float()
rel_ic_sup: Optional[float] = _float()
rel_q: Optional[float] = _float()
class RelacionAdos2Paciente(TeaModel, table=True):
"""One patient's z and model probability for an association row: the EEG's metric z mapped through relacion_ados2."""
__tablename__ = "relacion_ados2_paciente"
__table_args__ = (
sa.UniqueConstraint("rap_rel_id", "rap_eeg_id", name="uq_relacion_ados2_paciente"),
)
rap_id: Optional[str] = _id()
rap_rel_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(36), index=True))
rap_eeg_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(36), index=True))
rap_valor_z: Optional[float] = _float()
rap_probabilidad: Optional[float] = _float()
rap_probabilidad_referencia: Optional[float] = _float()
+93 -15
View File
@@ -1,12 +1,15 @@
# Diccionario de datos y reglas de validación — Proyecto TEA
Este documento describe el staging del proyecto: una tabla por tipo de estudio (M-CHAT, ADOS-2, nota de
neuropediatría y EEG), más los pacientes y las órdenes. Para cada tabla se listan sus variables, el tipo de dato,
neuropediatría y EEG), más los pacientes y las órdenes, y las dos del modelo de asociación con el ADOS-2
(`relacion_ados2` y `relacion_ados2_paciente`). Para cada tabla se listan sus variables, el tipo de dato,
la unidad (cuando aplica) y la validación que cumple cada una al importarse. El almacenamiento es permisivo: todo
campo es opcional y la validación ocurre en los esquemas de importación (`WebApi/webapi/imports/schemas/tea`).
Las columnas marcadas **(análisis del EEG)** las escribe el análisis del EEG a partir del EDF guardado: calidad,
canales, duración, sueño, métricas y valores por electrodo.
Las columnas marcadas **(análisis del EEG)** las escribe el análisis del EEG (la biblioteca `tea`) a partir del EDF
guardado: veredicto, criterios de calidad, canales, duración, sueño, métricas y valores por electrodo. Las dos
tablas de asociación con el ADOS-2 las escribe el modelo de asociación (también la biblioteca `tea`), y mientras
este llega la API de importación carga renglones de desarrollo igual que el resto del staging.
---
@@ -88,19 +91,46 @@ Los subtotales por dominio y el total no se guardan: son sumas de los puntajes d
| `eeg_con_sueno` | INTEGER | — | 0 o 1. **(análisis del EEG)** | — |
| `eeg_canales` | INTEGER | canales | Entre 1 y 256. **(análisis del EEG)** | — |
| `eeg_duracion_min` | FLOAT | minutos | Mayor que 0. **(análisis del EEG)** | — |
| `eeg_canales_amplitud` | INTEGER | canales | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
| `eeg_canales_alta_frecuencia` | INTEGER | canales | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
| `eeg_canales_correlacion` | INTEGER | canales | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
| `eeg_canales_sin_senal` | INTEGER | canales | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
| `eeg_ruido_linea_db` | FLOAT | dB | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
| `eeg_ruido_linea_db` | FLOAT | dB | Mayor o igual que 0: la mediana del ruido de la línea eléctrica en el cuero cabelludo. **(análisis del EEG)** | — |
| `eeg_estudio` | BLOB (LONGBLOB en MySQL) | — | El archivo EDF. | — |
| `eeg_valido` | INTEGER | — | 1 válido, 0 no válido; nulo: sin analizar. **(análisis del EEG)** | — |
| `eeg_nivel` | TEXT | — | Nivel de triaje: `completo`, `sin_referencia_auricular`, `parcial` o `no_analizable`. **(análisis del EEG)** | — |
| `eeg_fraccion_limpia` | FLOAT | fracción | Entre 0 y 1: la parte del registro en ventanas limpias. **(análisis del EEG)** | — |
| `eeg_canales_malos` | INTEGER | canales | Mayor o igual que 0. **(análisis del EEG)** | — |
| `eeg_edad_meses` | FLOAT | meses | La edad a la fecha del estudio con que se compararon las métricas; nula sin fecha de nacimiento. **(análisis del EEG)** | — |
| `eeg_plan_hash` | VARCHAR(16) | — | El plan de preprocesamiento con que se analizó. **(análisis del EEG)** | — |
| `eeg_versiones` | TEXT | — | Las versiones de los módulos del análisis (`nombre=versión;…`). **(análisis del EEG)** | — |
| `eeg_analizado_en` | DATETIME | — | Cuándo se analizó. **(análisis del EEG)** | — |
| `eeg_error` | TEXT | — | Por qué el análisis no terminó; nulo si terminó. **(análisis del EEG)** | — |
Un EEG es malo cuando cualquiera de sus criterios de calidad está fuera de su umbral; uno malo no tiene resultado y
sus alteraciones no cuentan.
Un EEG es válido cuando el análisis lo dice (`eeg_valido` = 1): ninguna regla decisiva de `eeg_criterio` fuera de su
umbral y el registro dentro de las condiciones del plan de preprocesamiento. Uno no válido no tiene resultado y sus
alteraciones no cuentan.
---
## 7. Tabla `eeg_metrica` **(análisis del EEG)**
## 7. Tabla `eeg_criterio` **(análisis del EEG)**
Un renglón por cada regla de calidad que el análisis evaluó sobre un EEG: las del estudio completo y, para cada canal
malo, el motivo con su electrodo.
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `cri_id` | VARCHAR(36), llave primaria | — | — | — |
| `cri_eeg_id` | VARCHAR(36), indexado | — | — | → `eeg.eeg_id` |
| `cri_codigo` | TEXT | — | Catálogo `CriterioEeg`: del estudio `file, clean-windows, internal-coverage, bad-scalp-triage, usable-scalp, triage-level, line-noise`; de un canal `dead-channel, frozen, saturated, inf-values, own-gaps, bridge, amplitude, aux-amplitude, does-not-correlate, intermittent-contact, intermittent-bursts`. | — |
| `cri_electrodo` | TEXT | — | El canal del motivo; nulo en las reglas del estudio. | — |
| `cri_valor` | FLOAT | `cri_unidad` | El valor medido, si es un número. | — |
| `cri_valor_texto` | TEXT | — | El valor o el motivo, si es un texto (por ejemplo, el nivel de triaje). | — |
| `cri_unidad` | TEXT | — | `%`, `fraction`, `electrodes` o `dB`. | — |
| `cri_bajo` | FLOAT | `cri_unidad` | Fuera de rango por debajo de este valor. | — |
| `cri_alto` | FLOAT | `cri_unidad` | Fuera de rango por encima de este valor. | — |
| `cri_decisivo` | INTEGER | — | 0 o 1: la regla basta, por sí sola, para que el EEG no sea válido. | — |
| `cri_anormal` | INTEGER | — | 0 o 1. | — |
---
## 8. Tabla `eeg_metrica` **(análisis del EEG)**
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
@@ -108,16 +138,64 @@ sus alteraciones no cuentan.
| `met_eeg_id` | TEXT | — | — | → `eeg.eeg_id` |
| `met_codigo` | TEXT | — | Catálogo `MetricaEeg`: `RITMO_POSTERIOR, HUSOS_SUENO_N2, HUSOS_SUENO_N3, PICOS_PAROXISTICOS, GRADIENTE_ANTEROPOSTERIOR`. | — |
| `met_valor` | FLOAT | la de la métrica | Nulo: la métrica no se puede evaluar (por ejemplo, husos sin registro de sueño). | — |
Solo se guarda el valor medido: el puntaje z y el estado salen de los rangos de referencia por grupo de edad.
| `met_z` | FLOAT | puntaje z | Contra la curva de referencia de la métrica a `eeg_edad_meses`; nulo si la edad no está cubierta. | — |
| `met_fuera` | INTEGER | — | -1 debajo del percentil 5, 0 dentro, +1 arriba del percentil 95. | — |
| `met_p5` | FLOAT | la de la métrica | El percentil 5 de la curva a esa edad. | — |
| `met_mediana` | FLOAT | la de la métrica | La mediana de la curva a esa edad. | — |
| `met_p95` | FLOAT | la de la métrica | El percentil 95 de la curva a esa edad. | — |
| `met_modelo` | TEXT | — | La versión registrada de la curva de referencia. | — |
---
## 8. Tabla `eeg_metrica_electrodo` **(análisis del EEG)**
## 9. Tabla `eeg_metrica_electrodo` **(análisis del EEG)**
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `mel_id` | VARCHAR(36), llave primaria | — | — | — |
| `mel_met_id` | TEXT | — | — | → `eeg_metrica.met_id` |
| `mel_electrodo` | TEXT | — | Un electrodo del sistema 10-20 (`Fp1` … `O2`). | — |
| `mel_valor` | FLOAT | puntaje z | — | — |
| `mel_valor` | FLOAT | la de la métrica | — | — |
| `mel_z` | FLOAT | puntaje z | Contra la curva de referencia del electrodo a `eeg_edad_meses`. | — |
---
## 10. Tabla `relacion_ados2`
Un renglón por versión del modelo y asociación: la razón de momios, en la cohorte, de una alteración del EEG en una
zona del cuero cabelludo contra el desenlace de un reactivo o dominio del ADOS-2. La llave natural
(`rel_version`, `rel_biomarcador`, `rel_zona`, `rel_resultado`) es única: es con la que la API de importación y la
biblioteca `tea` unen renglones al cargar una versión del modelo.
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `rel_id` | VARCHAR(36), llave primaria | — | — | — |
| `rel_version` | VARCHAR(32), indexado | — | La versión del modelo ajustado. | — |
| `rel_nivel` | TEXT | — | Catálogo `NivelRelacionAdos2`: `item, dominio`. El nivel del modelo. | — |
| `rel_validado` | INTEGER | — | 0 o 1: validado por el experto de dominio. | — |
| `rel_n_cohorte` | INTEGER | pacientes | Mayor que 0: el tamaño de la cohorte con que se ajustó el modelo. | — |
| `rel_biomarcador` | VARCHAR(32) | — | Catálogo `MetricaEeg`: la métrica del EEG asociada. | — |
| `rel_zona` | VARCHAR(32) | — | El código de la zona del cuero cabelludo, el de la biblioteca `tea`. | — |
| `rel_tipo` | TEXT | — | Catálogo `NivelRelacionAdos2`: `item, dominio`. El nivel que relaciona esta asociación. | — |
| `rel_resultado` | VARCHAR(32) | — | El código del reactivo del ADOS-2 (los de `ADOS2_ITEMS`) o del dominio. | — |
| `rel_evento` | TEXT | — | El evento de desenlace como umbral legible por máquina sobre el puntaje del desenlace: `>=2` (el puntaje del reactivo, o el total del algoritmo del dominio). | — |
| `rel_or` | FLOAT | razón de momios | Mayor que 0. | — |
| `rel_ic_inf` | FLOAT | razón de momios | El límite inferior del intervalo de confianza; menor o igual que `rel_ic_sup`. | — |
| `rel_ic_sup` | FLOAT | razón de momios | El límite superior del intervalo de confianza. | — |
| `rel_q` | FLOAT | — | Entre 0 y 1: el valor q del ajuste por comparaciones múltiples. | — |
---
## 11. Tabla `relacion_ados2_paciente`
Un renglón por EEG y renglón del modelo: el z del paciente para la asociación y la probabilidad que el modelo le
asigna. La pareja (`rap_rel_id`, `rap_eeg_id`) es única. El desenlace observado no se guarda: se lee del ADOS-2 del
paciente (`ados2`).
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `rap_id` | VARCHAR(36), llave primaria | — | — | — |
| `rap_rel_id` | VARCHAR(36), indexado | — | — | → `relacion_ados2.rel_id` |
| `rap_eeg_id` | VARCHAR(36), indexado | — | — | → `eeg.eeg_id` |
| `rap_valor_z` | FLOAT | puntaje z | El z del paciente en la asociación. | — |
| `rap_probabilidad` | FLOAT | probabilidad | Entre 0 y 1: la probabilidad que da el modelo. | — |
| `rap_probabilidad_referencia` | FLOAT | probabilidad | Entre 0 y 1: la probabilidad de referencia. | — |
+14
View File
@@ -83,6 +83,9 @@ def test_tea_tables_registered():
"eeg",
"eeg_metrica",
"eeg_metrica_electrodo",
"eeg_criterio",
"relacion_ados2",
"relacion_ados2_paciente",
# indicadores_kit CDM, built from staging by the webapi.orquestacion graph.
*INDICADORES_KIT_CDM,
}
@@ -115,3 +118,14 @@ def test_cat_mapeo_keeps_its_rules_in_the_schema():
assert {"ck_cat_mapeo_clase", "ck_cat_mapeo_destino", "ck_cat_mapeo_vigencia", "fk_cat_mapeo_valor",
"uq_cat_mapeo"} <= names
assert "ck_cat_sistema_fuente_vigencia" in {c.name for c in CatSistemaFuente.__table__.constraints}
def test_relacion_ados2_keeps_its_natural_keys_in_the_schema():
"""Pins down: the import merge and the `tea` library upsert one `relacion_ados2` row per
(rel_version, rel_biomarcador, rel_zona, rel_resultado), and one `relacion_ados2_paciente` row per
(rap_rel_id, rap_eeg_id). Fails if either unique constraint is dropped, which would let two imports of
the same model row or two probabilities for the same EEG and association both land."""
from core.tea.models import RelacionAdos2, RelacionAdos2Paciente
assert "uq_relacion_ados2" in {c.name for c in RelacionAdos2.__table__.constraints}
assert "uq_relacion_ados2_paciente" in {c.name for c in RelacionAdos2Paciente.__table__.constraints}
+6
View File
@@ -34,11 +34,14 @@ from core.tea.models import (
Ados2,
Eeg,
EegMetrica,
EegCriterio,
EegMetricaElectrodo,
EvaluacionNeuropediatrica,
Mchat,
OrdenesEstudio,
Pacientes,
RelacionAdos2,
RelacionAdos2Paciente,
)
from core.indicadores.cohortes import TablasCohorte
@@ -74,6 +77,9 @@ evaluacion_neuropediatrica_repository = Repository(get_tea_session, EvaluacionNe
eeg_repository = Repository(get_tea_session, Eeg)
eeg_metrica_repository = Repository(get_tea_session, EegMetrica)
eeg_metrica_electrodo_repository = Repository(get_tea_session, EegMetricaElectrodo)
eeg_criterio_repository = Repository(get_tea_session, EegCriterio)
relacion_ados2_repository = Repository(get_tea_session, RelacionAdos2)
relacion_ados2_paciente_repository = Repository(get_tea_session, RelacionAdos2Paciente)
# indicadores_kit (Core/docs/ADR-004). Se leen con get/list/count; lo que
# se escribe va por métodos de subclases (persistance/edges, por capa).
@@ -0,0 +1,90 @@
"""tea eeg analysis
What the EEG analysis writes from the stored EDF: its verdict, triage level, clean fraction, bad channels, the age it
compared the metrics at and what produced it, on `eeg`; one row per quality check in `eeg_criterio`; each metric's
z, -1/0/+1 against the age baseline and the baseline's p5/median/p95 there, on `eeg_metrica`; each electrode's z, on
`eeg_metrica_electrodo`. Only additions: nothing existing changes.
Revision ID: 16bf0b0ee3e4
Revises: b9e4d2c71a05
Create Date: 2026-11-19 13:14:08.006494
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '16bf0b0ee3e4'
down_revision = 'b9e4d2c71a05'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table('eeg_criterio',
sa.Column('cri_id', sa.String(length=36), nullable=False),
sa.Column('cri_eeg_id', sa.String(length=36), nullable=True),
sa.Column('cri_codigo', sa.Text(), nullable=True),
sa.Column('cri_electrodo', sa.Text(), nullable=True),
sa.Column('cri_valor', sa.Float(), nullable=True),
sa.Column('cri_valor_texto', sa.Text(), nullable=True),
sa.Column('cri_unidad', sa.Text(), nullable=True),
sa.Column('cri_bajo', sa.Float(), nullable=True),
sa.Column('cri_alto', sa.Float(), nullable=True),
sa.Column('cri_decisivo', sa.Integer(), nullable=True),
sa.Column('cri_anormal', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('cri_id')
)
with op.batch_alter_table('eeg_criterio', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_eeg_criterio_cri_eeg_id'), ['cri_eeg_id'], unique=False)
with op.batch_alter_table('eeg', schema=None) as batch_op:
batch_op.add_column(sa.Column('eeg_valido', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('eeg_nivel', sa.Text(), nullable=True))
batch_op.add_column(sa.Column('eeg_fraccion_limpia', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('eeg_canales_malos', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('eeg_edad_meses', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('eeg_plan_hash', sa.String(length=16), nullable=True))
batch_op.add_column(sa.Column('eeg_versiones', sa.Text(), nullable=True))
batch_op.add_column(sa.Column('eeg_analizado_en', sa.DateTime(), nullable=True))
batch_op.add_column(sa.Column('eeg_error', sa.Text(), nullable=True))
with op.batch_alter_table('eeg_metrica', schema=None) as batch_op:
batch_op.add_column(sa.Column('met_z', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('met_fuera', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('met_p5', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('met_mediana', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('met_p95', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('met_modelo', sa.Text(), nullable=True))
with op.batch_alter_table('eeg_metrica_electrodo', schema=None) as batch_op:
batch_op.add_column(sa.Column('mel_z', sa.Float(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('eeg_metrica_electrodo', schema=None) as batch_op:
batch_op.drop_column('mel_z')
with op.batch_alter_table('eeg_metrica', schema=None) as batch_op:
batch_op.drop_column('met_modelo')
batch_op.drop_column('met_p95')
batch_op.drop_column('met_mediana')
batch_op.drop_column('met_p5')
batch_op.drop_column('met_fuera')
batch_op.drop_column('met_z')
with op.batch_alter_table('eeg', schema=None) as batch_op:
batch_op.drop_column('eeg_error')
batch_op.drop_column('eeg_analizado_en')
batch_op.drop_column('eeg_versiones')
batch_op.drop_column('eeg_plan_hash')
batch_op.drop_column('eeg_edad_meses')
batch_op.drop_column('eeg_canales_malos')
batch_op.drop_column('eeg_fraccion_limpia')
batch_op.drop_column('eeg_nivel')
batch_op.drop_column('eeg_valido')
with op.batch_alter_table('eeg_criterio', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_eeg_criterio_cri_eeg_id'))
op.drop_table('eeg_criterio')
@@ -0,0 +1,70 @@
"""tea ados2 association
What the ADOS-2 association model writes: one row per model version and association in `relacion_ados2`, the cohort
odds ratio of an EEG alteration in a scalp zone against an ADOS-2 item or domain outcome, with its confidence
interval and q value; one row per EEG and association in `relacion_ados2_paciente`, the patient's z and the
probability the model gives them (the observed outcome stays in `ados2`, never stored here). Only additions:
nothing existing changes.
Revision ID: 41694156d3a1
Revises: c4306f438b3a
Create Date: 2026-11-21 01:49:39.884071
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '41694156d3a1'
down_revision = 'c4306f438b3a'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table('relacion_ados2',
sa.Column('rel_id', sa.String(length=36), nullable=False),
sa.Column('rel_version', sa.String(length=32), nullable=True),
sa.Column('rel_nivel', sa.Text(), nullable=True),
sa.Column('rel_validado', sa.Integer(), nullable=True),
sa.Column('rel_n_cohorte', sa.Integer(), nullable=True),
sa.Column('rel_biomarcador', sa.String(length=32), nullable=True),
sa.Column('rel_zona', sa.String(length=32), nullable=True),
sa.Column('rel_tipo', sa.Text(), nullable=True),
sa.Column('rel_resultado', sa.String(length=32), nullable=True),
sa.Column('rel_evento', sa.Text(), nullable=True),
sa.Column('rel_or', sa.Float(), nullable=True),
sa.Column('rel_ic_inf', sa.Float(), nullable=True),
sa.Column('rel_ic_sup', sa.Float(), nullable=True),
sa.Column('rel_q', sa.Float(), nullable=True),
sa.PrimaryKeyConstraint('rel_id'),
sa.UniqueConstraint('rel_version', 'rel_biomarcador', 'rel_zona', 'rel_resultado', name='uq_relacion_ados2')
)
with op.batch_alter_table('relacion_ados2', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_relacion_ados2_rel_version'), ['rel_version'], unique=False)
op.create_table('relacion_ados2_paciente',
sa.Column('rap_id', sa.String(length=36), nullable=False),
sa.Column('rap_rel_id', sa.String(length=36), nullable=True),
sa.Column('rap_eeg_id', sa.String(length=36), nullable=True),
sa.Column('rap_valor_z', sa.Float(), nullable=True),
sa.Column('rap_probabilidad', sa.Float(), nullable=True),
sa.Column('rap_probabilidad_referencia', sa.Float(), nullable=True),
sa.PrimaryKeyConstraint('rap_id'),
sa.UniqueConstraint('rap_rel_id', 'rap_eeg_id', name='uq_relacion_ados2_paciente')
)
with op.batch_alter_table('relacion_ados2_paciente', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_relacion_ados2_paciente_rap_eeg_id'), ['rap_eeg_id'], unique=False)
batch_op.create_index(batch_op.f('ix_relacion_ados2_paciente_rap_rel_id'), ['rap_rel_id'], unique=False)
def downgrade() -> None:
with op.batch_alter_table('relacion_ados2_paciente', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_relacion_ados2_paciente_rap_rel_id'))
batch_op.drop_index(batch_op.f('ix_relacion_ados2_paciente_rap_eeg_id'))
op.drop_table('relacion_ados2_paciente')
with op.batch_alter_table('relacion_ados2', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_relacion_ados2_rel_version'))
op.drop_table('relacion_ados2')
@@ -0,0 +1,32 @@
"""tea eeg criteria columns dropped
The EEG analysis writes each quality check as a row of `eeg_criterio`, so the four fixed criterion columns of `eeg`
go. Downgrade brings them back empty: the counts they held aren't kept anywhere else.
Revision ID: c4306f438b3a
Revises: 16bf0b0ee3e4
Create Date: 2026-11-19 14:09:04.196709
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c4306f438b3a'
down_revision = '16bf0b0ee3e4'
branch_labels = None
depends_on = None
COLUMNS = ('eeg_canales_amplitud', 'eeg_canales_alta_frecuencia', 'eeg_canales_correlacion', 'eeg_canales_sin_senal')
def upgrade() -> None:
with op.batch_alter_table('eeg', schema=None) as batch_op:
for column in COLUMNS:
batch_op.drop_column(column)
def downgrade() -> None:
with op.batch_alter_table('eeg', schema=None) as batch_op:
for column in COLUMNS:
batch_op.add_column(sa.Column(column, sa.Integer(), nullable=True))
+70
View File
@@ -0,0 +1,70 @@
"""What this module covers: the TEA Alembic chain in `persistance/tea/alembic`, applied through
`alembic.command` to a throwaway SQLite file: the deployed schema has the ADOS-2 association tables with
their natural keys, downgrading the association revision removes exactly those tables, and the migrated
schema never drifts from `core.tea.models`.
Fixtures: `url_tea` points `settings.tea_database_url` at a temp file and runs `upgrade head`, so a broken
migration fails the suite instead of the tests silently building the schema with `create_all`; it restores
the original URL and clears the cached engine afterwards (`persistance.db` caches engines per URL).
"""
from pathlib import Path
import pytest
from alembic import command
from alembic.config import Config
from sqlalchemy import create_engine, inspect
import persistance
from persistance import db as persistance_db
from persistance.settings import settings
def _config() -> Config:
ini = Path(persistance.__file__).parent / "tea" / "alembic.ini"
return Config(str(ini))
@pytest.fixture
def url_tea(tmp_path):
"""A temp SQLite file whose schema the migrations built, stamped at `head`."""
url_original = settings.tea_database_url
url = f"sqlite:///{tmp_path / 'tea.db'}"
settings.tea_database_url = url
persistance_db.get_tea_engine.cache_clear()
command.upgrade(_config(), "head")
yield url
persistance_db.get_tea_engine.cache_clear()
settings.tea_database_url = url_original
def test_association_tables_deployed_with_their_natural_keys(url_tea):
"""Pins down: `relacion_ados2` exists with the unique (rel_version, rel_biomarcador, rel_zona,
rel_resultado) that the import merge and the `tea` library upsert on, and `relacion_ados2_paciente`
with one row per (rap_rel_id, rap_eeg_id). Fails if the migration creating the tables is dropped or
loses a constraint."""
inspector = inspect(create_engine(url_tea))
assert {"relacion_ados2", "relacion_ados2_paciente"} <= set(inspector.get_table_names())
uniques = {tuple(c["column_names"]) for c in inspector.get_unique_constraints("relacion_ados2")}
assert ("rel_version", "rel_biomarcador", "rel_zona", "rel_resultado") in uniques
uniques_paciente = {tuple(c["column_names"])
for c in inspector.get_unique_constraints("relacion_ados2_paciente")}
assert ("rap_rel_id", "rap_eeg_id") in uniques_paciente
def test_downgrade_of_the_association_revision_drops_only_the_association_tables(url_tea):
"""Pins down: `downgrade -1` removes `relacion_ados2` and `relacion_ados2_paciente` and nothing the
hospital source loaded. Fails if the downgrade stops dropping them, or starts dropping other tables."""
command.downgrade(_config(), "-1")
names = set(inspect(create_engine(url_tea)).get_table_names())
assert "relacion_ados2" not in names
assert "relacion_ados2_paciente" not in names
assert {"pacientes", "ordenes_estudio", "mchat", "ados2", "eeg", "eeg_metrica",
"eeg_criterio", "eeg_metrica_electrodo"} <= names
def test_migrated_schema_matches_the_models(url_tea):
"""Pins down: `alembic check` sees no difference between the migrated schema and `core.tea.models`,
so a model change can never land without its migration. Fails if the metadata and the chain drift."""
command.check(_config())
+2 -28
View File
@@ -82,9 +82,8 @@ vars:
# TEA's rules (models/tea). The cohort: children whose first M-CHAT was at `edad_min_meses` to `edad_max_meses`
# completed months (days / `dias_por_mes`, rounded to one decimal, then truncated); `ventanas`, the age groups of
# that age. A confirmation is a neuropediatrics note with one of `cie_tea` (without the dot, compared exactly).
# An EEG is bad when any quality criterion passes its threshold (`calidad`); a metric is altered when its z-score
# against the reference of the child's age group at the EEG is at least `alteracion_z` away from 0.
# The references, thresholds and `alteracion_z` are placeholders until the domain expert validates them.
# Whether an EEG is valid, and whether a metric is altered (outside its age baseline's p5-p95), is the EEG
# analysis's: the baselines are the trained models in production, which the domain expert validates.
tea:
edad_min_meses: 16
edad_max_meses: 36
@@ -94,31 +93,6 @@ vars:
- {clave: "24_29", desde: 24, hasta: 29}
- {clave: "30_36", desde: 30, hasta: 36}
cie_tea: ["F840"]
alteracion_z: 2
calidad:
canales_amplitud: 2
canales_alta_frecuencia: 2
canales_correlacion: 2
canales_sin_senal: 2
ruido_linea_db: 8
# Reference range of each metric by age group at the EEG: (metric, group, min, max). The mean is the middle of
# the range and the standard deviation a quarter of its width.
referencias:
- ["ritmo_posterior", "16_23", 4.5, 7.0]
- ["ritmo_posterior", "24_29", 5.0, 7.5]
- ["ritmo_posterior", "30_36", 5.5, 8.5]
- ["husos_sueno_n2", "16_23", 2.5, 6.5]
- ["husos_sueno_n2", "24_29", 2.25, 6.25]
- ["husos_sueno_n2", "30_36", 2.0, 6.0]
- ["husos_sueno_n3", "16_23", 0.75, 2.75]
- ["husos_sueno_n3", "24_29", 0.5, 2.5]
- ["husos_sueno_n3", "30_36", 0.5, 2.5]
- ["picos_paroxisticos", "16_23", 0.0, 1.0]
- ["picos_paroxisticos", "24_29", 0.0, 1.0]
- ["picos_paroxisticos", "30_36", 0.0, 1.0]
- ["gradiente_anteroposterior", "16_23", 2.0, 3.5]
- ["gradiente_anteroposterior", "24_29", 1.75, 3.25]
- ["gradiente_anteroposterior", "30_36", 1.5, 3.0]
# The surveillance cohort's rules (models/cacu/cohorts/surveillance).
surveillance_cohort:
recruitment_start: "2024-01-01"
+14 -3
View File
@@ -31,9 +31,20 @@
end
{%- endmacro %}
{# A bounded number of the EEG's quality: within its threshold of `tea.calidad`. #}
{% macro tea_criterio_bueno(columna, umbral) -%}
({{ columna }} is not null and {{ columna }} <= {{ var('tea')['calidad'][umbral] }})
{# The EEG's metrics and quality checks as the catalog names them: `eeg.<metric>`, `eeg.calidad_<check>`. The checks
are the EEG analysis's: study-wide ones on the recording, channel ones on a `parte` per bad channel. #}
{% macro tea_metricas() -%}
{{ return(['ritmo_posterior', 'husos_sueno_n2', 'husos_sueno_n3', 'picos_paroxisticos', 'gradiente_anteroposterior']) }}
{%- endmacro %}
{% macro tea_criterios_estudio() -%}
{{ return(['clean_windows', 'internal_coverage', 'bad_scalp_triage', 'usable_scalp', 'triage_level', 'line_noise',
'file']) }}
{%- endmacro %}
{% macro tea_criterios_canal() -%}
{{ return(['dead_channel', 'frozen', 'saturated', 'inf_values', 'own_gaps', 'bridge', 'amplitude', 'aux_amplitude',
'does_not_correlate', 'intermittent_contact', 'intermittent_bursts']) }}
{%- endmacro %}
{# The later of two values when both are known, else null: a step reached after the previous one is dated by the
+18
View File
@@ -10,3 +10,21 @@
('á','a'),('é','e'),('í','i'),('ó','o'),('ú','u'),('ü','u')] -%}
upper({% for _ in pares %}replace({% endfor %}{{ columna }}{% for con, sin in pares %}, '{{ con }}', '{{ sin }}'){% endfor %})
{%- endmacro %}
{# Texts joined into one, portable: `||` on SQLite and PostgreSQL, CONCAT on MySQL, + on SQL Server. A null part
nulls the whole on SQL Server, where the join then simply doesn't match; the parts are never null there. #}
{% macro concatena() -%}
{{ return(adapter.dispatch('concatena', 'isssteleon')(varargs)) }}
{%- endmacro %}
{% macro default__concatena(campos) -%}
{{ campos | join(' || ') }}
{%- endmacro %}
{% macro mysql__concatena(campos) -%}
concat({{ campos | join(', ') }})
{%- endmacro %}
{% macro sqlserver__concatena(campos) -%}
{{ campos | join(' + ') }}
{%- endmacro %}
@@ -146,6 +146,7 @@ metrics:
grupo: TOTAL
contrato: C2
tipos_periodo: [semestre, mes]
figuras: [fig_c2_donas, fig_c2_barras]
poblaciones_fhir: [measure-observation]
conocida_en: [toma_conocida_en]
parametros:
@@ -172,6 +173,23 @@ metrics:
conocida_en: [biopsia_conocida_en]
orden: [biopsia_gravedad, biopsia_fecha_reporte, biopsia_fuente_id]
sin_seguimiento: SIN_BIOPSIA
# The captions and colours of `cacu.catalogos.biopsia`, least to most severe (WebApi's reference parameters,
# provisional), then the two kept apart: no biopsy reported at the cut-off, and one reported without a grade.
# Groups (provisional): ANORMAL is `deteccion_grados` (dbt var and parameter `cacu.deteccion_grados`), the other
# grades NO_ANORMAL; «Sin biopsia aún» is in no group and «Sin dato» in its own.
etiquetas:
NORMAL: {etiqueta: "Normal", color: "#9DBFE3", grupo: NO_ANORMAL}
LIEBG: {etiqueta: "LIEBG (CIN 1)", color: "#E8C28E", grupo: NO_ANORMAL}
LIEAG: {etiqueta: "LIEAG (CIN 2 y 3)", color: "#D98E4A", grupo: ANORMAL}
CIS: {etiqueta: "Carcinoma in situ", color: "#B55A1F", grupo: ANORMAL}
CARCINOMA: {etiqueta: "Carcinoma invasor", color: "#7A2E0E", grupo: ANORMAL}
SIN_BIOPSIA: {etiqueta: "Sin biopsia aún", color: "#C9CDD2"}
SIN_DATO: {etiqueta: "Biopsia sin grado", color: "#C9CDD2", grupo: SIN_DATO}
# The groups' captions; the no-data group is named as its category.
grupos:
NO_ANORMAL: "Menor que LIEAG"
ANORMAL: "LIEAG o más"
SIN_DATO: "Biopsia sin grado"
estratos:
# The result of that same sample.
citologia_alto_grado:
@@ -131,6 +131,7 @@ metrics:
grupo: TOTAL
contrato: C2
tipos_periodo: [semestre, mes]
figuras: [fig_c2_donas, fig_c2_barras]
poblaciones_fhir: [measure-observation]
conocida_en: [toma_conocida_en]
parametros:
@@ -148,6 +149,23 @@ metrics:
fechada_en: [fecha_reporte]
conocida_en: [resultado_conocido_en]
orden: [fecha_toma, fuente_id]
# The captions and colours of `cacu.catalogos.citologia` and `cacu.catalogos.sin_dato` (WebApi's
# reference parameters, provisional), in their order, from least to most severe. Groups (provisional): ANORMAL
# is `citologia_anomala` (dbt var and parameter `cacu.citologia_anomala`), the rest is NO_ANORMAL, and «Sin dato»
# is a group of its own.
etiquetas:
NORMAL: {etiqueta: "Normal", color: "#9DBFE3", grupo: NO_ANORMAL}
ASC-US: {etiqueta: "ASC-US", color: "#2F6DB3", grupo: ANORMAL}
LIEBG: {etiqueta: "LIEBG", color: "#E8C28E", grupo: ANORMAL}
ASC-H: {etiqueta: "ASC-H", color: "#D98E4A", grupo: ANORMAL}
LIEAG: {etiqueta: "LIEAG", color: "#B55A1F", grupo: ANORMAL}
CIS: {etiqueta: "Carcinoma in situ", color: "#7A2E0E", grupo: ANORMAL}
SIN_DATO: {etiqueta: "Sin dato", color: "#C9CDD2", grupo: SIN_DATO}
# The groups' captions; the no-data group is named as its category.
grupos:
NO_ANORMAL: "Sin anomalía"
ANORMAL: "Anormal"
SIN_DATO: "Sin dato"
estratos:
grupo_edad:
tipo: edad_al_inicio_del_periodo
@@ -166,6 +184,14 @@ metrics:
# takes her out.
- {valor: PRE_COLPOSCOPIA, si: [{citologia_de_vigilancia: true}, {citologia: false}]}
resto: INFO_INSUFICIENTE
# The follow-up statuses' captions, as the follow-up list shows them (WebApi follow_up/estratos.toml). Kept
# out of `estratos` on purpose: the strata's spec is part of a report's key and captions don't change answers.
etiquetas_estrato:
estatus_seguimiento:
PRE_COLPOSCOPIA: "Pre colposcopia"
POST_COLPOSCOPIA: "Post colposcopia"
POST_TRATAMIENTO: "Post tratamiento"
INFO_INSUFICIENTE: "Información insuficiente"
- name: cacu_eu_tiempo_reporte
label: "Días de la toma de la citología a su resultado"
description: >-
@@ -185,6 +211,7 @@ metrics:
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [toma_conocida_en]
parametros:
@@ -219,6 +246,7 @@ metrics:
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [toma_conocida_en]
# The first resolving note's days, if it was written by the event cut-off; a sample without one whose
+12
View File
@@ -0,0 +1,12 @@
version: 2
# The ADOS-2 association model's staging, read by dbt directly. Its rows are model output, not patient events
# (no patient, no date), so they don't go through the two-table silver load like the studies; the import API
# fills them until the `tea` library does. dbt reads them like the `oro` tables the Python cycle writes
# (`_silver.yml`): as sources, and only the gold view on top of them reaches the WebApi.
sources:
- name: staging
schema: "{{ target.schema }}"
tables:
- name: relacion_ados2
- name: relacion_ados2_paciente
@@ -9,12 +9,10 @@ select
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
max(case when m.estado in ('aumentado', 'disminuido') then 1 else 0 end) as con_alteracion
{%- for metrica in tea_metricas() %},
max(case when m.metrica = '{{ metrica }}' and m.estado in ('aumentado', 'disminuido') then 1 else 0 end) as alt_{{ metrica }}
{%- endfor %}
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
@@ -54,8 +54,9 @@ metrics:
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.
en él; un grupo por alteración, y un niño cuenta en cada una que tenga, así que no suman. Una métrica está
alterada fuera de los percentiles 5 a 95 de su curva de referencia a la edad del niño al EEG, pendiente de
validar.
type: ratio
type_params:
numerator: tea_m30_con_alteracion
@@ -34,8 +34,8 @@ 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.
EEG realizados en el periodo a niños de la cohorte, por su calidad: bueno si su análisis lo encontró válido
para el estudio, malo si no. Los que su análisis no ha calificado cuentan como sin analizar.
type: simple
type_params:
measure: eegs
@@ -9,11 +9,18 @@ models:
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."
description: "Cada EEG con su calidad y la edad a la que su análisis comparó las referencias: el EEG del estudio a una fecha de corte."
config: {materialized: view, meta: {lee_la_webapi: true}}
- name: tea_paciente_eeg_criterios
description: "Cada regla de calidad que el análisis evaluó en cada EEG, y cada canal malo con su motivo."
config: {materialized: view, meta: {lee_la_webapi: true}}
- name: tea_paciente_eeg_metricas
description: "Cada métrica de cada EEG contra su referencia."
description: "Cada métrica de cada EEG contra su referencia por edad (p5, mediana, p95) y el modelo registrado de esa 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."
description: "El valor y el puntaje z de cada métrica en cada electrodo."
config: {materialized: view, meta: {lee_la_webapi: true}}
- name: tea_paciente_relacion_ados2
description: "Cada niño, su EEG del estudio y cada renglón de la última versión del modelo que lo puntuó: la
asociación en la cohorte (OR, IC, q) y lo que muestra su ADOS-2 (observado, calculado del primer ADOS-2)."
config: {materialized: view, meta: {lee_la_webapi: true}}
@@ -0,0 +1,52 @@
-- One row per quality check the EEG analysis evaluated on each EEG: each study-wide check (`electrodo` null) with its
-- value, its limit, whether it was out of range and whether it alone can make the EEG not valid, and each bad channel with the check that flagged it and the
-- analysis's reason (`valor_texto`). Labels and units are the catalog's.
{%- set float = dbt.type_float() %}
{% for c in tea_criterios_estudio() %}
select
p.procedimiento_id,
p.pac_id,
{{ as_text("'" ~ c ~ "'") }} as criterio,
{{ as_text("null") }} as electrodo,
max(case when o.resultado_id = 'eeg.calidad_{{ c }}' then o.valor_numerico end) as valor,
max(case when o.resultado_id = 'eeg.calidad_{{ c }}' then o.valor_texto end) as valor_texto,
max(case when o.resultado_id = 'eeg.calidad_{{ c }}_bajo' then o.valor_numerico end) as bajo,
max(case when o.resultado_id = 'eeg.calidad_{{ c }}_alto' then o.valor_numerico end) as alto,
max(case when o.resultado_id = 'eeg.calidad_{{ c }}_anormal' then o.valor_numerico end) as anormal,
max(case when o.resultado_id = 'eeg.calidad_{{ c }}_decisivo' then o.valor_numerico end) as decisivo,
r.etiqueta,
r.unidad
from {{ source('silver', 'procedimiento') }} p
join {{ source('silver', 'observacion_clinica') }} o
on o.procedimiento_id = p.procedimiento_id
and o.resultado_id in ('eeg.calidad_{{ c }}', 'eeg.calidad_{{ c }}_bajo', 'eeg.calidad_{{ c }}_alto',
'eeg.calidad_{{ c }}_anormal', 'eeg.calidad_{{ c }}_decisivo')
left join {{ source('silver', 'cat_resultado') }} r
on r.resultado_id = 'eeg.calidad_{{ c }}'
where p.estudio_id = 'eeg' and p.clase = 'toma'
group by p.procedimiento_id, p.pac_id, r.etiqueta, r.unidad
union all
{% endfor %}
select
padre.procedimiento_id,
padre.pac_id,
{{ as_text("substring(o.resultado_id, 13, 64)") }} as criterio,
p.codigo_fuente as electrodo,
cast(null as {{ float }}) as valor,
o.valor_texto,
cast(null as {{ float }}) as bajo,
cast(null as {{ float }}) as alto,
1 as anormal,
0 as decisivo,
r.etiqueta,
r.unidad
from {{ source('silver', 'procedimiento') }} p
join {{ source('silver', 'procedimiento') }} padre
on padre.procedimiento_id = p.padre_id
join {{ source('silver', 'observacion_clinica') }} o
on o.procedimiento_id = p.procedimiento_id
and o.resultado_id in ({% for c in tea_criterios_canal() %}'eeg.calidad_{{ c }}'{{ ', ' if not loop.last }}{% endfor %})
left join {{ source('silver', 'cat_resultado') }} r
on r.resultado_id = o.resultado_id
where p.estudio_id = 'eeg' and p.clase = 'parte'
@@ -1,4 +1,4 @@
-- One row per EEG, metric and electrode: the metric's z-score there, what the WebApp draws the map from.
-- One row per EEG, metric and electrode: the metric's value and z-score there; the WebApp draws the map from the z.
select procedimiento_id, pac_id, metrica, electrodo, valor
select procedimiento_id, pac_id, metrica, electrodo, valor, valor_z
from {{ ref('tea_eeg_electrodos') }}
@@ -1,4 +1,5 @@
-- One row per EEG and metric: value, age group at the EEG, reference range, z-score and state.
-- One row per EEG and metric: value, age group at the EEG, the baseline's p5, median and p95 there, the registered
-- label of the baseline the analysis compared against, z-score and state.
select procedimiento_id, pac_id, metrica, valor, grupo_edad_eeg, ref_min, ref_max, valor_z, estado
select procedimiento_id, pac_id, metrica, valor, grupo_edad_eeg, ref_min, ref_mediana, ref_max, modelo, valor_z, estado
from {{ ref('tea_eeg_metricas') }}
@@ -1,18 +1,9 @@
-- One row per EEG: its date, what its analysis wrote, each quality criterion within its threshold or not
-- (`<criterio>_bueno`, null while not analysed) and its overall quality. The WebApi picks the study's EEG at a
-- cut-off: the first good one by then, or else the latest, marked not valid.
{% set criterios = [
('calidad_amplitud', 'canales_amplitud'), ('calidad_alta_frecuencia', 'canales_alta_frecuencia'),
('calidad_correlacion', 'canales_correlacion'), ('calidad_sin_senal', 'canales_sin_senal'),
('calidad_linea', 'ruido_linea_db')] %}
-- One row per EEG: its date, what its analysis wrote (sleep, channels, duration, the age it compared the references
-- at, triage level, clean fraction, bad channels, line noise) and its quality. Its quality checks are
-- `tea_paciente_eeg_criterios`. The WebApi picks the study's EEG at a cut-off: the first good one by then, or else
-- the latest, marked not valid.
select
procedimiento_id, pac_id, fecha_eeg, con_sueno, canales, duracion_min,
{%- for r, umbral in criterios %}
{{ r }},
case when {{ r }} is null then null when {{ tea_criterio_bueno(r, umbral) }} then 1 else 0 end as {{ r }}_bueno,
{%- endfor %}
calidad,
valido
procedimiento_id, pac_id, fecha_eeg, con_sueno, canales, duracion_min, edad_meses, nivel, fraccion_limpia,
canales_malos, ruido_linea_db, calidad, valido
from {{ ref('tea_eegs') }}
@@ -0,0 +1,90 @@
-- One row per child of the cohort, the study's EEG and association row of the latest model version that scored
-- that EEG: the model's metadata (version, expert validation, level, cohort size), the association (EEG metric,
-- scalp zone, outcome level, ADOS-2 item or domain, event) with the cohort's odds ratio, confidence interval and
-- q, and the child's z and probabilities. `observado` is read here, never stored: the outcome's score in the
-- child's first ADOS-2 by date (the one the patient summary shows), the item's score for an item, the domain's
-- algorithm total for a domain. `rel_evento` is the outcome event as a threshold on that score, machine-readable
-- (`>=2`).
--
-- Latest model version is the greatest version label among the versions that scored the child's study EEG.
-- The patient rows reference the EEG by its staging id, the recording's `fuente_id` in silver.
-- The association tables are model output, not patient events, so they reach dbt as staging sources
-- (`models/tea/_staging.yml`), not through the two-table silver load.
with estudio as (
select h.pac_id, h.eeg_estudio_id as procedimiento_id, e.fuente_id as eeg_id
from {{ ref('tea_hitos') }} h
join {{ ref('tea_eegs') }} e on e.procedimiento_id = h.eeg_estudio_id
where h.vigente = 1 and h.eeg_estudio_id is not null
),
ultima_version as (
select e.pac_id, max(r.rel_version) as version
from estudio e
join {{ source('staging', 'relacion_ados2_paciente') }} rap on rap.rap_eeg_id = e.eeg_id
join {{ source('staging', 'relacion_ados2') }} r on r.rel_id = rap.rap_rel_id
group by e.pac_id
),
primer_ados2 as (
select a.pac_id, min(a.fecha_ados2) as fecha
from {{ ref('tea_ados2') }} a
group by a.pac_id
),
observados as (
select a.pac_id, r.reactivo, r.dominio, r.puntaje, r.puntaje_algoritmo
from primer_ados2 p
join {{ ref('tea_ados2') }} a on a.pac_id = p.pac_id and a.fecha_ados2 = p.fecha
join {{ ref('tea_ados2_reactivos') }} r on r.procedimiento_id = a.procedimiento_id
),
item_obs as (
select pac_id, reactivo, puntaje from observados
),
dominio_obs as (
select pac_id, dominio, sum(puntaje_algoritmo) as total
from observados
group by pac_id, dominio
)
select
e.pac_id,
e.procedimiento_id,
r.rel_version as version,
r.rel_validado as validado,
r.rel_nivel as nivel,
r.rel_n_cohorte as n_cohorte,
r.rel_biomarcador as biomarcador,
r.rel_zona as zona,
r.rel_tipo as tipo,
r.rel_resultado as resultado,
r.rel_evento as evento,
r.rel_or as odds_ratio,
r.rel_ic_inf as ic_inf,
r.rel_ic_sup as ic_sup,
r.rel_q as q,
rap.rap_valor_z as valor_z,
rap.rap_probabilidad as probabilidad,
rap.rap_probabilidad_referencia as probabilidad_referencia,
case
when r.rel_tipo = 'item' then io.puntaje
when r.rel_tipo = 'dominio' then dom.total
end as observado
from estudio e
join ultima_version u
on u.pac_id = e.pac_id
join {{ source('staging', 'relacion_ados2_paciente') }} rap
on rap.rap_eeg_id = e.eeg_id
join {{ source('staging', 'relacion_ados2') }} r
on r.rel_id = rap.rap_rel_id
and r.rel_version = u.version
left join item_obs io
on io.pac_id = e.pac_id
and r.rel_tipo = 'item'
and io.reactivo = {{ concatena(as_text("'ados2.'"), 'r.rel_resultado') }}
left join dominio_obs dom
on dom.pac_id = e.pac_id
and r.rel_tipo = 'dominio'
and dom.dominio = r.rel_resultado
@@ -1,14 +1,20 @@
/* One row per EEG, metric and electrode: the metric's z-score at that 10-20 electrode, from its analysis. */
/* One row per EEG, metric and electrode: the metric's value at that 10-20 electrode and its z against the
electrode's age baseline, from the analysis. */
select
padre.procedimiento_id,
padre.pac_id,
{{ as_text("substring(o.resultado_id, 5, 64)") }} as metrica,
p.codigo_fuente as electrodo,
o.valor_numerico as valor
o.valor_numerico as valor,
z.valor_numerico as valor_z
from {{ source('silver', 'procedimiento') }} p
join {{ source('silver', 'procedimiento') }} padre
on padre.procedimiento_id = p.padre_id
join {{ source('silver', 'observacion_clinica') }} o
on o.procedimiento_id = p.procedimiento_id
and o.resultado_id in ({% for m in tea_metricas() %}'eeg.{{ m }}'{{ ', ' if not loop.last }}{% endfor %})
left join {{ source('silver', 'observacion_clinica') }} z
on z.procedimiento_id = p.procedimiento_id
and z.resultado_id = {{ dbt.concat(["o.resultado_id", "'_z'"]) }}
where p.estudio_id = 'eeg' and p.clase = 'parte'
@@ -1,44 +1,53 @@
/* One row per EEG and metric its analysis measured: the value, the child's age group at the EEG, the reference
range for it, the z-score and its state. `no_evaluable`: the value is null (spindles without sleep) or there's no
reference for the age; `aumentado` or `disminuido`: at least `tea.alteracion_z` away from the mean; else `normal`. */
/* One row per EEG and metric its analysis measured: the value, the child's age group at the EEG, and the analysis's
comparison with the metric's age baseline: its z and the baseline's p5, median and p95 at the child's age
(`ref_min`, `ref_mediana`, `ref_max`), plus the registered label of the baseline that comparison used (`modelo`).
The state comes from the analysis's -1/0/+1: `aumentado` above p95, `disminuido` below p5, `normal` within;
`no_evaluable` without a z (no value, no baseline in production, or an age the baseline doesn't cover). */
{% set z = var('tea')['alteracion_z'] %}
{%- set deviation = ['z', 'fuera', 'p5', 'mediana', 'p95'] %}
with medidas as (
{%- for m in tea_metricas() %}
select
e.procedimiento_id,
e.pac_id,
e.fecha_eeg,
{{ as_text("substring(o.resultado_id, 5, 64)") }} as metrica,
o.valor_numerico as valor,
{{ tea_grupo_edad(tea_meses_cumplidos('de.dia_num - dn.dia_num')) }} as grupo_edad_eeg
{{ as_text("'" ~ m ~ "'") }} as metrica,
max(case when o.resultado_id = 'eeg.{{ m }}' then o.valor_numerico end) as valor
{%- for d in deviation %},
max(case when o.resultado_id = 'eeg.{{ m }}_{{ d }}' then o.valor_numerico end) as {{ d }}
{%- endfor %},
max(case when o.resultado_id = 'eeg.{{ m }}_modelo' then o.valor_texto end) as modelo
from {{ ref('tea_eegs') }} e
join {{ source('silver', 'observacion_clinica') }} o
on o.procedimiento_id = e.procedimiento_id
and o.resultado_id in ('eeg.ritmo_posterior', 'eeg.husos_sueno_n2', 'eeg.husos_sueno_n3',
'eeg.picos_paroxisticos', 'eeg.gradiente_anteroposterior')
left join {{ source('silver', 'persona') }} pe on pe.pac_id = e.pac_id
left join {{ source('silver', 'dim_fecha') }} de on de.fecha = e.fecha_eeg
left join {{ source('silver', 'dim_fecha') }} dn on dn.fecha = pe.fecha_nacimiento
),
puntuadas as (
select
m.*,
r.ref_min,
r.ref_max,
case when m.valor is not null and r.ref_de > 0 then (m.valor - r.ref_media) / r.ref_de end as valor_z
from medidas m
left join {{ ref('tea_eeg_referencias') }} r
on r.metrica = m.metrica and r.grupo_edad = m.grupo_edad_eeg
and o.resultado_id in ('eeg.{{ m }}'{% for d in deviation %}, 'eeg.{{ m }}_{{ d }}'{% endfor %},
'eeg.{{ m }}_modelo')
group by e.procedimiento_id, e.pac_id, e.fecha_eeg
having max(case when o.resultado_id = 'eeg.{{ m }}' then 1 end) = 1
{{ 'union all' if not loop.last }}
{%- endfor %}
)
select
p.*,
m.procedimiento_id,
m.pac_id,
m.fecha_eeg,
m.metrica,
m.valor,
{{ tea_grupo_edad(tea_meses_cumplidos('de.dia_num - dn.dia_num')) }} as grupo_edad_eeg,
m.p5 as ref_min,
m.mediana as ref_mediana,
m.p95 as ref_max,
m.z as valor_z,
m.modelo,
case
when p.valor_z is null then {{ as_text("'no_evaluable'") }}
when p.valor_z >= {{ z }} then {{ as_text("'aumentado'") }}
when p.valor_z <= -{{ z }} then {{ as_text("'disminuido'") }}
when m.z is null then {{ as_text("'no_evaluable'") }}
when m.fuera = 1 then {{ as_text("'aumentado'") }}
when m.fuera = -1 then {{ as_text("'disminuido'") }}
else {{ as_text("'normal'") }}
end as estado
from puntuadas p
from medidas m
left join {{ source('silver', 'persona') }} pe on pe.pac_id = m.pac_id
left join {{ source('silver', 'dim_fecha') }} de on de.fecha = m.fecha_eeg
left join {{ source('silver', 'dim_fecha') }} dn on dn.fecha = pe.fecha_nacimiento
@@ -1,10 +0,0 @@
{% set refs = var('tea')['referencias'] %}
/* The reference range of each EEG metric by age group at the EEG (`tea.referencias`), with the mean (the middle of
the range) and the standard deviation (a quarter of its width) its z-score is computed with. */
{% for metrica, grupo, minimo, maximo in refs %}
{{ 'union all' if not loop.first }}
select {{ as_text("'" ~ metrica ~ "'") }} as metrica, {{ as_text("'" ~ grupo ~ "'") }} as grupo_edad,
cast({{ minimo }} as {{ dbt.type_float() }}) as ref_min, cast({{ maximo }} as {{ dbt.type_float() }}) as ref_max,
cast({{ (minimo + maximo) / 2 }} as {{ dbt.type_float() }}) as ref_media,
cast({{ (maximo - minimo) / 4 }} as {{ dbt.type_float() }}) as ref_de
{%- endfor %}
+15 -22
View File
@@ -1,11 +1,6 @@
/* One row per EEG: what its analysis wrote and its quality. `BUENO` when every criterion is within its threshold
(`tea.calidad`), `MALO` when one isn't, `SIN_ANALIZAR` while the analysis hasn't written any. Only a good EEG is
valid: a bad one has no result and its alterations don't count. */
{% set criterios = [
('calidad_amplitud', 'canales_amplitud'), ('calidad_alta_frecuencia', 'canales_alta_frecuencia'),
('calidad_correlacion', 'canales_correlacion'), ('calidad_sin_senal', 'canales_sin_senal'),
('calidad_linea', 'ruido_linea_db')] %}
/* One row per EEG: what its analysis wrote and its quality. `BUENO` when the analysis found it valid, `MALO` when
it didn't, `SIN_ANALIZAR` while it hasn't analysed it. Only a good EEG is valid: a bad one has no result and its
alterations don't count. `edad_meses` is the age the analysis compared the metrics' references at, from the EDF. */
with valores as (
select
@@ -14,12 +9,15 @@ with valores as (
p.fuente_id,
p.fecha as fecha_eeg,
p.carga_id,
max(case when o.resultado_id = 'eeg.con_sueno' then o.valor_numerico end) as con_sueno,
max(case when o.resultado_id = 'eeg.canales' then o.valor_numerico end) as canales,
max(case when o.resultado_id = 'eeg.duracion_min' then o.valor_numerico end) as duracion_min,
{%- for resultado, _ in criterios %}
max(case when o.resultado_id = 'eeg.{{ resultado }}' then o.valor_numerico end) as {{ resultado }}{{ ',' if not loop.last }}
{%- endfor %}
max(case when o.resultado_id = 'eeg.valido' then o.valor_numerico end) as veredicto,
max(case when o.resultado_id = 'eeg.nivel' then o.valor_texto end) as nivel,
max(case when o.resultado_id = 'eeg.fraccion_limpia' then o.valor_numerico end) as fraccion_limpia,
max(case when o.resultado_id = 'eeg.canales_malos' then o.valor_numerico end) as canales_malos,
max(case when o.resultado_id = 'eeg.edad_meses' then o.valor_numerico end) as edad_meses,
max(case when o.resultado_id = 'eeg.con_sueno' then o.valor_numerico end) as con_sueno,
max(case when o.resultado_id = 'eeg.canales' then o.valor_numerico end) as canales,
max(case when o.resultado_id = 'eeg.duracion_min' then o.valor_numerico end) as duracion_min,
max(case when o.resultado_id = 'eeg.ruido_linea' then o.valor_numerico end) as ruido_linea_db
from {{ source('silver', 'procedimiento') }} p
left join {{ source('silver', 'observacion_clinica') }} o
on o.procedimiento_id = p.procedimiento_id
@@ -30,14 +28,9 @@ with valores as (
select
v.*,
case
when {% for r, _ in criterios %}v.{{ r }} is null{{ ' and ' if not loop.last }}{% endfor %}
then {{ as_text("'SIN_ANALIZAR'") }}
when {% for r, umbral in criterios %}{{ tea_criterio_bueno('v.' ~ r, umbral) }}{{ ' and ' if not loop.last }}{% endfor %}
then {{ as_text("'BUENO'") }}
when v.veredicto is null then {{ as_text("'SIN_ANALIZAR'") }}
when v.veredicto = 1 then {{ as_text("'BUENO'") }}
else {{ as_text("'MALO'") }}
end as calidad,
case
when {% for r, umbral in criterios %}{{ tea_criterio_bueno('v.' ~ r, umbral) }}{{ ' and ' if not loop.last }}{% endfor %}
then 1 else 0
end as valido
case when v.veredicto = 1 then 1 else 0 end as valido
from valores v
+1 -1
Submodule WebApi updated: b1bbbc25b4...26631bd564
+1 -1
Submodule WebApp updated: baf5edca42...fb54cfb188
+4
View File
@@ -44,6 +44,10 @@ WEBAPI_REPORT_MIN_COUNT=5
# INDICADORES_HASTA=2026
# Cada cuántos segundos revisa si hubo cargas nuevas.
INDICADORES_INTERVALO_S=20
# Dónde analiza TEA los EEG guardados antes de cargar la plata: auto (DASK_SCHEDULER_ADDRESS si existe, si no un
# clúster local), local, remote, sync (en el mismo proceso) u off.
# EEG_ANALYSIS_CLUSTER=auto
# DASK_SCHEDULER_ADDRESS=tcp://dask-scheduler:8786
# --- Proceso de la API ---
WEBAPI_MAX_UPLOAD_MB=200
+7 -1
View File
@@ -236,7 +236,13 @@ El servicio `indicadores` revisa cada `INDICADORES_INTERVALO_S` segundos (20 por
omisión) si hubo cargas. Cuando una carga escribe registros de un dominio,
vuelve a calcular ese dominio con todo lo que hay en la base: carga los datos,
prepara las vistas y calcula cada indicador en cada periodo; en CaCu también
arma la cohorte de vigilancia. Al final revisa la integridad de lo cargado.
arma la cohorte de vigilancia; en TEA, antes de cargar, analiza cada EEG guardado
que no se haya analizado (calidad, métricas y valores por electrodo). Al final
revisa la integridad de lo cargado.
- El análisis de EEG tarda minutos por estudio. `EEG_ANALYSIS_CLUSTER` dice dónde
corre: `auto` (por omisión: en el clúster de Dask de `DASK_SCHEDULER_ADDRESS`, si
existe, o en uno local), `sync` (en el mismo proceso) u `off` (fuera del recálculo).
- Los años calculados van de `INDICADORES_DESDE` a `INDICADORES_HASTA`
(por omisión, los últimos cinco años). Ajústelos a los años que cubren los
+2 -2
View File
@@ -26,7 +26,7 @@ CONSTRUIR_IMAGENES="${CONSTRUIR_IMAGENES:-1}"
[ -d .git ] || error "Corra esto desde la raíz del repositorio."
[ -z "$(git status --porcelain)" ] \
|| error "Hay cambios sin comprometer; git archive solo empaqueta lo que está en HEAD. Comprométalos o guárdelos (git stash) antes de continuar."
git submodule status | grep -q '^[+-]' \
git submodule status --recursive | grep -q '^[+-]' \
&& error "Hay submódulos sin comprometer o desactualizados respecto al índice (vea 'git submodule status'); corra 'git submodule update' o comprometa el puntero." \
|| true
[ -e "$DESTINO" ] && error "Ya existe $DESTINO; bórrelo o pase otra ruta de destino."
@@ -37,7 +37,7 @@ aviso "Exportando el repositorio principal (HEAD) a codigo/"
git archive HEAD | tar -x -C "$DESTINO/codigo"
aviso "Exportando submódulos, cada uno en su commit fijado"
git submodule status | while read -r linea; do
git submodule status --recursive | while read -r linea; do
sha="$(printf '%s\n' "$linea" | awk '{s=$1; gsub(/^[+-]/, "", s); print s}')"
ruta="$(printf '%s\n' "$linea" | awk '{print $2}')"
aviso " $ruta @ $sha"
+1 -1
Submodule models updated: 7b2eae2782...200cb106e1