Compare commits

...

58 Commits

Author SHA1 Message Date
edgar fdd0befa76 feat(cacu): add the times along the screening route
A model with one row per cytology follows the route: the first colposcopy after the sample, the first biopsy report
the sample led to, and the three steps between consecutive events (cytology result to colposcopy, colposcopy to
biopsy report, biopsy report to diagnosis). Five measures publish them with their windows, 60 days, provisional.
2026-11-21 23:52:20 -06:00
edgar 78b3d28008 feat(cacu): add the times from sample and from diagnosis to treatment
A macro finds the first event of a kind after each start, for the same patient, within a horizon. The diagnosis
lookup of cacu_tomas_citologia uses it with the same result, and two more calls give the days from the sample to
the first treatment and from its diagnosis to it. Both horizons are 60 days, provisional.
2026-11-21 19:35:44 -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
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
Angel Capetillo Zavala aa840b9f31 chore(submodules): update WebApp with the CI spec fixes 2026-11-18 23:41:47 -06:00
Angel Capetillo Zavala d2f597cec8 chore(submodules): update WebApp dev color fixes 2026-11-18 15:30:00 -06:00
Angel Capetillo Zavala cc5738d036 chore(submodules): update WebApp for CaMa BI-RADS donut 2026-11-18 15:13:27 -06:00
Angel Capetillo Zavala 3cd094a8c5 chore: actualizar WebApp con ajustes de CaMa 2026-11-18 14:29:34 -06:00
Angel Capetillo Zavala 9ace5da517 chore: actualizar WebApp con ajustes de CaMa 2026-11-18 09:25:45 -06:00
Angel Capetillo Zavala 0017b0ca4c Update WebApp CaMa indicator labels 2026-11-17 12:44:43 -06:00
Angel Capetillo Zavala 9903e22c2a Add CaMa cohort and L3 measures with integrated API and dashboard
Publish deterministic cohort candidates and detection, result-to-diagnosis and BI-RADS histopathology measures. Pin locally prepared WebApi and WebApp commits based on current dev; retain models and shared persistence changes from upstream. Document compatibility, required views and stored-report behavior.
2026-11-17 10:44:08 -06:00
Roberto Treviño Cervantes 8885162147 wording fixes 2026-11-17 02:20:15 -06:00
Roberto Treviño Cervantes 20f244c014 wording fixes 2026-11-17 02:18:05 -06:00
roberto 9baeeb7ff0 Merge pull request 'Kit exit: retire indicadores_kit, converge TEA/CaMa work onto dev' (#11) from feature/kit-exit-integration into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/11
2026-11-16 21:09:40 -06:00
Roberto Treviño Cervantes 28d80ad7e3 Submodule pointers: the WebApi with live estimators and pac_id follow-up, the WebApp with the CaMa dashboard over FHIR 2026-11-15 05:40:28 -06:00
Roberto Treviño Cervantes 80e0677b3a Compose profile that trains the CaCu model on the loaded data; the manual explains the measures, the model and the risk batches 2026-11-15 05:39:26 -06:00
Roberto Treviño Cervantes a6a05febfd TEA: one migration head again, joining the source-terminology and order-PDF revisions 2026-11-15 00:48:48 -06:00
Roberto Treviño Cervantes 1405208c3e Merge remote-tracking branch 'origin/feature/163-tea-redesign' into feature/kit-exit-integration
# Conflicts:
#	Core/core/tea/models.py
#	Core/spec/tablas_TEA.md
#	Persistance/persistance/cacu/__init__.py
#	Persistance/persistance/cama/__init__.py
#	Persistance/persistance/edges/silver/__init__.py
#	Persistance/persistance/tea/__init__.py
#	README.md
#	Transformation/.gitignore
#	Transformation/dbt_project.yml
#	WebApi
#	WebApp
#	indicadores_kit
#	models
2026-11-15 00:47:16 -06:00
Roberto Treviño Cervantes 64abc56989 Retire the indicadores_kit submodule: its jobs live in Transformation, the WebApi and models 2026-11-15 00:40:13 -06:00
alberto 918fe01ea1 WebApp submodule pointer: history chart and KPI card with measures that publish more groups 2026-11-13 21:15:48 -06:00
alberto 130ef28a16 WebApp submodule pointer: the EEG result measure draws one bar per alteration 2026-11-13 19:38:47 -06:00
rockdrigo 983b702488 WebApi and WebApp submodule pointers: indicators over FHIR and the TEA views; dbt's local database ignored 2026-11-13 17:03:23 -06:00
alberto 1dbde8b830 The webapi image builds its own dbt manifest: a local Transformation/target stays out of the build context; submodule pointer 2026-11-13 15:31:29 -06:00
alberto 5aa90c230a Merge remote-tracking branch 'origin/feature/163-tea-redesign' into feature/163-tea-redesign 2026-11-13 15:13:42 -06:00
alberto 92cf95e1af TEA: ordenes_estudio.ord_pdf_blob holds the study's report as a PDF (new revision); submodule pointer 2026-11-13 15:03:02 -06:00
Angel Capetillo Zavala 532338cdea Update TEA web application 2026-11-13 14:28:10 -06:00
alberto 11dabc4714 Ignore graphify's output 2026-11-12 19:47:50 -06:00
alberto c67b52b828 TEA: one version of each child per load that brought its facts, and a neuropediatrics note counts from the psychology step on; submodule pointer 2026-11-12 19:47:19 -06:00
edgar 3aec97a8b7 TEA staging by study (eight tables and a new revision), its catalog, and dbt's TEA models and measures; submodule pointers 2026-11-12 15:21:26 -06:00
edgar f7faabf699 SQL Server 2016: dbt's sources in the target's schema, one type per timeline value, LTRIM(RTRIM()) for TRIM, stratum values added to their catalog 2026-11-08 17:28:24 -06:00
edgar 987efe54f8 The indicator kit's code lives in its owners now: the WebApi, models and Transformation 2026-11-08 17:28:24 -06:00
edgar bcfd6aef07 English names: Persistance's edges (bronze, silver, gold), the materializer and their repositories 2026-11-08 17:28:24 -06:00
edgar f13efbad67 CaCu and CaMa measures from dbt's semantic layer over the generic tables: follow-up status from inferred procedures, one timeline for every reader 2026-11-08 17:28:24 -06:00
58 changed files with 2002 additions and 209 deletions
+3
View File
@@ -10,4 +10,7 @@ WebApp/
**/uv.lock
!WebApi/uv.lock
dist/
# The image compiles its own manifest.
Transformation/target/
Transformation/logs/
**/node_modules/
-4
View File
@@ -7,7 +7,3 @@
[submodule "models"]
path = models
url = ssh://git@10.0.10.41:2222/ISSSTELEON/models.git
[submodule "indicadores_kit"]
path = indicadores_kit
url = ssh://git@10.0.10.41:2222/ISSSTELEON/indicadores_kit.git
branch = dev
+309 -25
View File
@@ -196,13 +196,39 @@ 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`) and the curve's p5, median and p95 there. 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 +243,313 @@ 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.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_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.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.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"
# An order (procedure of class `orden`): its `estudio_id` is the study it asks for, from `codigos_hospital`.
[orden]
+22
View File
@@ -54,6 +54,28 @@ class MetricaEeg(str, Enum):
GRADIENTE_ANTEROPOSTERIOR = "GRADIENTE_ANTEROPOSTERIOR"
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",
+45 -8
View File
@@ -1,14 +1,14 @@
"""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.
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 +49,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"
@@ -71,6 +75,7 @@ class OrdenesEstudio(TeaModel, table=True):
)
ord_tipo_estudio: Optional[str] = _text() # TipoEstudio: ADOS2, NEUROPEDIATRIA, EEG
ord_fecha: Optional[date] = _date()
ord_pdf_blob: Optional[bytes] = Field(default=None, sa_column=sa.Column(FileBlob)) # the study's report, as PDF
class Mchat(TeaModel, table=True):
@@ -151,13 +156,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):
@@ -169,6 +198,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):
@@ -180,3 +216,4 @@ 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()
+47 -14
View File
@@ -5,8 +5,8 @@ neuropediatría y EEG), más los pacientes y las órdenes. Para cada tabla se li
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.
---
@@ -29,6 +29,7 @@ canales, duración, sueño, métricas y valores por electrodo.
| `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_pdf_blob` | BLOB (LONGBLOB en MySQL/MariaDB) | — | Informe del estudio en PDF, si la fuente lo trae. | — |
---
@@ -87,19 +88,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 |
|---|---|---|---|---|
@@ -107,16 +135,21 @@ 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`. | — |
+1
View File
@@ -83,6 +83,7 @@ def test_tea_tables_registered():
"eeg",
"eeg_metrica",
"eeg_metrica_electrodo",
"eeg_criterio",
# indicadores_kit CDM, built from staging by the webapi.orquestacion graph.
*INDICADORES_KIT_CDM,
}
@@ -14,6 +14,7 @@ from persistance.edges.gold.cohorts import (
CohortMember,
PatientMembership,
PatientRisk,
PendingBatch,
RiskOutsideCohort,
RiskHorizon,
change_state_in,
@@ -34,6 +35,7 @@ __all__ = [
"MeasureReportRepository",
"PatientMembership",
"PatientRisk",
"PendingBatch",
"PublicationRepository",
"ReferenceRepository",
"RiskOutsideCohort",
@@ -114,6 +114,22 @@ class CohortRepository(Repository):
{v.variable: v.valor_codigo if v.valor_codigo is not None else v.valor_numerico
for v in values})
def pending_batches(self) -> list["PendingBatch"]:
"""Batches with no evaluation confirmed or voided yet (ADR-MD-008): created by estimating, waiting for
someone's decision. Newest first."""
lote, e = self.cohortes.EvaluacionRiesgoLote, self.cohortes.EvaluacionRiesgo
with self._session_factory() as sesion:
lotes = sesion.exec(select(lote).order_by(lote.lote_id.desc())).all()
pending = []
for fila in lotes:
latest = _latest_versions(sesion, e, fila.lote_id)
decided = sesion.exec(select(e.evaluacion_id).join(latest, _same_version(e, latest))
.where(e.lote_id == fila.lote_id, e.estado != PRELIMINAR).limit(1)).first()
if decided is None:
pending.append(PendingBatch(fila.lote_id, fila.modelo_nombre, fila.modelo_version,
fila.evaluado_en, fila.n_evaluaciones))
return pending
def current_risk(self, pac_id: int) -> "PatientRisk | None":
"""The patient's risks in the current batch: the highest `lote_id` among the patient's batches where some
evaluation's latest version is `final`. One horizon per `horizonte_anios`, at its latest version, ascending;
@@ -159,6 +175,18 @@ class RiskHorizon:
estado: str
@dataclass(frozen=True)
class PendingBatch:
"""A risk batch waiting for someone to confirm or void it; no evaluation has reached `final` or
`entered-in-error` yet."""
lote_id: int
modelo_nombre: str
modelo_version: str
evaluado_en: datetime
n_evaluaciones: int
@dataclass(frozen=True)
class PatientRisk:
"""A patient's risks in the current batch, with the model that produced them."""
+2
View File
@@ -34,6 +34,7 @@ from core.tea.models import (
Ados2,
Eeg,
EegMetrica,
EegCriterio,
EegMetricaElectrodo,
EvaluacionNeuropediatrica,
Mchat,
@@ -74,6 +75,7 @@ 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)
# 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,28 @@
"""tea order pdf
`ordenes_estudio.ord_pdf_blob` holds the report of the study an order asks for, as a PDF.
Revision ID: a7d3c9e5b160
Revises: f2b6d1e8c934
Create Date: 2026-11-13 10:12:00.000000
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = 'a7d3c9e5b160'
down_revision = 'f2b6d1e8c934'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('ordenes_estudio', schema=None) as batch_op:
batch_op.add_column(sa.Column('ord_pdf_blob', sa.LargeBinary().with_variant(mysql.LONGBLOB(), 'mariadb').with_variant(mysql.LONGBLOB(), 'mysql'), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('ordenes_estudio', schema=None) as batch_op:
batch_op.drop_column('ord_pdf_blob')
@@ -0,0 +1,24 @@
"""tea heads joined
The source-terminology tables and `ordenes_estudio.ord_pdf_blob` were added on separate lines from the same
revision; this joins them so the chain has one head again. Nothing to change on any engine.
Revision ID: b9e4d2c71a05
Revises: 6d772e9a342f, a7d3c9e5b160
Create Date: 2026-11-15 00:50:00.000000
"""
# revision identifiers, used by Alembic.
revision = 'b9e4d2c71a05'
down_revision = ('6d772e9a342f', 'a7d3c9e5b160')
branch_labels = None
depends_on = None
def upgrade() -> None:
pass
def downgrade() -> None:
pass
@@ -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))
+19 -1
View File
@@ -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.edges.gold import CohortRepository, RiskHorizon
from persistance.edges.gold import CohortRepository, PendingBatch, RiskHorizon
URL = "cacu/cohorte_vigilancia"
TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote,
@@ -90,3 +90,21 @@ def test_an_annulled_batch_is_no_longer_current(repository):
repository.change_state(first, "entered-in-error", "modelo equivocado")
assert repository.current_risk(10) is None
def test_pending_batches_are_the_ones_with_no_decision_yet(repository):
"""Pins down: a batch stays pending until it's confirmed or voided, newest first, and dropping off the list is
permanent either way. Fails if a confirmed or a voided batch is still listed, or the order is reversed."""
first = _batch(repository, "1", [(10, 1.0, 0.1, None, None)])
second = _batch(repository, "2", [(10, 1.0, 0.2, None, None)])
third = _batch(repository, "3", [(10, 1.0, 0.3, None, None)])
repository.change_state(second, "final", "revisado")
pending = repository.pending_batches()
assert [(b.lote_id, b.modelo_version, b.n_evaluaciones) for b in pending] == [(third, "3", 1), (first, "1", 1)]
assert all(isinstance(b, PendingBatch) and b.modelo_nombre == "cacu-cin2_logistic" for b in pending)
repository.change_state(third, "entered-in-error", "modelo equivocado")
assert [b.lote_id for b in repository.pending_batches()] == [first]
-1
View File
@@ -19,7 +19,6 @@ operación, en [`dist/MANUAL.md`](dist/MANUAL.md).
| `WebApp/` (submódulo) | Interfaz en Angular y Angular Material. |
| `models/` (submódulo) | Registro de modelos en MLflow, predicciones y trabajos de OCR de reportes. |
| `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
+1
View File
@@ -7,3 +7,4 @@ uv.lock
package-lock.yml
.venv/
graphify-out/
*.db
+20 -28
View File
@@ -28,6 +28,18 @@ vars:
cie_antecedente: ["D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539"]
horizonte_toma_reporte_dias: 60
horizonte_toma_diagnostico_dias: 180
# Provisional: how long after the sample, and after its diagnosis, a treatment still counts for the times to
# treatment (models/cacu/gold/eventos/cacu_tomas_citologia.sql).
horizonte_toma_tratamiento_dias: 60
horizonte_diagnostico_tratamiento_dias: 60
# Provisional: the windows of the screening route, in days: from the sample to the first colposcopy and to the
# biopsy report, from the cytology result to the colposcopy, from the colposcopy to the biopsy report and from the
# biopsy report to the diagnosis (models/cacu/gold/eventos/cacu_ruta_tamizaje.sql).
horizonte_toma_colposcopia_dias: 60
horizonte_toma_biopsia_dias: 60
horizonte_resultado_colposcopia_dias: 60
horizonte_colposcopia_biopsia_dias: 60
horizonte_biopsia_diagnostico_dias: 60
# ASCCP follow-up (the kit's cacu.seguimiento.*; provisional): what counts as a colposcopy and a treatment
# (models/cacu/silver/cacu_procedimientos_inferidos.sql).
seguimiento:
@@ -56,6 +68,12 @@ vars:
especialidades_diagnostico: ["CIRUGIA_ONCOLOGICA"]
horizonte_toma_diagnostico_dias: 180
birads_gravedad: ["B1", "B2", "B3", "B0", "B4", "B4A", "B4B", "B4C", "B5", "B6"]
# Biopsy grades from least to most severe (models/cama/gold/eventos/cama_resultado_biopsia.sql): the keys of
# cama.catalogos.biopsia.
biopsia_gravedad: ["BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"]
# The grades that count as cancer in the detection rate (models/cama/gold/eventos/cama_deteccion_biopsia.sql): the
# values of the parameter cama.biopsia_cancer (a test keeps them equal).
grados_cancer: ["CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"]
# 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
@@ -76,9 +94,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
@@ -88,31 +105,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"
@@ -0,0 +1,30 @@
{#
The first event of a kind after each start, for the same patient: the building block of a time between two events.
`inicio`: a relation with one row per start, with columns `id`, `pac_id` and the date `fecha`.
`linea`: the patient's timeline (`pac_id`, `fecha`, `conocida_en`, `tipo`).
`tipo`: the timeline kind that ends the interval.
`horizonte_dias`: the event must fall fewer days after the start.
`estricto`: true leaves out an event on the start's own day, false counts it.
One row per start that has such an event: `inicio_id`, `fecha_fin` (its date) and `fin_conocido_en` (when it became
known: the earliest load among the patient's events of that day). The days between are the difference of
`dim_fecha.dia_num`, plain arithmetic that every engine runs. The caller joins on `inicio_id`; a start without a
row has no event in its horizon.
#}
{% macro primer_evento_posterior(inicio, id, fecha, linea, tipo, horizonte_dias, estricto=true) -%}
select p.inicio_id, p.fecha_fin, min(l.conocida_en) as fin_conocido_en
from (
select i.{{ id }} as inicio_id, min(l.fecha) as fecha_fin
from {{ inicio }} i
join {{ linea }} l
on l.pac_id = i.pac_id and l.tipo = '{{ tipo }}' and l.fecha {{ '>' if estricto else '>=' }} i.{{ fecha }}
join {{ source('silver', 'dim_fecha') }} dl on dl.fecha = l.fecha
join {{ source('silver', 'dim_fecha') }} di on di.fecha = i.{{ fecha }}
where dl.dia_num - di.dia_num < {{ horizonte_dias }}
group by i.{{ id }}
) p
join {{ inicio }} i on i.{{ id }} = p.inicio_id
join {{ linea }} l on l.pac_id = i.pac_id and l.tipo = '{{ tipo }}' and l.fecha = p.fecha_fin
group by p.inicio_id, p.fecha_fin
{%- endmacro %}
+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
@@ -0,0 +1,108 @@
-- One row per cytology taken, followed along the screening route: the first colposcopy after the sample, the first
-- biopsy report the sample led to, and the three steps between consecutive events. The sample's own day, whether a
-- cervical cancer note came before it and when the sample and its result became known come from
-- `cacu_tomas_citologia`. Every event is the first of its kind after its start, within its horizon, with when it
-- became known; a step is the days between two of those events. Days are differences of `dim_fecha.dia_num`.
-- colposcopia first `colposcopia` after the sample (`horizonte_toma_colposcopia_dias`)
-- biopsia first biopsy report of the sample (`horizonte_toma_biopsia_dias`)
-- colposcopia_resultado first `colposcopia` from the cytology result on (`horizonte_resultado_colposcopia_dias`)
-- diagnostico_biopsia first `diagnostico` after the biopsy report (`horizonte_biopsia_diagnostico_dias`)
-- The step from the colposcopy to the biopsy report counts when the report falls within
-- `horizonte_colposcopia_biopsia_dias` of that colposcopy.
with colposcopia as (
{{ primer_evento_posterior(ref('cacu_citologias'), 'procedimiento_id', 'fecha_toma', ref('cacu_linea_de_tiempo'),
'colposcopia', var('horizonte_toma_colposcopia_dias')) }}
),
desde_resultado as (
select procedimiento_id, pac_id, fecha_reporte as fecha
from {{ ref('cacu_citologias') }}
where fecha_reporte is not null
),
colposcopia_resultado as (
{{ primer_evento_posterior('desde_resultado', 'procedimiento_id', 'fecha', ref('cacu_linea_de_tiempo'),
'colposcopia', var('horizonte_resultado_colposcopia_dias'), estricto=false) }}
),
-- The biopsy is linked to its sample, not to the patient: the first report of each sample.
primera_biopsia as (
select b.toma_id, min(b.fecha_reporte) as fecha
from {{ ref('cacu_biopsias') }} b
join {{ ref('cacu_citologias') }} c on c.procedimiento_id = b.toma_id
join {{ source('silver', 'dim_fecha') }} db on db.fecha = b.fecha_reporte
join {{ source('silver', 'dim_fecha') }} dt on dt.fecha = c.fecha_toma
where b.fecha_reporte > c.fecha_toma
and db.dia_num - dt.dia_num < {{ var('horizonte_toma_biopsia_dias') }}
group by b.toma_id
),
biopsia as (
select p.toma_id as inicio_id, p.fecha as fecha_fin, min(k.inicio) as fin_conocido_en
from primera_biopsia p
join {{ ref('cacu_biopsias') }} b on b.toma_id = p.toma_id and b.fecha_reporte = p.fecha
join {{ source('silver', 'carga') }} k on k.carga_id = b.reporte_carga_id
group by p.toma_id, p.fecha
),
desde_biopsia as (
select c.procedimiento_id, c.pac_id, bx.fecha_fin as fecha
from {{ ref('cacu_citologias') }} c
join biopsia bx on bx.inicio_id = c.procedimiento_id
),
diagnostico_biopsia as (
{{ primer_evento_posterior('desde_biopsia', 'procedimiento_id', 'fecha', ref('cacu_linea_de_tiempo'),
'diagnostico', var('horizonte_biopsia_diagnostico_dias')) }}
)
select
t.procedimiento_id,
t.fuente_id,
t.pac_id,
t.fecha_toma,
t.toma_conocida_en,
t.resultado_conocido_en,
t.toma_dia,
t.con_antecedente,
dia_reporte.dia_num as reporte_dia,
col.fecha_fin as fecha_colposcopia,
col.fin_conocido_en as colposcopia_conocida_en,
dia_colposcopia.dia_num - t.toma_dia as dias_toma_colposcopia,
bx.fecha_fin as fecha_biopsia,
bx.fin_conocido_en as biopsia_conocida_en,
dia_biopsia.dia_num as biopsia_dia,
dia_biopsia.dia_num - t.toma_dia as dias_toma_biopsia,
cr.fecha_fin as fecha_colposcopia_resultado,
cr.fin_conocido_en as colposcopia_resultado_conocida_en,
dia_colposcopia_resultado.dia_num as colposcopia_resultado_dia,
dia_colposcopia_resultado.dia_num - dia_reporte.dia_num as dias_resultado_colposcopia,
case
when dia_biopsia.dia_num - dia_colposcopia_resultado.dia_num >= 0
and dia_biopsia.dia_num - dia_colposcopia_resultado.dia_num < {{ var('horizonte_colposcopia_biopsia_dias') }}
then dia_biopsia.dia_num - dia_colposcopia_resultado.dia_num
end as dias_colposcopia_biopsia,
db.fecha_fin as fecha_diagnostico_biopsia,
db.fin_conocido_en as diagnostico_biopsia_conocido_en,
dia_diagnostico_biopsia.dia_num - dia_biopsia.dia_num as dias_biopsia_diagnostico
from {{ ref('cacu_tomas_citologia') }} t
join {{ ref('cacu_citologias') }} c on c.procedimiento_id = t.procedimiento_id
left join {{ source('silver', 'dim_fecha') }} dia_reporte
on dia_reporte.fecha = c.fecha_reporte
left join colposcopia col
on col.inicio_id = t.procedimiento_id
left join {{ source('silver', 'dim_fecha') }} dia_colposcopia
on dia_colposcopia.fecha = col.fecha_fin
left join biopsia bx
on bx.inicio_id = t.procedimiento_id
left join {{ source('silver', 'dim_fecha') }} dia_biopsia
on dia_biopsia.fecha = bx.fecha_fin
left join colposcopia_resultado cr
on cr.inicio_id = t.procedimiento_id
left join {{ source('silver', 'dim_fecha') }} dia_colposcopia_resultado
on dia_colposcopia_resultado.fecha = cr.fecha_fin
left join diagnostico_biopsia db
on db.inicio_id = t.procedimiento_id
left join {{ source('silver', 'dim_fecha') }} dia_diagnostico_biopsia
on dia_diagnostico_biopsia.fecha = db.fecha_fin
@@ -0,0 +1,233 @@
version: 2
models:
- name: cacu_ruta_tamizaje
description: "Citologías tomadas, una fila por toma, con la primera colposcopía, el primer reporte de biopsia y los tramos entre eventos consecutivos de la ruta."
config:
materialized: view
semantic_models:
- name: cacu_ruta_tamizaje
description: "Cytologies taken, one row each, followed along the screening route: what the times between its consecutive events count over."
model: ref('cacu_ruta_tamizaje')
defaults:
agg_time_dimension: fecha_toma
entities:
- name: toma_ruta
type: primary
expr: procedimiento_id
- name: paciente
type: foreign
expr: pac_id
dimensions:
- name: fecha_toma
type: time
type_params:
time_granularity: day
- name: toma_conocida_en
type: time
type_params:
time_granularity: day
- name: resultado_conocido_en
type: time
type_params:
time_granularity: day
- name: fecha_colposcopia
type: time
type_params:
time_granularity: day
- name: colposcopia_conocida_en
type: time
type_params:
time_granularity: day
- name: fecha_biopsia
type: time
type_params:
time_granularity: day
- name: biopsia_conocida_en
type: time
type_params:
time_granularity: day
- name: fecha_colposcopia_resultado
type: time
type_params:
time_granularity: day
- name: colposcopia_resultado_conocida_en
type: time
type_params:
time_granularity: day
- name: fecha_diagnostico_biopsia
type: time
type_params:
time_granularity: day
- name: diagnostico_biopsia_conocido_en
type: time
type_params:
time_granularity: day
- name: toma_dia
type: categorical
- name: reporte_dia
type: categorical
- name: con_antecedente
type: categorical
- name: dias_toma_colposcopia
type: categorical
- name: biopsia_dia
type: categorical
- name: dias_toma_biopsia
type: categorical
- name: colposcopia_resultado_dia
type: categorical
- name: dias_resultado_colposcopia
type: categorical
- name: dias_colposcopia_biopsia
type: categorical
- name: dias_biopsia_diagnostico
type: categorical
measures:
- name: citologias_en_ruta
description: "Distinct samples (the source's cytology id): the unit of the times along the route."
agg: count_distinct
expr: fuente_id
metrics:
- name: cacu_dias_toma_colposcopia
label: "Tiempo de toma de muestra a colposcopía"
description: >-
Días naturales de la toma de cada citología del periodo a la primera colposcopía posterior, dentro del horizonte y a la fecha de corte. La colposcopía se infiere de notas, órdenes y biopsias: su fecha es la de la consulta que ocurrió. Se excluyen las citologías de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.
type: simple
type_params:
measure: citologias_en_ruta
filter: "{{ Dimension('toma_ruta__con_antecedente') }} = 0"
config:
meta:
measure_url: cacu/CACU_DIAS_TOMA_COLPOSCOPIA
version: 0.1.0
scoring: continuous-variable
basis: examen
grupo: TOTAL
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [toma_conocida_en]
observacion:
valor: dias_toma_colposcopia
fechada_en: [fecha_colposcopia]
conocida_en: [colposcopia_conocida_en]
horizonte:
dias: "{{ var('horizonte_toma_colposcopia_dias') }}"
dia_inicio: toma_dia
- name: cacu_dias_toma_biopsia
label: "Tiempo de toma de muestra a resultado de biopsia"
description: >-
Días naturales de la toma de cada citología del periodo al primer reporte de la biopsia que esa citología originó, dentro del horizonte y a la fecha de corte. Se excluyen las citologías de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.
type: simple
type_params:
measure: citologias_en_ruta
filter: "{{ Dimension('toma_ruta__con_antecedente') }} = 0"
config:
meta:
measure_url: cacu/CACU_DIAS_TOMA_BIOPSIA
version: 0.1.0
scoring: continuous-variable
basis: examen
grupo: TOTAL
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [toma_conocida_en]
observacion:
valor: dias_toma_biopsia
fechada_en: [fecha_biopsia]
conocida_en: [biopsia_conocida_en]
horizonte:
dias: "{{ var('horizonte_toma_biopsia_dias') }}"
dia_inicio: toma_dia
- name: cacu_dias_resultado_colposcopia
label: "Tiempo del resultado de citología a la colposcopía"
description: >-
Días naturales del resultado de cada citología del periodo a la primera colposcopía desde ese día, dentro del horizonte y a la fecha de corte. Solo entran las citologías con resultado. Se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.
type: simple
type_params:
measure: citologias_en_ruta
filter: "{{ Dimension('toma_ruta__con_antecedente') }} = 0 and {{ Dimension('toma_ruta__reporte_dia') }} is not null"
config:
meta:
measure_url: cacu/CACU_DIAS_RESULTADO_COLPOSCOPIA
version: 0.1.0
scoring: continuous-variable
basis: examen
grupo: TOTAL
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [toma_conocida_en, resultado_conocido_en]
observacion:
valor: dias_resultado_colposcopia
fechada_en: [fecha_colposcopia_resultado]
conocida_en: [colposcopia_resultado_conocida_en]
horizonte:
dias: "{{ var('horizonte_resultado_colposcopia_dias') }}"
dia_inicio: reporte_dia
- name: cacu_dias_colposcopia_biopsia
label: "Tiempo de la colposcopía al resultado de biopsia"
description: >-
Días naturales de la colposcopía posterior al resultado de cada citología del periodo al primer reporte de la biopsia que esa citología originó, dentro del horizonte y a la fecha de corte. Solo entran las citologías con colposcopía. Se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.
type: simple
type_params:
measure: citologias_en_ruta
filter: "{{ Dimension('toma_ruta__con_antecedente') }} = 0 and {{ Dimension('toma_ruta__colposcopia_resultado_dia') }} is not null"
config:
meta:
measure_url: cacu/CACU_DIAS_COLPOSCOPIA_BIOPSIA
version: 0.1.0
scoring: continuous-variable
basis: examen
grupo: TOTAL
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [toma_conocida_en, resultado_conocido_en, colposcopia_resultado_conocida_en]
observacion:
valor: dias_colposcopia_biopsia
fechada_en: [fecha_biopsia]
conocida_en: [biopsia_conocida_en]
horizonte:
dias: "{{ var('horizonte_colposcopia_biopsia_dias') }}"
dia_inicio: colposcopia_resultado_dia
- name: cacu_dias_biopsia_diagnostico
label: "Tiempo del resultado de biopsia al diagnóstico"
description: >-
Días naturales del primer reporte de biopsia de cada citología del periodo a la primera nota médica de diagnóstico posterior, dentro del horizonte y a la fecha de corte. Solo entran las citologías con biopsia reportada. Se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.
type: simple
type_params:
measure: citologias_en_ruta
filter: "{{ Dimension('toma_ruta__con_antecedente') }} = 0 and {{ Dimension('toma_ruta__biopsia_dia') }} is not null"
config:
meta:
measure_url: cacu/CACU_DIAS_BIOPSIA_DIAGNOSTICO
version: 0.1.0
scoring: continuous-variable
basis: examen
grupo: TOTAL
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [toma_conocida_en, biopsia_conocida_en]
observacion:
valor: dias_biopsia_diagnostico
fechada_en: [fecha_diagnostico_biopsia]
conocida_en: [diagnostico_biopsia_conocido_en]
horizonte:
dias: "{{ var('horizonte_biopsia_diagnostico_dias') }}"
dia_inicio: biopsia_dia
@@ -146,6 +146,7 @@ metrics:
grupo: TOTAL
contrato: C2
tipos_periodo: [semestre, mes]
figuras: [fig_c2_donas, fig_c2_barras]
poblaciones_fhir: [measure-observation]
conocida_en: [toma_conocida_en]
parametros:
@@ -172,6 +173,23 @@ metrics:
conocida_en: [biopsia_conocida_en]
orden: [biopsia_gravedad, biopsia_fecha_reporte, biopsia_fuente_id]
sin_seguimiento: SIN_BIOPSIA
# The captions and colours of `cacu.catalogos.biopsia`, least to most severe (WebApi's reference parameters,
# provisional), then the two kept apart: no biopsy reported at the cut-off, and one reported without a grade.
# Groups (provisional): ANORMAL is `deteccion_grados` (dbt var and parameter `cacu.deteccion_grados`), the other
# grades NO_ANORMAL; «Sin biopsia aún» is in no group and «Sin dato» in its own.
etiquetas:
NORMAL: {etiqueta: "Normal", color: "#9DBFE3", grupo: NO_ANORMAL}
LIEBG: {etiqueta: "LIEBG (CIN 1)", color: "#E8C28E", grupo: NO_ANORMAL}
LIEAG: {etiqueta: "LIEAG (CIN 2 y 3)", color: "#D98E4A", grupo: ANORMAL}
CIS: {etiqueta: "Carcinoma in situ", color: "#B55A1F", grupo: ANORMAL}
CARCINOMA: {etiqueta: "Carcinoma invasor", color: "#7A2E0E", grupo: ANORMAL}
SIN_BIOPSIA: {etiqueta: "Sin biopsia aún", color: "#C9CDD2"}
SIN_DATO: {etiqueta: "Biopsia sin grado", color: "#C9CDD2", grupo: SIN_DATO}
# The groups' captions; the no-data group is named as its category.
grupos:
NO_ANORMAL: "Menor que LIEAG"
ANORMAL: "LIEAG o más"
SIN_DATO: "Biopsia sin grado"
estratos:
# The result of that same sample.
citologia_alto_grado:
@@ -3,27 +3,29 @@
-- was known (`toma_conocida_en`) and when its result was (`resultado_conocido_en`, null without a result). The birth
-- date is the patient's, for strata by age. From her timeline: the first note that resolves the sample (a
-- `diagnostico` after it, within `horizonte_toma_diagnostico_dias`), with its days and when it was known, and whether
-- a cervical cancer note (`antecedente`) came before the sample.
-- a cervical cancer note (`antecedente`) came before the sample. The first `tratamiento` after the sample, within
-- `horizonte_toma_tratamiento_dias`, and the first one after that diagnosis, within
-- `horizonte_diagnostico_tratamiento_dias`, each with its days and when it was known.
with resuelve as (
select c.procedimiento_id, min(l.fecha) as fecha_diagnostico
from {{ ref('cacu_citologias') }} c
join {{ ref('cacu_linea_de_tiempo') }} l
on l.pac_id = c.pac_id and l.tipo = 'diagnostico' and l.fecha > c.fecha_toma
join {{ source('silver', 'dim_fecha') }} dl on dl.fecha = l.fecha
join {{ source('silver', 'dim_fecha') }} dt on dt.fecha = c.fecha_toma
where dl.dia_num - dt.dia_num < {{ var('horizonte_toma_diagnostico_dias') }}
group by c.procedimiento_id
with diagnostico as (
{{ primer_evento_posterior(ref('cacu_citologias'), 'procedimiento_id', 'fecha_toma', ref('cacu_linea_de_tiempo'),
'diagnostico', var('horizonte_toma_diagnostico_dias')) }}
),
-- When the first resolving note became known: the earliest load among her notes of that day.
diagnostico as (
select r.procedimiento_id, r.fecha_diagnostico, min(l.conocida_en) as diagnostico_conocido_en
from resuelve r
join {{ ref('cacu_citologias') }} c on c.procedimiento_id = r.procedimiento_id
join {{ ref('cacu_linea_de_tiempo') }} l
on l.pac_id = c.pac_id and l.tipo = 'diagnostico' and l.fecha = r.fecha_diagnostico
group by r.procedimiento_id, r.fecha_diagnostico
tratamiento as (
{{ primer_evento_posterior(ref('cacu_citologias'), 'procedimiento_id', 'fecha_toma', ref('cacu_linea_de_tiempo'),
'tratamiento', var('horizonte_toma_tratamiento_dias')) }}
),
desde_diagnostico as (
select c.procedimiento_id, c.pac_id, dx.fecha_fin as fecha
from {{ ref('cacu_citologias') }} c
join diagnostico dx on dx.inicio_id = c.procedimiento_id
),
tratamiento_del_diagnostico as (
{{ primer_evento_posterior('desde_diagnostico', 'procedimiento_id', 'fecha', ref('cacu_linea_de_tiempo'),
'tratamiento', var('horizonte_diagnostico_tratamiento_dias')) }}
),
primer_antecedente as (
@@ -47,9 +49,16 @@ select
persona.fecha_nacimiento,
dia_toma.dia_num as toma_dia,
dia_reporte.dia_num - dia_toma.dia_num as dias_toma_reporte,
dx.fecha_diagnostico,
dx.diagnostico_conocido_en,
dx.fecha_fin as fecha_diagnostico,
dx.fin_conocido_en as diagnostico_conocido_en,
dia_diagnostico.dia_num - dia_toma.dia_num as dias_toma_diagnostico,
tx.fecha_fin as fecha_tratamiento,
tx.fin_conocido_en as tratamiento_conocido_en,
dia_tratamiento.dia_num - dia_toma.dia_num as dias_toma_tratamiento,
dia_diagnostico.dia_num as diagnostico_dia,
td.fecha_fin as fecha_tratamiento_diagnostico,
td.fin_conocido_en as tratamiento_diagnostico_conocido_en,
dia_tratamiento_dx.dia_num - dia_diagnostico.dia_num as dias_diagnostico_tratamiento,
case when antecedente.fecha < c.fecha_toma then 1 else 0 end as con_antecedente
from {{ ref('cacu_citologias') }} c
join {{ source('silver', 'persona') }} persona
@@ -64,8 +73,16 @@ left join {{ source('silver', 'dim_fecha') }} dia_toma
left join {{ source('silver', 'dim_fecha') }} dia_reporte
on dia_reporte.fecha = c.fecha_reporte
left join diagnostico dx
on dx.procedimiento_id = c.procedimiento_id
on dx.inicio_id = c.procedimiento_id
left join {{ source('silver', 'dim_fecha') }} dia_diagnostico
on dia_diagnostico.fecha = dx.fecha_diagnostico
on dia_diagnostico.fecha = dx.fecha_fin
left join tratamiento tx
on tx.inicio_id = c.procedimiento_id
left join {{ source('silver', 'dim_fecha') }} dia_tratamiento
on dia_tratamiento.fecha = tx.fecha_fin
left join tratamiento_del_diagnostico td
on td.inicio_id = c.procedimiento_id
left join {{ source('silver', 'dim_fecha') }} dia_tratamiento_dx
on dia_tratamiento_dx.fecha = td.fecha_fin
left join primer_antecedente antecedente
on antecedente.pac_id = c.pac_id
@@ -60,6 +60,28 @@ semantic_models:
time_granularity: day
- name: dias_toma_diagnostico
type: categorical
- name: fecha_tratamiento
type: time
type_params:
time_granularity: day
- name: tratamiento_conocido_en
type: time
type_params:
time_granularity: day
- name: dias_toma_tratamiento
type: categorical
- name: diagnostico_dia
type: categorical
- name: fecha_tratamiento_diagnostico
type: time
type_params:
time_granularity: day
- name: tratamiento_diagnostico_conocido_en
type: time
type_params:
time_granularity: day
- name: dias_diagnostico_tratamiento
type: categorical
- name: con_antecedente
type: categorical
measures:
@@ -131,6 +153,7 @@ metrics:
grupo: TOTAL
contrato: C2
tipos_periodo: [semestre, mes]
figuras: [fig_c2_donas, fig_c2_barras]
poblaciones_fhir: [measure-observation]
conocida_en: [toma_conocida_en]
parametros:
@@ -148,6 +171,23 @@ metrics:
fechada_en: [fecha_reporte]
conocida_en: [resultado_conocido_en]
orden: [fecha_toma, fuente_id]
# The captions and colours of `cacu.catalogos.citologia` and `cacu.catalogos.sin_dato` (WebApi's
# reference parameters, provisional), in their order, from least to most severe. Groups (provisional): ANORMAL
# is `citologia_anomala` (dbt var and parameter `cacu.citologia_anomala`), the rest is NO_ANORMAL, and «Sin dato»
# is a group of its own.
etiquetas:
NORMAL: {etiqueta: "Normal", color: "#9DBFE3", grupo: NO_ANORMAL}
ASC-US: {etiqueta: "ASC-US", color: "#2F6DB3", grupo: ANORMAL}
LIEBG: {etiqueta: "LIEBG", color: "#E8C28E", grupo: ANORMAL}
ASC-H: {etiqueta: "ASC-H", color: "#D98E4A", grupo: ANORMAL}
LIEAG: {etiqueta: "LIEAG", color: "#B55A1F", grupo: ANORMAL}
CIS: {etiqueta: "Carcinoma in situ", color: "#7A2E0E", grupo: ANORMAL}
SIN_DATO: {etiqueta: "Sin dato", color: "#C9CDD2", grupo: SIN_DATO}
# The groups' captions; the no-data group is named as its category.
grupos:
NO_ANORMAL: "Sin anomalía"
ANORMAL: "Anormal"
SIN_DATO: "Sin dato"
estratos:
grupo_edad:
tipo: edad_al_inicio_del_periodo
@@ -166,6 +206,14 @@ metrics:
# takes her out.
- {valor: PRE_COLPOSCOPIA, si: [{citologia_de_vigilancia: true}, {citologia: false}]}
resto: INFO_INSUFICIENTE
# The follow-up statuses' captions, as the follow-up list shows them (WebApi follow_up/estratos.toml). Kept
# out of `estratos` on purpose: the strata's spec is part of a report's key and captions don't change answers.
etiquetas_estrato:
estatus_seguimiento:
PRE_COLPOSCOPIA: "Pre colposcopia"
POST_COLPOSCOPIA: "Post colposcopia"
POST_TRATAMIENTO: "Post tratamiento"
INFO_INSUFICIENTE: "Información insuficiente"
- name: cacu_eu_tiempo_reporte
label: "Días de la toma de la citología a su resultado"
description: >-
@@ -185,6 +233,7 @@ metrics:
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [toma_conocida_en]
parametros:
@@ -219,6 +268,7 @@ metrics:
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [toma_conocida_en]
# The first resolving note's days, if it was written by the event cut-off; a sample without one whose
@@ -230,3 +280,69 @@ metrics:
horizonte:
dias: "{{ var('horizonte_toma_diagnostico_dias') }}"
dia_inicio: toma_dia
- name: cacu_dias_toma_tratamiento
label: "Tiempo de tamizaje a tratamiento"
description: >-
Días naturales de la toma de cada citología del periodo al primer tratamiento posterior: una nota médica con un
CIE-10 de tratamiento después de la primera colposcopia de la paciente, dentro del horizonte y a la fecha de
corte. Entran todas las citologías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de
cáncer cervicouterino anterior a la toma. El tratamiento se infiere de la nota: no distingue el indicado del
realizado.
type: simple
type_params:
measure: citologias
filter: "{{ Dimension('toma__con_antecedente') }} = 0"
config:
meta:
measure_url: cacu/CACU_DIAS_TOMA_TRATAMIENTO
version: 0.1.0
scoring: continuous-variable
basis: examen
grupo: TOTAL
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [toma_conocida_en]
# The first treatment's days, if it was written by the event cut-off; a sample without one whose horizon
# hasn't passed by then isn't measured yet. The horizon is the one the model used to find the treatment.
observacion:
valor: dias_toma_tratamiento
fechada_en: [fecha_tratamiento]
conocida_en: [tratamiento_conocido_en]
horizonte:
dias: "{{ var('horizonte_toma_tratamiento_dias') }}"
dia_inicio: toma_dia
- name: cacu_dias_diagnostico_tratamiento
label: "Tiempo de diagnóstico a tratamiento"
description: >-
Días naturales del diagnóstico que resuelve cada citología del periodo al primer tratamiento posterior: una nota
médica con un CIE-10 de tratamiento después de la primera colposcopia de la paciente, dentro del horizonte y a la
fecha de corte. Solo entran las citologías que un diagnóstico resolvió; se excluyen las de pacientes con un
diagnóstico de cáncer cervicouterino anterior a la toma. Dos citologías que resuelve el mismo diagnóstico cuentan
cada una. El tratamiento se infiere de la nota: no distingue el indicado del realizado.
type: simple
type_params:
measure: citologias
filter: "{{ Dimension('toma__con_antecedente') }} = 0 and {{ Dimension('toma__diagnostico_dia') }} is not null"
config:
meta:
measure_url: cacu/CACU_DIAS_DIAGNOSTICO_TRATAMIENTO
version: 0.1.0
scoring: continuous-variable
basis: examen
grupo: TOTAL
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [toma_conocida_en, diagnostico_conocido_en]
observacion:
valor: dias_diagnostico_tratamiento
fechada_en: [fecha_tratamiento_diagnostico]
conocida_en: [tratamiento_diagnostico_conocido_en]
horizonte:
dias: "{{ var('horizonte_diagnostico_tratamiento_dias') }}"
dia_inicio: diagnostico_dia
@@ -0,0 +1,16 @@
-- One row per biopsy report, dated by the report, flagged for the detection rate: `con_resultado` when its grade is one
-- of `vars.cama.biopsia_gravedad` (benign, in situ or invasive; a report without a grade, or with one the catalog doesn't
-- know, has none) and `maligno` when it is one of `vars.cama.grados_cancer` (the keys of the parameter
-- `cama.biopsia_cancer`). The flags are of the model, not rows of the parameter table, so a database that already holds
-- the other CaMa views answers the measure with only this view added.
select
r.procedimiento_id,
r.fuente_id,
r.pac_id,
r.fecha_reporte,
r.grado,
r.reporte_conocido_en,
case when r.grado in {{ sql_list(var('cama')['biopsia_gravedad']) }} then 1 else 0 end as con_resultado,
case when r.grado in {{ sql_list(var('cama')['grados_cancer']) }} then 1 else 0 end as maligno
from {{ ref('cama_reportes_biopsia') }} r
@@ -0,0 +1,88 @@
version: 2
models:
- name: cama_deteccion_biopsia
description: "Reportes de biopsia de mama fechados por el reporte, con las marcas de resultado conocido y de resultado maligno."
config:
materialized: view
semantic_models:
- name: cama_deteccion_biopsia
description: "Breast biopsy reports with the flags of a known and of a malignant result: what the detection rate counts."
model: ref('cama_deteccion_biopsia')
defaults:
agg_time_dimension: fecha_reporte
entities:
- name: biopsia_deteccion
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: con_resultado
type: categorical
- name: maligno
type: categorical
measures:
- name: reportes_de_biopsia
description: "Distinct biopsy reports: each report counts, not each patient."
agg: count_distinct
expr: procedimiento_id
metrics:
- name: cama_tasa_deteccion_histopatologica_denominador
label: "Reportes de biopsia con resultado conocido"
type: simple
type_params:
measure: reportes_de_biopsia
filter: "{{ Dimension('biopsia_deteccion__con_resultado') }} = 1"
config:
meta:
poblaciones_fhir: [initial-population, denominator]
fechada_en: [fecha_reporte]
conocida_en: [reporte_conocido_en]
- name: cama_tasa_deteccion_histopatologica_numerador
label: "De ellos, con resultado maligno"
type: simple
type_params:
measure: reportes_de_biopsia
filter: "{{ Dimension('biopsia_deteccion__maligno') }} = 1"
config:
meta:
poblaciones_fhir: [numerator]
fechada_en: [fecha_reporte]
conocida_en: [reporte_conocido_en]
- name: cama_tasa_deteccion_histopatologica
# dbt wants labels unique in the project; the title on screen is `meta.titulo`.
label: "CaMa: tasa de detección histopatológica"
description: >-
De los reportes de biopsia de mama fechados en el periodo con un resultado conocido (benigno, carcinoma in situ o
carcinoma invasor), cuántos son malignos (carcinoma in situ o invasor). La unidad es el reporte de biopsia, no la
paciente; los reportes sin grado no entran. Es una proporción entre las biopsias con resultado: no es una tasa
sobre las mujeres tamizadas ni la proporción de mastografías de sospecha que tienen biopsia
(CAMA_CONFIRMACION_BIRADS45).
type: ratio
type_params:
numerator: cama_tasa_deteccion_histopatologica_numerador
denominator: cama_tasa_deteccion_histopatologica_denominador
config:
meta:
measure_url: cama/CAMA_TASA_DETECCION_HISTOPATOLOGICA
titulo: "Tasa de detección histopatológica"
version: 0.1.0
scoring: proportion
basis: examen
grupo: principal
contrato: C1
tipos_periodo: [semestre, mes]
@@ -56,6 +56,7 @@ metrics:
grupo: TOTAL
contrato: C2
tipos_periodo: [semestre, mes]
figuras: [fig_c2_donas, fig_c2_barras]
poblaciones_fhir: [measure-observation]
conocida_en: [reporte_conocido_en]
# One row per report: its grade.
@@ -65,3 +66,10 @@ metrics:
elige: ultimo_valido
valido: "{% raw %}{{ Dimension('biopsia__grado') }} is not null{% endraw %}"
orden: [fecha_reporte]
# The captions and colours of `cama.catalogos.biopsia` and `cama.catalogos.sin_dato`. A grade outside them
# (DESCONOCIDO) is published as it comes.
etiquetas:
BENIGNO: {etiqueta: "Benigno", color: "#9DBFE3"}
CARCINOMA_IN_SITU: {etiqueta: "Carcinoma in situ", color: "#D98E4A"}
CARCINOMA_INVASOR: {etiqueta: "Carcinoma invasor", color: "#7A2E0E"}
SIN_DATO: {etiqueta: "Sin dato", color: "#C9CDD2"}
@@ -0,0 +1,44 @@
-- 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 cross a mammogram's BI-RADS with the result of its biopsy. A biopsy counts for the mammogram that
-- led to it (mammogram -> biopsy order -> biopsy report), of the same patient. When each became known: the start of the
-- loads that wrote them. `biopsia_gravedad` orders a patient's biopsies from least to most severe by
-- `vars.cama.biopsia_gravedad`: 0 for a grade the catalog doesn't know, -1 for a report without one, null when the
-- mammogram led to none. `birads_gravedad` orders BI-RADS as `cama_tomas_mastografia` does.
{% set r = var('cama') %}
select
m.procedimiento_id,
m.fuente_id,
m.pac_id,
m.fecha_toma,
toma.inicio as toma_conocida_en,
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,
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 r['biopsia_gravedad'] %}
when b.grado = '{{ grado }}' then {{ loop.index }}
{%- endfor %}
else 0
end as biopsia_gravedad,
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,120 @@
version: 2
models:
- name: cama_resultado_biopsia
description: "Mastografías con su reporte y el grado de cada biopsia que originaron, con cuándo se supo de cada uno."
config:
materialized: view
semantic_models:
- name: cama_resultado_biopsia
description: "Mammograms with their BI-RADS and the grade of the biopsies they led to: what the histopathological result by BI-RADS counts over."
model: ref('cama_resultado_biopsia')
defaults:
agg_time_dimension: fecha_toma
entities:
- name: mastografia_biopsia
type: primary
expr: "procedimiento_id || '-' || coalesce(fecha_reporte, '') || '-' || coalesce(biopsia_fuente_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: 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
- name: birads_gravedad
type: categorical
- name: biopsia_grado
type: categorical
- name: biopsia_gravedad
type: categorical
- name: biopsia_fuente_id
type: categorical
- name: fuente_id
type: categorical
measures:
- name: pacientes_con_mastografia_birads
description: "Distinct patients: each counts once per period, however many mammograms or biopsies."
agg: count_distinct
expr: pac_id
metrics:
- name: cama_histopatologia_birads
label: "CaMa: resultado histopatológico por categoría BI-RADS"
description: >-
De las pacientes con una mastografía del periodo con BI-RADS 4, 5 o 6 reportado, cada una en la más grave de sus
mastografías (la misma regla de CAMA_BIRADS456_PACIENTE), cuántas tienen cada resultado en la biopsia que esa
mastografía originó y que se reportó a la fecha de corte (la más grave; entre iguales, la más reciente), por
categoría BI-RADS. «Sin biopsia reportada»: la mastografía no tiene biopsia reportada al corte; «Sin dato»: la
biopsia no trae grado. A la fecha de corte, sin un plazo máximo: una paciente «sin biopsia» puede pasar a un
resultado mientras lleguen reportes.
type: simple
type_params:
measure: pacientes_con_mastografia_birads
config:
meta:
measure_url: cama/CAMA_HISTOPATOLOGIA_BIRADS
titulo: "Resultado histopatológico por categoría BI-RADS"
version: 0.1.0
scoring: composition
basis: paciente
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: biopsia_grado
sin_dato: SIN_DATO
elige: mas_grave
valido: "{% raw %}{{ Dimension('mastografia_biopsia__birads') }} is not null{% endraw %}"
fechada_en: [fecha_reporte]
conocida_en: [reporte_conocido_en]
orden: [birads_gravedad, fuente_id]
admite: "{% raw %}{{ Dimension('mastografia_biopsia__birads') }} in :birads_4_a_6{% 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
# The captions and colours of cama.catalogos.biopsia and cama.catalogos.sin_dato; a grade outside them is
# published as it comes.
etiquetas:
BENIGNO: {etiqueta: "Benigno", color: "#9DBFE3"}
CARCINOMA_IN_SITU: {etiqueta: "Carcinoma in situ", color: "#D98E4A"}
CARCINOMA_INVASOR: {etiqueta: "Carcinoma invasor", color: "#7A2E0E"}
SIN_BIOPSIA: {etiqueta: "Sin biopsia reportada", color: "#C9CDD2"}
SIN_DATO: {etiqueta: "Sin dato", color: "#C9CDD2"}
estratos:
# The BI-RADS of the mammogram that gave the patient her place.
birads:
tipo: del_elegido
etiqueta: Categoría BI-RADS
valor: birads
@@ -0,0 +1,73 @@
-- One row per mammogram that has a report: the grain of the time from the mammogram's result to the diagnosis. No
-- period and no cut-off here: they're the question's. The diagnosis is the first diagnosing note of the patient dated
-- on or after the report (a `diagnostico` of the patient's timeline: a diagnosis ICD-10 of `cama.cie_diagnostico`
-- written by a specialty of `cama.especialidades_diagnostico`) and within the horizon of the report. It is a note of
-- the patient, not a link to this mammogram's episode: the notes carry no episode. It is not the date of a biopsy.
-- Days are differences of `dim_fecha.dia_num`. When the report and the note became known: the start of the loads that
-- wrote them. A breast cancer note (`antecedente`) before the mammogram leaves it out, as in the time from the
-- mammogram to the diagnosis.
{% set r = var('cama') %}
-- One observation per mammogram: its earliest dated report, ties by the report's platform identity.
-- Later corrections do not move the observation to another period or duplicate it.
with ordenadas as (
select procedimiento_id, fuente_id, pac_id, fecha_toma, fecha_reporte, reporte_carga_id,
row_number() over (partition by procedimiento_id order by fecha_reporte, reporte_id, reporte_carga_id) as lugar
from {{ ref('cama_mastografias') }}
where reporte_id is not null and fecha_reporte is not null
),
reportada as (
select procedimiento_id, fuente_id, pac_id, fecha_toma, fecha_reporte, reporte_carga_id
from ordenadas where lugar = 1
),
resuelve as (
select m.procedimiento_id, min(l.fecha) as fecha_diagnostico
from reportada m
join {{ ref('cama_linea_de_tiempo') }} l
on l.pac_id = m.pac_id and l.tipo = 'diagnostico' and l.fecha >= m.fecha_reporte
join {{ source('silver', 'dim_fecha') }} dl on dl.fecha = l.fecha
join {{ source('silver', 'dim_fecha') }} dr on dr.fecha = m.fecha_reporte
where dl.dia_num - dr.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 reportada 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,
m.fecha_reporte,
reporte.inicio as reporte_conocido_en,
dia_reporte.dia_num as reporte_dia,
dx.fecha_diagnostico,
dx.diagnostico_conocido_en,
dia_diagnostico.dia_num - dia_reporte.dia_num as dias_reporte_diagnostico,
case when antecedente.fecha < m.fecha_toma then 1 else 0 end as con_antecedente
from reportada m
join {{ source('silver', 'carga') }} reporte
on reporte.carga_id = m.reporte_carga_id
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,87 @@
version: 2
models:
- name: cama_resultado_diagnostico
description: "Mastografías con reporte y la primera nota diagnóstica de la paciente a partir de ese reporte, con sus fechas y su conocimiento."
config:
materialized: view
semantic_models:
- name: cama_resultado_diagnostico
description: "Mammograms with a report and the first diagnosing note on or after it: what the time from result to diagnosis counts."
model: ref('cama_resultado_diagnostico')
defaults:
agg_time_dimension: fecha_reporte
entities:
- name: resultado_diagnostico
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_diagnostico
type: time
type_params:
time_granularity: day
- name: diagnostico_conocido_en
type: time
type_params:
time_granularity: day
- name: reporte_dia
type: categorical
- name: dias_reporte_diagnostico
type: categorical
- name: con_antecedente
type: categorical
- name: fuente_id
type: categorical
measures:
- name: mastografias_con_reporte
description: "Distinct mammograms by platform procedure identity, through their earliest report."
agg: count_distinct
expr: procedimiento_id
metrics:
- name: cama_dias_resultado_diagnostico
label: "CaMa: tiempo de resultado a diagnóstico"
description: >-
Días naturales del reporte de cada mastografía fechado en el periodo a la primera nota médica diagnóstica de la
paciente a partir de ese reporte: 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. La nota es de la
paciente, no está ligada a la mastografía (las notas no traen episodio) y no es la fecha de la biopsia. Las
mastografías sin nota en el horizonte no se miden. Se excluyen las de pacientes con un diagnóstico de cáncer de
mama anterior a la toma.
type: simple
type_params:
measure: mastografias_con_reporte
filter: "{{ Dimension('resultado_diagnostico__con_antecedente') }} = 0"
config:
meta:
measure_url: cama/CAMA_DIAS_RESULTADO_DIAGNOSTICO
titulo: "Tiempo de resultado a diagnóstico"
version: 0.1.0
scoring: continuous-variable
basis: examen
grupo: TOTAL
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [reporte_conocido_en]
observacion:
valor: dias_reporte_diagnostico
fechada_en: [fecha_diagnostico]
conocida_en: [diagnostico_conocido_en]
horizonte:
dias: "{{ var('cama')['horizonte_toma_diagnostico_dias'] }}"
dia_inicio: reporte_dia
@@ -88,6 +88,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]
# Each patient's most severe BI-RADS among her mammograms of the period reported by the cut-off; one without a
@@ -100,6 +101,19 @@ metrics:
fechada_en: [fecha_reporte]
conocida_en: [reporte_conocido_en]
orden: [birads_gravedad, fuente_id]
# The captions and colours of `cama.catalogos.birads` and `cama.catalogos.sin_dato`, in their order. A BI-RADS 4
# without subcategory is no declared category: a report that counts one publishes it as it comes.
etiquetas: &etiquetas_birads
B0: {etiqueta: "BI-RADS 0", color: "#8A9199"}
B1: {etiqueta: "BI-RADS 1", color: "#9DBFE3"}
B2: {etiqueta: "BI-RADS 2", color: "#2F6DB3"}
B3: {etiqueta: "BI-RADS 3", color: "#E8C28E"}
B4A: {etiqueta: "BI-RADS 4A", color: "#E0A060"}
B4B: {etiqueta: "BI-RADS 4B", color: "#CF7D3C"}
B4C: {etiqueta: "BI-RADS 4C", color: "#C26A2B"}
B5: {etiqueta: "BI-RADS 5", color: "#B55A1F"}
B6: {etiqueta: "BI-RADS 6", color: "#7A2E0E"}
SIN_DATO: {etiqueta: "Sin dato", color: "#C9CDD2"}
- name: cama_birads_456_paciente
label: "Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6"
description: >-
@@ -124,6 +138,13 @@ metrics:
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 %}"
# `cama.catalogos.birads_4_a_6`: what `admite` lets through, so no «Sin dato».
etiquetas: &etiquetas_birads_4_a_6
B4A: {etiqueta: "BI-RADS 4A", color: "#E0A060"}
B4B: {etiqueta: "BI-RADS 4B", color: "#CF7D3C"}
B4C: {etiqueta: "BI-RADS 4C", color: "#C26A2B"}
B5: {etiqueta: "BI-RADS 5", color: "#B55A1F"}
B6: {etiqueta: "BI-RADS 6", color: "#7A2E0E"}
- 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."
@@ -140,6 +161,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:
@@ -152,6 +174,7 @@ metrics:
fechada_en: [fecha_reporte]
conocida_en: [reporte_conocido_en]
orden: [birads_gravedad]
etiquetas: *etiquetas_birads_4_a_6
- name: cama_eu38a
label: "Días de la toma de la mastografía a su resultado"
description: >-
@@ -171,6 +194,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:
@@ -204,6 +228,7 @@ metrics:
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [toma_conocida_en]
observacion:
@@ -0,0 +1,7 @@
version: 2
# Views the WebApi reads, not measures: the cycle creates them with the event models (`lee_la_webapi`).
models:
- name: cama_cohorte_birads
description: "Mastografías con BI-RADS reportado y los reportes de biopsia que originaron: los candidatos de la cohorte BI-RADS de la lista de seguimiento."
config: {materialized: view, meta: {lee_la_webapi: true}}
@@ -0,0 +1,27 @@
-- The candidates of the BI-RADS cohort for the follow-up list: one row per mammogram with a reported BI-RADS and
-- each biopsy report that mammogram led to (one row with nulls when it led to none). The cohort itself depends on the
-- cut-off asked for (each patient's latest mammogram reported by it, kept when its BI-RADS is 4 to 6), and a view takes
-- no parameter, so the WebApi picks the rows by date as it does for the other follow-up lists. Nothing here is
-- derived from a rule that isn't in silver: dates and codes are the source's.
select
m.pac_id,
m.procedimiento_id,
m.fuente_id,
m.fecha_toma,
m.reporte_id,
m.fecha_reporte,
m.birads,
p.fecha_nacimiento,
b.procedimiento_id as biopsia_id,
b.fuente_id as biopsia_fuente_id,
b.fecha_reporte as biopsia_fecha_reporte,
b.grado as biopsia_grado
from {{ ref('cama_mastografias') }} m
join {{ source('silver', 'persona') }} p
on p.pac_id = m.pac_id
left join {{ ref('cama_biopsias') }} b
on b.toma_id = m.procedimiento_id and b.pac_id = m.pac_id
where m.birads is not null
and m.fecha_toma is not null
and m.fecha_reporte is not null
@@ -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
@@ -11,9 +11,12 @@ models:
- 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_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)."
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}}
@@ -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, 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, valor_z, estado
from {{ ref('tea_eeg_metricas') }}
@@ -1,18 +1,8 @@
-- 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, 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, nivel, fraccion_limpia, canales_malos,
ruido_linea_db, calidad, valido
from {{ ref('tea_eegs') }}
@@ -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,50 @@
/* 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`). 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 %}
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 %})
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,
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 %}
+14 -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. */
with valores as (
select
@@ -14,12 +9,14 @@ 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.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 +27,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: 73cbf0cfb8...c2b18d9969
+1 -1
Submodule WebApp updated: bb2f49be37...bb957ec6a4
+7
View File
@@ -36,11 +36,18 @@ WEBAPI_SQL_ALLOWED_DIALECTS=mysql,mariadb,postgresql,mssql
WEBAPI_REPORT_MIN_COUNT=5
# --- Indicadores en vivo ---
# Las medidas se compilan al arrancar contra las bases de arriba cuando no son
# SQLite (dbt); el resultado queda en ISSSTELEON_DATOS/dbt/. No hay nada que
# configurar aquí.
# Años de los periodos que se calculan (por omisión, los últimos 5 años).
# INDICADORES_DESDE=2021
# 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
+50 -3
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
@@ -255,8 +261,49 @@ arma la cohorte de vigilancia. Al final revisa la integridad de lo cargado.
pasos de cada corrida.
Las definiciones de los indicadores (qué cuenta como caso, ventanas, cortes)
son del equipo clínico y viven en `indicadores_kit`; la aplicación solo las
ejecuta.
son del equipo clínico y viven en `Transformation/` (la capa semántica de
dbt); la aplicación solo las ejecuta.
### 6.1 Cómo se calculan
Las medidas están definidas en dbt (`Transformation/`). La imagen trae esas
definiciones compiladas para SQLite; cuando las bases están en MySQL/MariaDB,
PostgreSQL o SQL Server, `webapi` e `indicadores` las compilan al arrancar
contra las bases configuradas y las guardan en `ISSSTELEON_DATOS/dbt/`. Sin
esa compilación la API no publica indicadores: si `Indicadores` dice que no
pudo cargarlos, revise `docker compose logs webapi` al inicio.
Cada corrida crea las vistas que las medidas leen, arma la cohorte de
vigilancia de CaCu y, si hay un modelo en producción, estima el riesgo de
cada paciente de la cohorte. Las respuestas se calculan al consultarlas y se
guardan con su corte, así que una pregunta repetida no vuelve a calcular.
### 6.2 El modelo de CaCu
El riesgo individual (ficha de la paciente y lista de seguimiento) necesita
una versión del modelo `cacu-cin2_logistic` en producción. Después de la
primera carga, entrénela una vez, desde Gobernanza → Versiones de modelo →
**Entrenar cacu/cin2_logistic** (o, con acceso a la línea de comandos del
servidor, `docker compose run --rm entrenar`; ambos corren el mismo
entrenamiento). Exporta la cohorte armada, entrena con ella, registra la
versión en MLflow (dentro de `ISSSTELEON_DATOS`) y la pone en producción; si
ya existía una versión entrenada con esa cohorte, no hace nada. Si la versión
entrenada no tiene aún sus reportes de validación adjuntos, se queda
entrenada pero no en producción: adjúntelos desde el detalle de la versión y
promuévala desde ahí.
Desde entonces cada corrida del servicio `indicadores` escribe un lote de
riesgos **preliminar**. Los riesgos se muestran solo cuando alguien confirma
el lote, desde Gobernanza → **Lotes de riesgo** (confirmar o anular, con un
motivo), o con acceso a la línea de comandos:
```sh
docker compose exec webapi uv run --no-sync python -m webapi.orchestration confirm-risks cacu <lote_id> --reason "revisado por clínica"
```
El `lote_id` aparece en la corrida (`reportes/indicadores.jsonl`, paso
`estimate`) y en la pestaña de Gobernanza. `--void` anula un lote en vez de
confirmarlo.
## 7. Datos, respaldos y reinstalación
+12
View File
@@ -44,6 +44,18 @@ services:
webapi:
condition: service_healthy
# One-shot (`docker compose run --rm entrenar`): exports the latest CaCu
# surveillance cohort build, trains cin2_logistic on it and puts that version
# in production, so the `indicadores` service estimates risks on each cycle.
# Run it after the first load; it's a no-op once the version is trained.
entrenar:
<<: *api
profiles: [entrenar]
command: ["entrenar"]
depends_on:
webapi:
condition: service_healthy
notebooks:
image: isssteleon/webapi:${ISSSTELEON_VERSION}
command: ["notebooks"]
+1 -1
View File
@@ -178,7 +178,7 @@ cmd_construir() {
opciones=""
[ -n "$PLATAFORMA" ] && opciones="--platform $PLATAFORMA"
[ -f "$RAIZ/WebApi/Dockerfile" ] && [ -f "$RAIZ/indicadores_kit/pyproject.toml" ] \
[ -f "$RAIZ/WebApi/Dockerfile" ] && [ -f "$RAIZ/Transformation/dbt_project.yml" ] \
|| error "corra este comando desde dist/ dentro del repositorio completo (con submódulos)."
aviso "isssteleon/webapi:$VERSION"
+12
View File
@@ -41,6 +41,18 @@ services:
webapi:
condition: service_healthy
# One-shot (`docker compose run --rm entrenar`): exports the latest CaCu
# surveillance cohort build, trains cin2_logistic on it and puts that version
# in production, so the `indicadores` service estimates risks on each cycle.
# Run it after the first load; it's a no-op once the version is trained.
entrenar:
<<: *api
profiles: [entrenar]
command: ["entrenar"]
depends_on:
webapi:
condition: service_healthy
# Runs the notebooks uploaded from Gobernanza, isolated: no network, a
# read-only system, an unprivileged user and only the jobs folder. Same
# image as webapi; the jobs folder must be mounted at the same path in both.
+57
View File
@@ -0,0 +1,57 @@
# CaMa L1–L3 integration with dev
Prepared from ISSSTELEON dev `8885162147552cf57f4196c27a0152a07c08de48`,
WebApi dev `0571b5e6af6005737d918997f1f13daec5b4be16` and
WebApp dev `dc37c5493801f40f43cb0a67452b15ad2392b650`.
The existing model submodule and dev changes to governance, risk batches, cohort persistence and training are retained.
The local 18092 deployment and its images/data are not changed by these commits.
## Reconciled contracts
- The L1 follow-up and L2 descriptive blueprints are the only CaMa handlers registered by `create_app`.
The former `webapi/cama_analysis.py` is renamed to `cama_analysis_legacy.py` to avoid colliding with the new package.
Its explicit Python blueprint consumers remain compatible through package exports; legacy tests remain active.
An explicit `CAMA_COHORT_READER` override (including disabling it) retains dev's previous list/detail/aggregate
contract. The marked historical default selects the new production implementation. New descriptive sections require
the dbt views and are not provided by the old reader override.
- `/cama/pacientes/<pac_id>` is retained and uses the new follow-up selection, revision and suppression, returning `item`.
It returns 404 for a patient outside that selection. It does not bypass suppression by looking up a patient first.
- The existing optional `CAMA_COHORT_ACCESS` callback is retained for both new blueprints. There is no new auth mechanism.
- Clients must refresh the cohort context after upgrading; former revision hashes will produce 409.
The new age/filter options come from platform parameters; consumers should use the advertised options.
- CaMa defines its three new FHIR measures once, for both Resumen and Historico.
Clinical definitions and synthetic-data scope remain in `WebApi/docs/cama-*.md`.
## Deployment dependencies (not executed here)
The WebApi and WebApp commits must be available in their repositories before publishing the parent gitlink commit.
No push or remote deployment is part of this integration.
Compile dbt from the same parent revision used to build WebApi. On an existing database, arrange a separately approved
and backed-up view update before enabling the new pages: `cama_cohorte_birads` and the three L3 event views
(`cama_deteccion_biopsia`, `cama_resultado_biopsia`, `cama_resultado_diagnostico`). The normal event-model cycle
can create these views, but affects additional domain views and must not be invoked casually on a live deployment.
Follow-up/analysis return 503 when the cohort view is absent. These measures require no new Alembic migration.
FHIR reads can persist new reports and their units/strata. Existing CaCu reports are not deleted or recomputed:
the shared knowledge-date correction changes new composition calculations, while old stored results remain as stored.
Agree any historical recomputation separately. Aggregated FHIR small cells remain unsuppressed; real-data security
and disclosure policy remain separate prerequisites.
Local 18092-specific scripts, backups, logs, image IDs and absolute host paths are deliberately not product commits.
Validate with a compiled `DBT_MANIFEST`, the WebApi pytest suite (external MySQL tests require their own server),
`npm test -- --watch=false` and `npm run build` in WebApp. Record environment-specific logs outside the product tree.
## Integration validation (2026-11-17)
Based on remote dev: parent `8885162147552cf57f4196c27a0152a07c08de48`,
WebApi `0571b5e6af6005737d918997f1f13daec5b4be16`, WebApp `dc37c5493801f40f43cb0a67452b15ad2392b650`.
All three refs were checked again after the integration work and had not advanced.
- WebApi: 681 passed, with five dependency warnings; the two external-MySQL test files were excluded.
Covers legacy and new CaMa routes, optional access and reader overrides, individual selection, governance/risk batches,
CaCu and TEA. Tests used disposable container databases, without production volumes.
- WebApp: 1785 passed; the six known `saved-sql-connections.spec.ts` failures remain caused by unavailable
`localStorage` in Node 26. No other failures. Production build succeeded (known CommonJS warnings).
- No changes were deployed, no stored reports were recomputed, and no push was performed.
+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"
Submodule indicadores_kit deleted from f79e8d2bc2
+1 -1
Submodule models updated: 572b7561fa...200cb106e1