Compare commits

..

105 Commits

Author SHA1 Message Date
Angel Capetillo Zavala 15a1f095d0 Update breast analysis dashboard 2026-11-14 08:12:24 -06:00
Angel Capetillo Zavala 3b442d89a2 Integrate patient identity across follow-up 2026-11-13 18:24:00 -06:00
Angel Capetillo Zavala ec6d3e6cd7 Pin the verified breast dashboard merge 2026-11-13 15:46:03 -06:00
Angel Capetillo Zavala f922209269 Update breast dashboard integration 2026-11-13 15:44:08 -06:00
Angel Capetillo Zavala d867892379 Compose persistent synthetic breast follow-up 2026-11-13 15:18:14 -06:00
Angel Capetillo Zavala 8c9949ff35 Update CaMa analysis and follow-up components 2026-11-13 14:36:51 -06:00
Angel Capetillo Zavala f1628f4387 Update WebApp 2026-11-13 00:02:02 -06:00
Angel Capetillo Zavala 4e0d43a5e1 Update breast cancer follow-up application components 2026-11-12 22:40:34 -06:00
Angel Capetillo Zavala 1c72366ac8 Update CaMa dashboard presentation 2026-11-12 13:20:50 -06:00
Angel Capetillo Zavala 0f6da3d7db Pin integrated CaMa dashboard components 2026-11-12 12:17:02 -06:00
Angel Capetillo Zavala 175914891a chore: integrate WebApp history and indicators shell 2026-11-12 01:49:44 -06:00
Angel Capetillo Zavala 056ce791d8 chore: update WebApp CaMa dashboard integration 2026-11-12 00:40:05 -06:00
Angel Capetillo Zavala 907a8ce540 chore: update WebApp dashboard-test pointer 2026-11-11 23:59:53 -06:00
Angel Capetillo Zavala 621aafb6eb Pin models to dev revision 2026-11-11 20:44:25 -06:00
Roberto Treviño Cervantes 2188d7a5e8 Submodule pointers: WebApi and indicadores_kit at their dev with import files in columns 2026-11-11 11:20:13 -06:00
Roberto Treviño Cervantes d8ff604b6f import files in columns 2026-11-11 11:19:41 -06:00
edgar a69db40067 Merge pull request 'Persistance: cohort membership and current risks; models, WebApi and indicadores_kit pointers' (#10) from feature/model-proto into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/10
2026-11-06 15:06:53 +00:00
edgar e27a5da077 indicadores_kit: README with BIRTH_DATE 2026-11-06 08:46:21 -06:00
edgar 7e4c643c4d indicadores_kit: staging patients in tests get a birth date 2026-11-06 08:33:52 -06:00
edgar 4a30d64193 models and WebApi: the CIN2+ prototype, risk batches stored and served, report eda, cohorts list and show 2026-11-06 08:29:05 -06:00
edgar a31d987548 Persistance: a patient's membership in a cohort's latest build and risks in the current confirmed batch 2026-11-06 08:21:52 -06:00
angel c6c8bdf3f8 Merge pull request 'chore: update WebApi submodule to latest dev' (#9) from fix/webapi-lock-gitlink into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/9
2026-11-06 06:23:25 +00:00
Angel Capetillo Zavala 6ff683ad80 chore: update WebApi submodule to latest dev 2026-11-06 00:21:10 -06:00
edgar a43f41727e Merge pull request 'Feature/model proto' (#8) from feature/model-proto into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/8
2026-11-06 05:38:58 +00:00
edgar af7ed4495a Persistance reads dbt's timeline view and compiled queries; Transformation: the CaCu surveillance cohort as one query per rule 2026-11-05 16:12:23 -06:00
edgar a377ed0eaf Submodules: models and WebApi at their merged dev 2026-11-04 13:38:25 -06:00
edgar 4e7b5701e5 Merge pull request 'Core: docstring points to models.io.registry' (#7) from feature/model-proto into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/7
2026-11-04 19:13:40 +00:00
edgar ef1fd82a42 Core: docstring points to models.io.registry 2026-11-04 12:48:41 -06:00
edgar 92c46e4f78 Merge pull request 'Feature/model proto' (#6) from feature/model-proto into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/6
2026-11-04 18:15:22 +00:00
edgar 9b9b4b7f8b Submodules: models and WebApi at their merged dev 2026-11-04 12:12:20 -06:00
edgar 924c5f17a3 Merge pull request 'Feature/model proto' (#5) from feature/model-proto into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/5
2026-11-04 17:36:58 +00:00
edgar 3b024f5314 Persistance: CohorteRepository.builds lists the builds, newest first 2026-11-04 09:23:37 -06:00
edgar 90c083e305 Transformation: the timeline as a view from each domain's declared sources, equal to the kit's in the three domains 2026-11-04 02:03:49 +00:00
edgar 55ee3cfba7 Transformation: one silver source shared by the three domains; dbt_utils no longer used 2026-11-04 02:03:49 +00:00
edgar 2f210c4797 Transformation: renamed from Transformacion; models per project in silver and gold, one folder per indicator family 2026-11-04 01:42:28 +00:00
edgar 0d12c73d15 Transformacion: SQL Server through the mssql-python driver, without system ODBC libraries 2026-11-04 01:31:29 +00:00
edgar 5370805886 Transformacion: date_literal, as_text and as_integer, MySQL's datediff, typed output of tiempo_reporte and a unit test of datediff 2026-11-04 01:31:29 +00:00
edgar 01d0f11dfb Transformacion: the CIE lists as variables instead of seeds; dbt creates only views 2026-11-04 01:23:47 +00:00
edgar db2a7804d0 Transformacion: intermediates compiled as CTEs over silver's tables; only the timeline and the marts are created 2026-11-04 01:22:51 +00:00
edgar 69896d641a Transformacion: datediff arguments in order, biopsies linked to their cytology through the order, cytology id as procedimiento_id 2026-11-04 01:11:21 +00:00
edgar 5b6e701310 Transformacion: SQLite variants of generate_schema_name and datediff 2026-11-04 01:11:21 +00:00
edgar 29c9963e5d Transformacion: the intermediates read silver's procedimiento and observacion_clinica; the staging views over bronze are removed 2026-11-04 01:11:21 +00:00
edgar f5819efa7a Transformacion: dbt-core in one group per engine (sqlite, sqlserver, postgres on 1.12; mysql on 1.7) and one profile per domain 2026-11-04 01:02:20 +00:00
Klingsor0 b5a53c587f feat(Transformacion): marts CaCu IND1, TIEMPO_REPORTE, DIAS_TOMA_DIAGNOSTICO y schema_marts
- int_cacu_notas: pivot columnar desde int_cacu_procedimiento/observacion (silver, no bronze)
- mart_cacu_ind1: C1 tamizadas con resultado anómalo
- mart_cacu_tiempo_reporte: C3r días toma→reporte con horizonte y pendiente
- mart_cacu_dias_toma_diagnostico: C3r días toma→nota diagnóstico, join-based (workaround SQLite 3.40)
- stg_cacu_nota_medica_{proc,obs}: refactor; clasificacion de tipo_nota via seeds (no CASE hardcodeado)
- seeds cacu: seed_cacu_nota_cie (es_diagnostico, es_antecedente), seed_cacu_nota_especialidad (prioridad)
- dbt_project.yml: vars citologia_anomala, especialidades_diagnostico, horizontes; marts → view; seeds schema
- schema_marts.yml: meta FHIR (measure_url, contrato, parametros, poblaciones) para los seis marts CaCu

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-11-04 01:00:01 +00:00
Klingsor0 f68babec98 feat(Transformacion): marts CaCu EU7, EU13 y CONFIRMACION_CITOLOGIA
Tres modelos gold para CaCu, traducidos del SQLAlchemy de indicadores_kit
a SQL puro sobre la capa plata:

- mart_cacu_eu7: distribución de resultados citológicos; último resultado
  válido por paciente en el periodo (mismo criterio de validez que EU7).
- mart_cacu_eu13: detección histopatológica; denominador = tamizadas,
  numerador = con biopsia confirmada (deteccion_grados) ligada por toma_id.
- mart_cacu_confirmacion_citologia: colposcopia → biopsia; población =
  alto grado, categoría = grado más grave de biopsia (orden catalogo_biopsia).

Los tres leen únicamente de int_cacu_citologias e int_cacu_biopsias (plata);
ninguno toca bronze. Parámetros de corrida y catálogo declarados en
dbt_project.yml como vars con valores por defecto sobreescribibles.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-11-04 01:00:01 +00:00
Klingsor0 b20cd02709 feat(Transformacion): directorio dbt para la capa de transformación CaCu
Staging e intermedio de CaCu movidos desde indicadores_kit/dbt (feature/dbt-trial).
Los modelos de staging mapean las tablas bronce (citologia_cervical, biopsia_cervical,
nota_medica, ordenes_estudio) a filas de observacion/procedimiento genéricos; los
intermedios las consolidan en int_cacu_observacion, int_cacu_procedimiento y
int_cacu_linea_de_tiempo.

marts/cacu/ queda vacío: siguiente paso es mover cacu_eu8.sql como primer modelo gold.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-11-04 01:00:01 +00:00
edgar 6a0007c372 Persistance tests: say why each asset, timeline and cohort-read test exists
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 19:22:53 +00:00
edgar 257ef9bef1 Merge pull request 'feature/model-proto: asset vocabulary, TimelineRepository, cohort-build reads' (#4) from feature/model-proto into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/4
tests could be more expressive next time, they are the majority of line of code additions
2026-11-03 18:22:42 +00:00
edgar 03d0d6388e Persistance: timeline_repository per domain, query bound with with_query (#21) 2026-11-03 17:46:46 +00:00
edgar e524041b70 Persistance: cohort-build reads in CohorteRepository (#124) 2026-11-03 17:21:36 +00:00
edgar 01e80eaefb Persistance: TimelineRepository with an injected query (#21) 2026-11-03 17:06:30 +00:00
edgar 9a7a4f45b1 Persistance: asset vocabulary for Hamilton graphs (#9) 2026-11-03 17:06:30 +00:00
Roberto Treviño Cervantes 7ae5ecc0fc reorganization 2026-10-31 12:59:45 -06:00
Roberto Treviño Cervantes c1d8fd727d reorganization 2026-10-31 12:59:17 -06:00
Roberto Treviño Cervantes e687f59672 reorganization 2026-10-31 12:48:20 -06:00
Roberto Treviño Cervantes 700ce42787 fold Orquestacion into the WebApi submodule as webapi.orquestacion
Single consumer (webapi.indicadores_vivos), already shipped as the same
Docker image/venv as WebApi — the separate package boundary wasn't
earning its keep. See WebApi@ae1ee46 for the actual move; this commit
removes the now-empty source tree, bumps the submodule pointer, and
updates the docs that pointed at it (README.md, LEEME.md, Persistance).
2026-10-31 00:51:55 -06:00
Roberto Treviño Cervantes 471df3c3ce package ISSSTELEON as an installable release: dist/ scripts, Hamilton-based Orquestacion, governance cohort cleanup, sanitized gitignore comments 2026-10-30 11:19:43 -06:00
Roberto Treviño Cervantes c159a69284 preliminary release 2026-10-29 12:16:56 -06:00
Roberto Treviño Cervantes 87a02938a9 integrating latest dashboard changes 2026-10-26 01:42:38 -06:00
Roberto Treviño Cervantes 8572e90e06 bump WebApp submodule pointer (fix flex-sizing bug and --issste-* variable aliases for the vendored indicadores module) 2026-10-23 08:07:16 -06:00
Roberto Treviño Cervantes 5840de1163 bump WebApi/WebApp submodule pointers to the amended dashboard history 2026-10-23 01:13:34 -06:00
Roberto Treviño Cervantes 73238205ba bump WebApi submodule pointer (Dockerfile + column matcher + duration coercion fixes) 2026-10-23 00:42:05 -06:00
Roberto Treviño Cervantes 4a18656dd2 add ClasificacionEeg/EstadoSegmentoEeg/FuenteSegmentoEeg enums (fork dev, additive alongside existing narrative EEG enums) 2026-10-23 00:41:54 -06:00
Roberto Treviño Cervantes 6efa4c6151 fold raw hospital BIRADS subcategory values (B4A/B4B/B4C) into B4 2026-10-23 00:25:19 -06:00
Roberto Treviño Cervantes 84144b03db integration layer; merge work on indicators from forks with existing ingestion pipeline 2026-10-23 00:06:24 -06:00
alberto 45124f95b3 Merge pull request 'revert 3b04ccd9bbf8ddbe863510ca76fc27599a9fcf5d' (#2) from dev into main
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/2
2026-10-09 00:09:59 +00:00
alberto c8d94c429d revert 3b04ccd9bb
revert Merge pull request 'Version/v0.4.0' (#1) from edgar/ISSSTELEON:version/v0.4.0 into main

Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/1
2026-10-09 00:07:41 +00:00
alberto 3b04ccd9bb Merge pull request 'Version/v0.4.0' (#1) from edgar/ISSSTELEON:version/v0.4.0 into main
pruebas / core (push) Successful in 17s
pruebas / persistance (push) Successful in 15s
pruebas / indicadores_kit (push) Successful in 1m7s
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/1
2026-10-08 23:58:16 +00:00
alberto c9aa09414c Merge pull request 'TEA: eeg_estudio desde el archivo .edf y tabla nueva eeg_segmento (Enmienda 01)' (#1) from v0.3.0 into version/v0.4.0
pruebas / core (pull_request) Successful in 11s
pruebas / persistance (pull_request) Successful in 19s
pruebas / indicadores_kit (pull_request) Successful in 1m14s
Reviewed-on: http://10.0.10.41:3000/edgar/ISSSTELEON/pulls/1
2026-10-08 23:54:53 +00:00
edgar 630b6f192a indicadores_kit en v0.4.0; ADR-004 al día
- Submódulo en la etiqueta v0.4.0 (3ba36dc): periodos de cada
  granularidad (T-1), reporte que no se repite con parametros_sha (T-2),
  los indicadores publican semestres y meses (S-M8). Resuelve I-M3: el
  job del kit ya prueba el kit que espera la regla nueva.
- ADR-004: la migración de parametros_sha y la regla de guardar.

Pruebas: Core 18 passed; Persistance 26 passed; indicadores_kit 293
passed, 1 skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:43:15 +00:00
edgar 0a42bc385b T-2 (v0.4.0): el reporte idéntico no se guarda; measure_report.parametros_sha
- Core: MeasureReportBase.parametros_sha (nulo en reportes anteriores):
  la huella de los valores en uso (I-K58).
- Persistance: migración nueva por dominio, sin editar las anteriores
  (cacu 1b350354d5ed, cama 2568e85ae55a; agrega la columna).
- guardar_reporte_en / MeasureReportRepository.guardar: si el último
  reporte del mismo indicador y periodo (por generado_en) tiene la misma
  versión, SQL, archivo de parámetros, parametros_sha, intervalo, estado,
  tipo y los mismos valores, no escribe y devuelve su report_id
  (decisión del usuario: opción A, D-5; I-K52).
- test_guardar_otra_vez_agrega_un_reporte_y_no_pisa se cambia por
  "guardar lo mismo devuelve el anterior"; se agregan conteo distinto,
  cada columna que distingue y "se compara con el último".

Pruebas: Core 18 passed; Persistance 26 passed; indicadores_kit 293
passed, 1 skipped (con el kit de esta misma rama).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:34:03 +00:00
edgar 63e3e38e9a TEA: eeg_estudio desde el archivo .edf y tabla nueva eeg_segmento (Enmienda 01)
- Core/spec/tablas_TEA_enmienda_01_eeg.md: diferencias de eeg_estudio,
  tabla eeg_segmento, catálogos y Anexo C.
- eeg_estudio se reemplaza (38 -> 19 columnas); eeg_archivo es BLOB.
- Catálogos nuevos: ClasificacionEeg, EstadoSegmentoEeg, FuenteSegmentoEeg.
  Se quitan los 9 catálogos de interpretación clínica.
- Migración 70c4097e286f y repositorio eeg_segmento_repository.
- La prueba de alembic check incluye TEA.
2026-10-08 23:16:37 +00:00
edgar 4c9339ee0c indicadores_kit en v0.3.1; pruebas también en ramas version/*
- Submódulo en la etiqueta v0.3.1 (b075161): estratos que siguen al
  total sin supresión por celda (S-M2), grupos de edad abiertos (S-M3),
  CI sin llave, pruebas de estratos más rápidas. La etiqueta v0.3.0 no
  se movió.
- .gitea/workflows/pruebas.yml: también en version/* (I-M1: desde v0.4.0
  la rama es version/vX.Y.Z y la etiqueta vX.Y.Z).

Pruebas: Core 18 passed; Persistance 20 passed; indicadores_kit 237
passed, 1 skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 23:03:56 +00:00
edgar f5804540b1 ADR-004 al día con v0.3.0
La lista de pendientes marcaba sin hacer "parámetros y periodos por
subclases", que se hizo en v0.3.0 (RegistroRepository). Se anotan
también las tablas de v0.3.0 (dim_fecha, dim_grupo_edad,
indicador_definicion) con sus migraciones. Solo documentación.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 21:40:40 +00:00
edgar d0cd6bad79 Lanza el CI de ISSSTELEON en v0.3.0 (Actions recién activadas)
Commit vacío: no cambia archivos.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 20:15:21 +00:00
edgar 021e152e74 CI sin llave SSH: el submódulo del kit se baja por HTTP
edgar/indicadores_kit es público. El trabajo indicadores_kit cambia la
URL ssh de .gitmodules por la del servidor que corre la acción
(insteadOf) y ya no necesita el secreto CLAVE_SSH. Se sigue probando el
commit exacto del puntero y comprobando que tenga etiqueta.

Pruebas, simuladas en un clon nuevo sin llaves y con ssh deshabilitado,
Python 3.12: Core 18 passed, Persistance 20 passed, indicadores_kit
232 passed, 1 skipped; el submódulo queda en v0.3.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 20:08:12 +00:00
edgar 7dd1b27ed2 indicadores_kit en v0.3.0 (rama v0.3.0, sin integrar a main)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 06:21:59 +00:00
edgar b6c1db526c Pruebas en Gitea también en las ramas de versión (v*)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 06:21:59 +00:00
edgar c33c111ba6 T-5 (v0.3.0): indicador_definicion en Core, migración y repositorio
- core/indicadores/reportes.py: IndicadorDefinicionBase.
- core/{cacu,cama}/indicadores/models.py: IndicadorDefinicion; exportada.
- Core/tests: conjuntos esperados y columnas iguales por dominio.
- Persistance: migración nueva por dominio, solo create_table (CaCu
  04fa57d42fec, CaMa b47d340c39f9); upgrade, check limpio, downgrade y
  upgrade otra vez. indicador_definicion_repository (RegistroRepository).

Pruebas: Core 18, Persistance 20, kit 218.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 06:14:37 +00:00
edgar c6ae5bce54 T-4 (v0.3.0): dim_fecha y dim_grupo_edad en Core, migración y repositorios
- core/indicadores/registro.py: DimFechaBase y DimGrupoEdadBase.
- core/{cacu,cama}/indicadores/models.py: DimFecha y DimGrupoEdad sobre
  CaCuModel / CaMaModel; exportadas en core/<dominio>/models.py.
- Core/tests: test_models (conjuntos esperados) y test_indicadores suman
  las dos tablas.
- Persistance: migración nueva por dominio, solo create_table de las dos
  (CaCu b4a35a200913, CaMa 1006aa43f896); upgrade, check limpio,
  downgrade y upgrade otra vez en bases temporales.
- dim_fecha_repository y dim_grupo_edad_repository (RegistroRepository).

Pruebas: Core 17, Persistance 20, kit 208.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 06:12:39 +00:00
edgar 5dbee86ab4 T-1 (v0.3.0): RegistroRepository para parámetros y periodos
- persistance/indicadores.py: RegistroRepository(Repository) con
  reemplazar(filas) y agregar_faltantes(filas), cada una en una sesión,
  todo o nada; reemplazar_en y agregar_faltantes_en son sus cuerpos.
  Servirá también a dim_fecha, dim_grupo_edad e indicador_definicion.
- persistance/{cacu,cama}/__init__.py: def_parametro_repository y
  dim_periodo_repository son RegistroRepository.
- tests/test_registro_repository.py.

Pruebas: Persistance 20 pasan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 03:49:22 +00:00
edgar 4a0032c344 indicadores_kit en v0.2.1
v0.2.0 más la prueba de punta a punta por el camino de producción.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 03:38:16 +00:00
edgar a1c4ecd883 indicadores_kit en v0.2.0
Desde aquí el submódulo apunta a etiquetas, no a commits sueltos.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 03:14:21 +00:00
edgar 1dae7d2ca9 Workflow de pruebas en Gitea para Core, Persistance e indicadores_kit
.gitea/workflows/pruebas.yml, un trabajo por paquete, cada uno con pytest
desde su directorio (así resuelven ../Core y ../Persistance):

- core, persistance: sin secretos.
- indicadores_kit: inicializa solo ese submódulo (secreto CLAVE_SSH con
  lectura en edgar/indicadores_kit), comprueba que el puntero sea una
  etiqueta (versión declarada funcional) y corre sus pruebas en esa
  versión.

Simulado sobre un clon de Gitea: Core 15, Persistance 16 y kit 181 pasan
con Python 3.12; la comprobación de etiqueta detecta un puntero sin ella.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 03:14:21 +00:00
edgar 44bbd1c825 indicadores_kit en kit-en-core (c0a9f39)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 03:01:08 +00:00
edgar f350ef3bb9 MeasureReportRepository: el reporte de indicadores_kit se guarda por Repository
- persistance/indicadores.py: MeasureReportRepository(Repository) con
  guardar(reporte, valores): una sola sesión, todo o nada; pone el
  report_id a los valores; cada llamada agrega un reporte.
  guardar_reporte_en es su cuerpo sobre una sesión que se recibe.
- persistance/{cacu,cama}/__init__.py: measure_report_repository es un
  MeasureReportRepository.
- tests/test_reporte_repository.py: reporte con sus valores; guardar otra
  vez agrega; si un valor falla no queda nada.
- Core/docs/ADR-004: reporte hecho; siguen parámetros y periodos.

Pruebas: Persistance 16 pasan (12 + 4 nuevas); Core 15; kit 181.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 03:01:08 +00:00
edgar d12040bf23 indicadores_kit en kit-en-core (a7c4329)
Mueve el puntero del submódulo de v0 (14aea50) al último commit de su
rama kit-en-core, del que dependen los cambios de Core y Persistance de
esta rama. Pedido por el usuario.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 02:58:34 +00:00
edgar c6a6e39e73 CargaRepository: el lote de indicadores_kit se escribe por Repository
Decisión del usuario: el kit escribe por subclases de Repository en
Persistance. Registrada en Core/docs/ADR-004 ("How the kit writes").

- persistance/indicadores.py: CargaRepository(Repository) con
  guardar_lote(fuente, personas, hechos): una sola sesión, todo o nada;
  versiones por huella (sin cambio no crea versión; con cambio, la
  siguiente con amended). La lógica estaba en el kit; no sabe de
  indicadores, recibe filas armadas.
- persistance/{cacu,cama}/__init__.py: carga_repository es un
  CargaRepository con la Persona de su dominio.
- tests/test_carga_repository.py: lote entero y legible con la sesión
  cerrada; si una fila falla no queda nada; personas sin duplicar;
  recargar sin cambios y con un cambio.

El puntero del submódulo indicadores_kit no se incluye.

Pruebas: Persistance 12 pasan (7 + 5 nuevas); Core 15; kit 181.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 02:53:28 +00:00
edgar c175ad513e Etapa 5: migración y repositorios de las tablas de indicadores_kit
- persistance/{cacu,cama}/alembic/versions: una migración nueva por
  dominio que solo crea las 8 tablas del kit (CaCu 9952833a0048, CaMa
  0616858b7434). Generadas con autogenerate contra una base temporal en
  head; ninguna migración existente se editó.
- persistance/{cacu,cama}/alembic/env.py: render_item agrega el import
  de los tipos propios de Core (FechaHoraUTC). Sin él la migración
  generada no corría (ADR-004, R8). Se arregló el generador y se
  regeneró; la migración no se editó a mano.
- persistance/{cacu,cama}/__init__.py: una instancia de Repository por
  tabla del kit.
- tests/test_indicadores.py: cada tabla del kit tiene su repositorio;
  lectura por Repository; upgrade head deja la base igual a los modelos
  (lo que comprueba alembic check).
- Core/docs/ADR-004: R7 decidido (sin naming convention por ahora), R8
  resuelto, etapa 5 hecha.

Comprobado en bases temporales: upgrade, check limpio, downgrade -1 y
upgrade otra vez. Sobre copias del staging sintético el upgrade conserva
staging. El puntero del submódulo indicadores_kit no se incluye.

Pruebas: Persistance 7 pasan (1 + 6 nuevas); Core 15; kit 181.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 02:30:06 +00:00
edgar 2a98126e8c Etapa 4b: tablas de indicadores_kit en Core, en el registro de cada dominio
Decisión y riesgos en Core/docs/ADR-004_tablas_del_kit_en_el_registro_del_dominio.md.

- core/indicadores/: las columnas, sin tabla, declaradas una vez (tipos,
  roles, comunes, registro, reportes).
- core/{cacu,cama}/indicadores/models.py: las 7 tablas comunes y la de
  hechos de cada dominio, sobre CaCuModel / CaMaModel.
- core/{cacu,cama}/models.py: las exporta, así el env.py de Alembic de
  cada dominio las ve sin cambios.
- tests/test_models.py: los conjuntos esperados de CaCu y CaMa incluyen
  las tablas del kit (autorizado por el usuario).
- tests/test_indicadores.py: mismas columnas en los dos dominios, ninguna
  llave foránea del kit hacia staging (B4), restricción de versión.

alembic check sobre una base temporal de CaCu en head propone solo las 8
tablas del kit (add_table), nada sobre staging. La migración es la
etapa 5. El puntero del submódulo indicadores_kit no se incluye.

Pruebas: Core 15 pasan (4 + 11 nuevas); Persistance 1; kit 181.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 02:20:41 +00:00
edgar 9a11248f09 indicadores_kit en v0 2026-10-07 02:48:06 +00:00
edgar b96b4b3d8f submodulo de indicadores 2026-10-06 22:39:31 +00:00
edgar 46aa111cca version cero 2026-10-06 22:31:52 +00:00
Roberto Treviño Cervantes a82767605a [schema revision] fix disconnected work, half-edits and metadata collisions at CaCu/CaMa; added ADOS-2 columns to TEA 2026-09-24 10:31:06 -06:00
Klingsor0 3c181d9f24 alias de enums corregidos 2026-09-21 15:22:06 -06:00
Klingsor0 e71054c712 enums central 2026-09-21 15:21:25 -06:00
Klingsor0 dcf3b2f8a6 alias de enums 2026-09-21 15:21:03 -06:00
Klingsor0 a9e52a4968 readme de modelos orm 2026-09-21 15:20:30 -06:00
Klingsor0 db6b8894b4 modelos orm para cama 2026-09-21 15:19:20 -06:00
Klingsor0 ef03bb4a3d enums por entidad, cacu/enums.py los importa 2026-09-21 14:07:14 -06:00
Klingsor0 8da1bfa807 herencia de clase base para resolver nombres compartidos de tabalas de distintos proyectos 2026-09-21 13:54:04 -06:00
Klingsor0 fdb5323e6c primera version de modelos limpios, iguales a los del repo original, solo que con los opcionales corregidos 2026-09-21 13:32:04 -06:00
Klingsor0 187d060b71 Readmes de los docs del repo, fuente de verdad para los modelos 2026-09-21 13:15:07 -06:00
Roberto Treviño Cervantes 6fd7792e69 add persistance's and models' readme 2026-09-21 10:38:47 -06:00
Roberto Treviño Cervantes 474f72c08a initial commit 2026-09-21 10:24:06 -06:00
476 changed files with 15607 additions and 375496 deletions
+13 -7
View File
@@ -1,7 +1,13 @@
.venv
data
**/__pycache__
**/target
**/logs
WebApp
.git
# Read by the webapi build, whose context is the repo root.
.git/
WebApp/
**/__pycache__/
**/*.pyc
**/.venv/
**/*.egg-info/
**/.pytest_cache/
**/*.db
**/uv.lock
!WebApi/uv.lock
dist/
**/node_modules/
+32
View File
@@ -0,0 +1,32 @@
# Copy to .env (docker compose reads it for the webapi service; Persistance's
# settings also read a .env in the working directory when run directly).
# --- Target databases (one per domain; SQLite files by default) ---
# CACU_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_cacu
# CAMA_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_cama
# TEA_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_tea
# GOVERNANCE_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_governance
CACU_DATABASE_URL=sqlite:////data/cacu.db
CAMA_DATABASE_URL=sqlite:////data/cama.db
TEA_DATABASE_URL=sqlite:////data/tea.db
# Stored predictions and the OCR extraction log.
GOVERNANCE_DATABASE_URL=sqlite:////data/governance.db
# --- SQL import sources a client may point the server at ---
# SQLAlchemy backend names. sqlite is excluded on purpose: its URL is a
# path on this server's disk.
WEBAPI_SQL_ALLOWED_DIALECTS=mysql,mariadb,postgresql,mssql
# Optional host allowlist (unset = any host reachable from the server).
# WEBAPI_SQL_ALLOWED_HOSTS=10.0.0.5,his-db.internal
# --- WebApi process ---
# Max request size (files travel inside import requests). Keep nginx's
# client_max_body_size (WebApp/nginx.conf) about 35% above it.
WEBAPI_MAX_UPLOAD_MB=200
# WEBAPI_WORKERS=2
# Seconds; OCR over many scanned pages runs inside one request.
# WEBAPI_TIMEOUT=600
# Tesseract languages for scanned documents.
# EXTRACTION_OCR_LANG=spa+eng
# Only for browser clients on another origin (the WebApp uses the proxy).
# WEBAPI_CORS_ORIGINS=https://example.internal
-106
View File
@@ -1,106 +0,0 @@
name: ci
on:
push:
branches: [rebuild]
pull_request:
branches: [rebuild]
env:
# Submodule URLs are SSH; the runner reaches the same repos over the server's HTTP.
GIT_CONFIG_COUNT: 1
GIT_CONFIG_KEY_0: url.${{ github.server_url }}/ISSSTELEON/.insteadOf
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
jobs:
python: # the whole suite, nothing skipped: SQLite and PostgreSQL, OCR included
runs-on: ubuntu-latest
services:
postgres:
image: postgres:17
env:
POSTGRES_PASSWORD: postgres
POSTGRES_DB: platform
options: >-
--health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10
sqlserver: # the hospital's test source (synthetic.site): ArchivosUni and ResultadosSubrogados
image: mcr.microsoft.com/mssql/server:2022-CU20-ubuntu-22.04
env:
ACCEPT_EULA: "Y"
MSSQL_PID: Developer
MSSQL_SA_PASSWORD: Test-only-Site-1
options: >-
--health-cmd "/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P Test-only-Site-1 -Q 'select 1' -b"
--health-interval 5s --health-timeout 10s --health-retries 30
env:
POSTGRES_TEST_URL: postgresql://postgres:postgres@postgres:5432/platform
SITE_SQL_SERVER: mssql+pymssql://sa:Test-only-Site-1@sqlserver:1433
PGHOST: postgres
FHIR_VALIDATOR_JAR: /opt/fhir/validator_cli.jar
SYNTHEA_JAR: /opt/synthea/synthea.jar
steps:
- uses: actions/checkout@v4
- run: git submodule update --init
- run: |
apt-get update
apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-spa ghostscript \
default-jre-headless
- name: HL7 validator, pinned
run: |
mkdir -p /opt/fhir
curl -sLo /opt/fhir/validator_cli.jar https://github.com/hapifhir/org.hl7.fhir.core/releases/download/7.0.5/validator_cli.jar
echo "9dfe9f305b0f9389eceade2a4a1c9a2740d7b0e614066fdf07a78b571c76d92f /opt/fhir/validator_cli.jar" | sha256sum -c
- name: Synthea, pinned
run: |
mkdir -p /opt/synthea
curl -sLo /opt/synthea/synthea.jar https://github.com/synthetichealth/synthea/releases/download/v4.0.0/synthea-with-dependencies.jar
echo "ed43c20ad40ba5c3bc724503a5af032715fe3c491620b766148e7c2361e6ecc1 /opt/synthea/synthea.jar" | sha256sum -c
- uses: astral-sh/setup-uv@v5
- run: uv sync --locked
- run: uv run ruff check
- run: uv run ruff format --check
- run: uv run lint-imports
- run: uv run pytest -q -rs -m "not webapp" # the pages run in the web job
web:
runs-on: ubuntu-latest
services:
sqlserver: # the hospital's test source (synthetic.site): ArchivosUni and ResultadosSubrogados
image: mcr.microsoft.com/mssql/server:2022-CU20-ubuntu-22.04
env:
ACCEPT_EULA: "Y"
MSSQL_PID: Developer
MSSQL_SA_PASSWORD: Test-only-Site-1
options: >-
--health-cmd "/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P Test-only-Site-1 -Q 'select 1' -b"
--health-interval 5s --health-timeout 10s --health-retries 30
env:
SITE_SQL_SERVER: mssql+pymssql://sa:Test-only-Site-1@sqlserver:1433
SYNTHEA_JAR: /opt/synthea/synthea.jar
steps:
- uses: actions/checkout@v4
- run: git submodule update --init
- uses: astral-sh/setup-uv@v5
- uses: actions/setup-node@v4
with:
node-version: '24'
- name: Generated API client matches the API
run: |
uv sync --locked
uv run python -m webapi.openapi > WebApp/openapi.json
cd WebApp && npm ci && npm run api
git diff --exit-code -- . || { echo 'Run: npm run api (after exporting openapi.json)'; exit 1; }
- working-directory: WebApp
run: npx ng build
- working-directory: WebApp
run: npx ng test --watch=false
- name: Every page loads from the API (Playwright over a loaded platform)
run: |
apt-get update
apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-spa ghostscript \
default-jre-headless
mkdir -p /opt/synthea
curl -sLo /opt/synthea/synthea.jar https://github.com/synthetichealth/synthea/releases/download/v4.0.0/synthea-with-dependencies.jar
echo "ed43c20ad40ba5c3bc724503a5af032715fe3c491620b766148e7c2361e6ecc1 /opt/synthea/synthea.jar" | sha256sum -c
(cd WebApp && npx playwright install --with-deps chromium)
uv run pytest -q -rs -m webapp
+15 -9
View File
@@ -1,10 +1,16 @@
.venv/
__pycache__/
data/
*.db
.dlt/
.pytest_cache/
.ruff_cache/
compose.override.yml
!tests/fixtures/**/*.db
# Local notes.
CLAUDE.md
AGENTS.md
HANDOFF*.md
# Local environment (database credentials); docker-compose reads it but git
# must never see it. Committed template lives in .env.example.
.env
.DS_Store
# Deliverable bundle: images and local state are built/created, not versioned.
dist/imagenes/
dist/.env
dist/datos/
dist/*.tar.gz
+9 -8
View File
@@ -1,12 +1,13 @@
[submodule "WebApi"]
path = WebApi
url = ../WebApi.git
branch = rebuild
[submodule "WebApp"]
path = WebApp
url = ../WebApp.git
branch = rebuild
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApp.git
[submodule "WebApi"]
path = WebApi
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApi.git
[submodule "models"]
path = models
url = ../models.git
branch = rebuild
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
-26
View File
@@ -1,26 +0,0 @@
[importlinter]
root_packages =
core
persistance
models
webapi
synthetic
[importlinter:contract:layers]
name = WebApi and models sit on Persistance, which sits on Core
type = layers
layers =
webapi | models
persistance
core
[importlinter:contract:synthetic]
name = Product packages never import the synthetic hospital
type = forbidden
source_modules =
core
persistance
models
webapi
forbidden_modules =
synthetic
-1
View File
@@ -1 +0,0 @@
3.12
+8
View File
@@ -0,0 +1,8 @@
__pycache__/
*.pyc
.venv/
.pytest_cache/
.coverage
*.egg-info/
.env
uv.lock
-92
View File
@@ -1,92 +0,0 @@
"""CaCu clinical parameters: the one place they are set. dbt reads them as vars, the models
import them. Codes are the platform's (core.schema)."""
# Biopsy grades that count as CIN2+ (the outcome) and as invasive cancer.
CIN2_PLUS = ["HSIL", "CIS", "carcinoma"]
CANCER = ["carcinoma"]
CASE = ["CIS", "carcinoma"] # a biopsy this grade makes her a case: she has cancer
# The follow-up list: patients with a cytology sampled within the window before the cut-off.
FOLLOW_UP_WINDOWS = [1, 3, 6, 12] # months
FOLLOW_UP_WINDOW = 3
# Index cytology in the six KPNC categories, least to most severe.
KPNC = {
"NILM": ["NILM"],
"ASC-US": ["ASC-US"],
"LSIL": ["LSIL"],
"ASC-H": ["ASC-H"],
"AGC": ["AGC"],
"HSIL+": ["HSIL", "CIS", "adenocarcinoma"],
}
# The three categories used after colposcopy and after treatment.
KPNC_3 = {
"NILM": ["NILM"],
"ASC-US/LSIL": ["ASC-US", "LSIL"],
"High Grade": ["ASC-H", "AGC", "HSIL", "CIS", "adenocarcinoma"],
}
# The referral PPVs (core.cacu.measures.ReferralPPV). Cytology groups overlap: each holds its
# grade and every more severe squamous one. Histology levels are numerators over one
# denominator; the first is the measure's score.
PPV_CYTOLOGY = {
"ASCUS+": ["ASC-US", "LSIL", "ASC-H", "HSIL", "CIS"],
"LSIL+": ["LSIL", "ASC-H", "HSIL", "CIS"],
"HSIL+": ["HSIL", "CIS"],
}
PPV_HISTOLOGY = {"LIEBG+": ["LSIL", *CIN2_PLUS], "LIEAG+": CIN2_PLUS, "invasive": CANCER}
PREVIOUS_SCREENING = ["1_year_or_less", "2_years", "3_years_or_more"] # screening_history
REFERRAL_CYTOLOGY_DAYS = 365 # the referring cytology's report is at most this old
# Results that show a patient free of CIN2+ at a visit: a negative co-test (both within
# INDEX_SAMPLE_DAYS of each other), or a biopsy below the outcome grades.
KNOWN_NEGATIVE = {"bethesda": ["NILM", "ASC-US"], "hpv": ["negative"]}
INDEX_SAMPLE_DAYS = 30 # results this many days after the index sample still describe it
PREVALENT_WINDOW_DAYS = 6 * 365.25 / 12 # an outcome this soon was there at the index
DAYS_PER_YEAR = 365.25
# Recruitment windows (start inclusive, end exclusive).
RECRUITMENT = ("2018-01-01", "2027-01-01")
POST_TREATMENT_RECRUITMENT = ("2024-01-01", "2027-01-01")
POST_TREATMENT_INDEX_AFTER_DAYS = 90 # the index cytology comes this long after treatment
POST_TREATMENT_LOOKBACK_DAYS = 365 # a biopsy result this long before treatment is required
POST_COLPOSCOPY_VISIT = 1 # index: the k-th surveillance cytology after the colposcopy result
REFERRAL_LOOKBACK_DAYS = 365 # results this long before colposcopy are why she was referred
HYSTERECTOMY_ICD10 = ["Z907"]
# Inferred procedures, from clinical notes (ICD-10 without the dot).
# Specialties are the platform's codes; each site's pipeline maps its own names to them.
DIAGNOSIS_SPECIALTIES = ["colposcopy", "oncology_surgery"]
COLPOSCOPY_SPECIALTIES = ["colposcopy"]
SAMPLE_TO_DIAGNOSIS_DAYS = 120 # a diagnosis note this soon after a sample assesses it
DIAGNOSIS_ICD10 = [
"Z014", "Z124", "B977", "R876", "N87", "N870", "N871", "N872", "N879",
"D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539",
] # fmt: skip
HISTORY_ICD10 = ["D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539"]
TREATMENT_ICD10 = ["D06", "D060", "D061", "D067", "D069"]
COLPOSCOPY_ICD10 = ["R876", "N87", "N870", "N871", "N872", "N879", "B977"]
COLPOSCOPY_REASONS = ["ACUDE A COLPOSCOPIA", "COLPOSCOPIA"]
COLPOSCOPY_DIAGNOSES = ["VIRUS DEL PAPILOMA HUMANO"]
SURVEILLANCE_SPECIALTIES = ["family_medicine", "colposcopy"]
# Measures (core.measures): the horizons of the screening route, in days; an interval
# that hasn't ended after its horizon counts as not ended.
HORIZONS = {
"sample_to_report": 60, "sample_to_treatment": 180, "diagnosis_to_treatment": 60,
"sample_to_colposcopy": 60, "sample_to_biopsy": 60, "result_to_colposcopy": 60,
"colposcopy_to_biopsy": 60, "biopsy_to_diagnosis": 60,
} # fmt: skip
ABNORMAL = ["ASC-US", "ASC-H", "LSIL", "HSIL", "CIS"] # IND1
HIGH_GRADE = ["ASC-H", "HSIL", "CIS"] # cytology that should be confirmed by biopsy
DETECTION = ["HSIL", "CIS", "carcinoma"] # biopsy grades counted as detected (EU13)
BIOPSY_SEVERITY = ["normal", "LSIL", "HSIL", "CIS", "carcinoma"] # least to most severe
AGE_GROUPS = [(25, 34), (35, 44), (45, 54), (55, 64)] # plus "<25" and "65+"
RISK_BAND_MODEL = "cacu.cin2_pim" # whose risk at the index visit is banded (surveillance)
RISK_BANDS = [("low", 0.04), ("intermediate", 0.25), ("high", None)] # below each cut
def dbt_vars() -> dict:
"""What dbt reads (`var('cacu')`)."""
return {k.lower(): v for k, v in globals().items() if k.isupper()}
+12
View File
@@ -0,0 +1,12 @@
import sqlalchemy.orm as orm
from sqlmodel import SQLModel
registry = orm.registry()
class CaCuModel(SQLModel, registry=registry):
"""Base class for every CaCu table.
Uses its own SQLAlchemy registry so table names such as `notamedica`
don't collide with CaMa's tables of the same name.
"""
@@ -0,0 +1,34 @@
## biometria_hematica
Tabla de resultados de laboratorio, 1 fila por reporte de biometría hemática.
Fuente: extracción OCR y NLP sobre PDF vinculado en Estudios Laboratorio (BH1).
Join hacia ordenes_estudio por ord_numero_hospital (lógico, sin FK constraint). Join hacia paciente por pac_id_hospital (resuelto en carga).
| Columna | Fuente | Descripción |
| ------------------------------ | -------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `bh_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | Join lógico hacia paciente.pac_id, resuelto en carga, nulo si no hay match al momento de ingesta |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, obligatorio para el join lógico hacia paciente |
| `ord_numero_hospital` | Hospital, BH4 | Número de orden HIS, join lógico hacia ordenes_estudio.ord_numero_hospital |
| `bh_fecha` | Hospital, BH2 | Fecha de solicitud del estudio; pendiente de distinción con BH3 (fecha resultado) según ETL |
| `eritrocitos_mill_ul` | Derivado, OCR sobre PDF BH1 | Conteo de eritrocitos (millones/µL) |
| `hemoglobina_g_dl` | Derivado, OCR sobre PDF BH1 | Concentración de hemoglobina (g/dL) |
| `hematocrito_pct` | Derivado, OCR sobre PDF BH1 | Hematocrito como porcentaje del volumen sanguíneo |
| `vcm_fl` | Derivado, OCR sobre PDF BH1 | Volumen corpuscular medio (fL) |
| `hcm_pg` | Derivado, OCR sobre PDF BH1 | Hemoglobina corpuscular media (pg) |
| `chcm_g_dl` | Derivado, OCR sobre PDF BH1 | Concentración de hemoglobina corpuscular media (g/dL) |
| `rdw_pct` | Derivado, OCR sobre PDF BH1 | Amplitud de distribución eritrocitaria (%) |
| `leucocitos_mil_ul` | Derivado, OCR sobre PDF BH1 | Conteo total de leucocitos (miles/µL) |
| `neutrofilos_pct` | Derivado, OCR sobre PDF BH1 | Neutrófilos totales como porcentaje del diferencial leucocitario |
| `linfocitos_pct` | Derivado, OCR sobre PDF BH1 | Linfocitos como porcentaje del diferencial leucocitario |
| `monocitos_pct` | Derivado, OCR sobre PDF BH1 | Monocitos como porcentaje del diferencial leucocitario |
| `eosinofilos_pct` | Derivado, OCR sobre PDF BH1 | Eosinófilos como porcentaje del diferencial leucocitario |
| `basofilos_pct` | Derivado, OCR sobre PDF BH1 | Basófilos como porcentaje del diferencial leucocitario |
| `neutrofilos_segmentados_pct` | Derivado, OCR sobre PDF BH1 | Neutrófilos segmentados, desglose del diferencial neutrofílico (%) |
| `neutrofilos_banda_pct` | Derivado, OCR sobre PDF BH1 | Neutrófilos en banda, desglose del diferencial neutrofílico (%) |
| `metamielocitos_pct` | Derivado, OCR sobre PDF BH1 | Metamielocitos, desglose del diferencial neutrofílico (%) |
| `mielocitos_pct` | Derivado, OCR sobre PDF BH1 | Mielocitos, desglose del diferencial neutrofílico (%) |
| `plaquetas_mil_ul` | Derivado, OCR sobre PDF BH1 | Conteo de plaquetas (miles/µL) |
| `vpm_fl` | Derivado, OCR sobre PDF BH1 | Volumen plaquetario medio (fL) |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
@@ -0,0 +1 @@
from core.cacu.biometria_hematica.model import BiometriaHematica
@@ -0,0 +1,60 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import HOSPITAL_ID_LENGTH
class BiometriaHematica(CaCuModel, table=True):
"""
Modelo ORM para biometría hemática.
No hay validación en esta capa, se almacena laxamente.
"""
bh_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# Logical join, resolved on import by looking up paciente.pac_id_hospital
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
# Hospital patient id: links studies to patients
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# Logical join to ordenes_estudio.ord_numero_hospital, no FK constraint
ord_numero_hospital: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
bh_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
eritrocitos_mill_ul: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
hemoglobina_g_dl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
hematocrito_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
vcm_fl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
hcm_pg: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
chcm_g_dl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
rdw_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
leucocitos_mil_ul: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
linfocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
monocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
basofilos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
eosinofilos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
neutrofilos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
mielocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
metamielocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
neutrofilos_banda_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
neutrofilos_segmentados_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
plaquetas_mil_ul: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
vpm_fl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
+21
View File
@@ -0,0 +1,21 @@
## biopsia_cervical
Tabla de resultados histopatológicos, 1 fila por reporte de biopsia cervical.
Fuente: extracción OCR y NLP sobre PDF vinculado en ordenes_estudio.
Join hacia ordenes_estudio por ord_numero_hospital (lógico, sin FK constraint). Join hacia paciente por pac_id_hospital (resuelto en carga).
| Columna | Fuente | Descripción |
| -------------------- | -------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `bx_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | Join lógico hacia paciente.pac_id, resuelto en carga, nulo si no hay match al momento de ingesta |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, obligatorio para el join lógico hacia paciente |
| `ord_numero_hospital`| Hospital, HPC1, TVPH1 | Número de orden HIS, join lógico hacia ordenes_estudio.ord_numero_hospital |
| `cit_id` | Derivado, FK citologiacervical | Citología cervical previa asociada, nulo si no documentada en el sistema |
| `bx_fecha_solicitud` | Hospital, HPC2 | Fecha de solicitud de la biopsia |
| `bx_fecha_reporte` | Derivado, OCR regex fecha | Fecha de emisión del reporte histopatológico por el patólogo |
| `bx_cin_grado` | Derivado, NLP regex PDF HPC1 | Grado CIN extraído del diagnóstico histopatológico, variable objetivo principal para modelos de riesgo |
| `bx_observaciones` | Hospital, — | Observaciones del reporte |
| `bx_ocr_confianza` | Derivado, pipeline OCR | Score de confianza global del motor OCR sobre el documento |
| `bx_pdf_blob` | Derivado, extracción ETL HPC1 | Contenido binario del PDF del reporte histopatológico |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
@@ -0,0 +1 @@
from core.cacu.biopsia_cervical.model import BiopsiaCervical
+22
View File
@@ -0,0 +1,22 @@
from enum import Enum
class GradoCIN(str, Enum):
NORMAL = "NORMAL"
LIEBG = "LIEBG" # histological low-grade — CIN1 equivalent
LIEAG = "LIEAG" # histological high-grade — CIN2/3 equivalent
CIS = "CIS" # carcinoma in situ
CARCINOMA = "CARCINOMA" # invasive
DESCONOCIDO = "DESCONOCIDO"
GRADO_CIN_ALIAS: dict[str, str] = {
"LESIÓN INTRAEPITELIAL ESCAMOSA DE BAJO GRADO": "LIEBG",
"LESION INTRAEPITELIAL ESCAMOSA DE BAJO GRADO": "LIEBG",
"LESIÓN INTRAEPITELIAL ESCAMOSA DE ALTO GRADO": "LIEAG",
"LESION INTRAEPITELIAL ESCAMOSA DE ALTO GRADO": "LIEAG",
"CARCINOMA IN SITU": "CIS",
"CARCINOMA INVASOR": "CARCINOMA",
# CIN/NIC grades as reports write them; CIN2 and CIN3 are both LIEAG.
"CIN1": "LIEBG", "CIN 1": "LIEBG", "CIN-1": "LIEBG", "NIC1": "LIEBG", "NIC 1": "LIEBG", "NIC-1": "LIEBG",
"CIN2": "LIEAG", "CIN 2": "LIEAG", "CIN-2": "LIEAG", "NIC2": "LIEAG", "NIC 2": "LIEAG", "NIC-2": "LIEAG",
"CIN3": "LIEAG", "CIN 3": "LIEAG", "CIN-3": "LIEAG", "NIC3": "LIEAG", "NIC 3": "LIEAG", "NIC-3": "LIEAG",
}
+82
View File
@@ -0,0 +1,82 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
class BiopsiaCervical(CaCuModel, table=True):
"""
Modelo ORM para biopsia cervical.
No hay validación en esta capa, se almacena laxamente.
"""
bx_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# Logical join, resolved on import by looking up paciente.pac_id_hospital
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
# Hospital patient id, required: links studies to patients
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# Logical join to ordenes_estudio.ord_numero_hospital, no FK constraint
ord_numero_hospital: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
cit_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("citologiacervical.cit_id"), index=True),
)
bx_fecha_solicitud: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
bx_fecha_reporte: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
bx_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Observaciones",
)
bx_cin_grado: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_pdf_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(FileBlob),
)
bx_ocr_confianza: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
# VAR-03
bx_ocr_estatus: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="valor de core.ocr.OcrEstatus guardado como texto",
)
bx_ocr_requiere_revision: Optional[bool] = Field(
default=None,
sa_column=sa.Column(sa.Boolean),
)
bx_ocr_metodo_principal: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_ocr_metodo_alternativo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
@@ -0,0 +1,29 @@
## citologia_cervical
Tabla de resultados, 1 fila por reporte citológico. Fuente: TC1-TC10, resultado VPH integrado (TVPH1).
Join hacia ordenes_estudio por ord_numero_hospital (lógico, sin FK constraint). Join hacia paciente por pac_id_hospital (resuelto en carga).
| Columna | Fuente | Descripción |
| --------------------------- | ------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `cit_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | Join lógico hacia paciente.pac_id, resuelto en carga, nulo si no hay match al momento de ingesta |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, obligatorio para el join lógico hacia paciente |
| `ord_numero_hospital` | Hospital, TC1, TVPH1 | Número de orden HIS, join lógico hacia ordenes_estudio.ord_numero_hospital |
| `cit_fecha_toma` | Hospital, TC1 | Fecha en que se realizó la toma de muestra |
| `cit_fecha_reporte` | Derivado, reporte VPH u otro | Fecha de disponibilidad del resultado para el paciente |
| `cit_calidad_especimen` | Hospital, TC5 | Calidad del espécimen según criterios del sistema Bethesda 2014 |
| `cit_dx_lesion` | Hospital, TC6 | Diagnóstico citológico general para lesión intraepitelial o malignidad |
| `cit_celulas_escamosas` | Hospital, TC7 | Categoría de anomalía en células escamosas según Bethesda |
| `cit_carcinoma_invasor` | Hospital, TC8 | Presencia de carcinoma epidermoide invasor |
| `cit_celulas_glandulares` | Hospital, TC9 | Categoría de anomalía en epitelio glandular según Bethesda |
| `cit_condiciones_ginecoobs` | Hospital, TC2 | Condiciones gineco-obstétricas al momento de la toma (embarazo, DIU, menopausia, etc.) |
| `cit_exploracion` | Hospital, TC4 | Hallazgos a la exploración: aspecto del cérvix, flujo, lesiones visibles |
| `cit_observaciones` | Hospital, TC10 | Observaciones libres del citólogo no capturadas en los campos estructurados |
| `cit_vph_resultado` | Derivado, OCR sobre PDF TVPH1 | Resultado cualitativo del tamizaje VPH co-solicitado con la citología |
| `cit_vph_genotipo_16` | Derivado, OCR sobre PDF TVPH1 | Detección específica de genotipo VPH-16 |
| `cit_vph_genotipo_18` | Derivado, OCR sobre PDF TVPH1 | Detección específica de genotipo VPH-18 |
| `cit_vph_ocr_confianza` | Derivado, pipeline OCR | Score de confianza global del motor OCR sobre el PDF VPH |
| `cit_pdf_blob` | Derivado, extracción ETL | Contenido binario del PDF del resultado citológico |
| `cit_vph_pdf_blob` | Derivado, extracción ETL TVPH1 | Contenido binario del PDF del resultado VPH, su presencia distingue VPH no solicitado de extracción fallida |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
@@ -0,0 +1 @@
from core.cacu.citologia_cervical.model import CitologiaCervical
@@ -0,0 +1,41 @@
from enum import Enum
class CelulasEscamosas(str, Enum):
"""
Resultado de celulas escamosas.
Los resultados de celulas escamosas estan en el sistema de terminos Bethesda.
Se normalizan para usar sus abreviaturas.
"""
NORMAL = "NORMAL"
ASC_US = "ASC-US"
ASC_H = "ASC-H"
LIEBG = "LIEBG"
LIEAG = "LIEAG"
CIS = "CIS"
CELULAS_ESCAMOSAS_ALIAS: dict[str,str] = {
# Long forms, as the hospital platform is expected to write them
"LESIÓN INTRAEPITELIAL ESCAMOSA DE BAJO GRADO (DISPLASIA LEVE Y/O VPH)": "LIEBG",
"LESION INTRAEPITELIAL ESCAMOSA DE BAJO GRADO (DISPLASIA LEVE Y/O VPH)": "LIEBG", # without accent
"LESIÓN INTRAEPITELIAL ESCAMOSA DE ALTO GRADO (DISPLASIA MODERADA Y GRAVE)": "LIEAG",
"LESION INTRAEPITELIAL ESCAMOSA DE ALTO GRADO (DISPLASIA MODERADA Y GRAVE)": "LIEAG",
"CARCINOMA IN SITU": "CIS",
# Bethesda "negative for intraepithelial lesion or malignancy" (NILM).
"NEGATIVO": "NORMAL",
"NILM": "NORMAL",
"NEGATIVO PARA LESION INTRAEPITELIAL O MALIGNIDAD": "NORMAL",
"NEGATIVO PARA LESIÓN INTRAEPITELIAL O MALIGNIDAD": "NORMAL",
}
CITO_CALIDAD_ESPECIMEN_ALIAS: dict[str,bool] = {
# String forms the source platforms are expected to send
"SATISFACTORIO": True,
"INSATISFACTORIO": False,
"1": True, # from JSON bool serialization
"0": False,
}
class ResultadoVPH(str, Enum):
POSITIVO = "POSITIVO"
NEGATIVO = "NEGATIVO"
INDETERMINADO = "INDETERMINADO" # extracted but ambiguous — not same as NULL
+122
View File
@@ -0,0 +1,122 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
class CitologiaCervical(CaCuModel, table=True):
cit_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# Logical join, resolved on import by looking up paciente.pac_id_hospital
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
# Hospital patient id, required: links studies to patients
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# Logical join to ordenes_estudio.ord_numero_hospital, no FK constraint
ord_numero_hospital: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
cit_fecha_toma: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha de toma de muestra",
)
cit_fecha_reporte: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha de disponibilidad de resultado para el paciente",
)
cit_calidad_especimen: Optional[str] = Field(
default=None
)
cit_pdf_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(FileBlob),
description="PDF de resultado",
)
cit_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Observaciones",
)
cit_condiciones_ginecoobs: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Condiciones gineco-obstétricas: embarazo, DIU, etc.",
)
cit_exploracion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Hallazgos en exploración",
)
cit_dx_lesion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="TC6 Diagnóstico citológico para lesión",
)
cit_celulas_glandulares: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="TC9 Anomalías del epitelio glandular",
)
cit_carcinoma_invasor: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="TC8 Carcinoma epidermoide invasor",
)
cit_celulas_escamosas: Optional[str] = Field(
default=None,
description="TC7 Anomalías de células escamosas"
)
cit_vph_pdf_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(FileBlob)
)
cit_vph_ocr_confianza: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float)
)
cit_vph_resultado: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text)
)
cit_vph_genotipo_16: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer)
)
cit_vph_genotipo_18: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer)
)
# VAR-03: besides the confidence, the status, the manual-review flag and the
# method (main or fallback) that produced the value.
cit_vph_ocr_estatus: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="valor de core.ocr.OcrEstatus guardado como texto",
)
cit_vph_ocr_requiere_revision: Optional[bool] = Field(
default=None,
sa_column=sa.Column(sa.Boolean),
)
cit_vph_ocr_metodo_principal: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
cit_vph_ocr_metodo_alternativo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
+6
View File
@@ -0,0 +1,6 @@
from core.cacu.paciente.enums import SexoBiologico, SEXO_BIOLOGICO_ALIAS
from core.cacu.citologia_cervical.enums import CelulasEscamosas, CELULAS_ESCAMOSAS_ALIAS, CITO_CALIDAD_ESPECIMEN_ALIAS, ResultadoVPH
from core.cacu.biopsia_cervical.enums import GradoCIN, GRADO_CIN_ALIAS
from core.cacu.nota_medica.enums import TipoNota, TIPO_NOTA_ALIAS, Especialidad, ESPECIALIDAD_ALIAS, Parentesco, PARENTESCO_ALIAS, Dependencia, DEPENDENCIA_ALIAS
from core.cacu.ordenes_estudio.enums import TipoEstudio, TIPO_ESTUDIO_ALIAS
from core.cacu.episodio_clinico.enums import TipoEpisodio, TIPO_EPISODIO_ALIAS
+17
View File
@@ -0,0 +1,17 @@
from enum import Enum
class TipoEpisodio(str, Enum):
"""IND-02: la unidad de análisis para evaluación de desempeño del
modelo es un episodio de tamizaje, diagnóstico o tratamiento."""
TAMIZAJE = "TAMIZAJE"
DIAGNOSTICO = "DIAGNOSTICO"
TRATAMIENTO = "TRATAMIENTO"
TIPO_EPISODIO_ALIAS: dict[str, str] = {
"SCREENING": "TAMIZAJE",
"DIAGNOSTIC": "DIAGNOSTICO",
"TREATMENT": "TRATAMIENTO",
}
+72
View File
@@ -0,0 +1,72 @@
from datetime import date, datetime, timezone
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import HOSPITAL_ID_LENGTH
class EpisodioClinico(CaCuModel, table=True):
"""IND-02/IND-03: a screening, diagnosis or treatment episode, the unit
of analysis for model evaluation.
An episode combines a CIE10 code and medical specialty, a time window
bounded by the previous episode (`episodio_anterior_id`), and the medical
note it originates from (`nm_id`). The CIE10 code and specialty are
usually copied from `NotaMedica` and stored here so episodes can be
filtered without joining back to the note. Storage only; building
episodes from notes and orders is not implemented yet.
"""
episodio_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
)
tipo_episodio: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="valor de core.cacu.episodio_clinico.enums.TipoEpisodio guardado como texto",
)
nm_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("notamedica.nm_id"), index=True),
description="nota médica cuyo contenido escrito origina/documenta el episodio",
)
cie10_codigo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
especialidad_medica: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
evento_fecha: date = Field(
sa_column=sa.Column(sa.Date, nullable=False),
description="fecha del evento de interés que define el episodio",
)
ventana_inicio: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="inicio de la ventana de tiempo fija delimitada a partir del evento anterior",
)
ventana_fin: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
episodio_anterior_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("episodioclinico.episodio_id"), index=True),
description="evento anterior que delimita la ventana de este episodio",
)
created_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_column=sa.Column(sa.DateTime, nullable=False),
)
-55
View File
@@ -1,55 +0,0 @@
"""CaCu's follow-up list (pure): who is on it at a cut-off day, her status then, and the order
it is read in. The list holds every patient with a cytology sampled within the window
(`cacu.FOLLOW_UP_WINDOWS` months) up to the cut-off."""
from collections.abc import Iterable
from datetime import date
from core import cacu
from core.cacu.measures import follow_up_status
# Risk outcomes the list can be ordered by: a model counts for the outcome its name starts.
OUTCOMES = {"cin2": "cacu.cin2", "cancer": "cacu.cancer"}
SORTS = ("-recent", *(f"-risk-{o}" for o in OUTCOMES))
DEFAULT_HORIZON = 5.0
WINDOWS = cacu.FOLLOW_UP_WINDOWS
STATUS_SYSTEM = "cacu-follow-up-status"
PROCEDURES = ("colposcopy", "treatment")
REPORT_FACTS = {"cervical_cytology": "diagnosis_days"} # days from the sample to its diagnosis
def status(row: dict, cutoff: date) -> str:
"""Her follow-up status by the end of the cut-off day."""
return follow_up_status(row, cutoff, through=True)
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
"""The rows (whoever had a cytology sampled in the window, most recent first), each with
her status."""
return [{**r, "status": status(r, cutoff)} for r in rows]
def current_risk(risks: Iterable[dict], outcome: str, horizon: float) -> float | None:
"""Her current risk of an outcome at a horizon (years): from the latest index date any
of the outcome's models scored her at; the highest when several did."""
prefix = OUTCOMES[outcome]
mine = [r for r in risks if r["model"].startswith(prefix) and r["horizon_years"] == horizon]
if not mine:
return None
latest = max(str(r["index_date"]) for r in mine)
return max(r["probability"] for r in mine if str(r["index_date"]) == latest)
def ordered(rows: list[dict], sort: str, risks: dict[str, list[dict]],
horizon: float) -> list[dict]: # fmt: skip
"""The list in reading order. `rows` come most recent first; by risk, highest first,
unscored patients last, ties kept most recent first."""
if sort == "-recent":
return rows
outcome = sort.removeprefix("-risk-")
def key(row: dict):
found = current_risk(risks.get(row["person_id"], []), outcome, horizon)
return (found is None, -(found or 0.0))
return sorted(rows, key=key)
+200
View File
@@ -0,0 +1,200 @@
"""Las tablas de indicadores_kit en el dominio CaCu.
Viven en el registro de `CaCuModel`, en la misma base que el staging de
CaCu (ADR-004). Las columnas se declaran una vez en `core.indicadores`;
aquí solo se instancian. Ninguna llave foránea apunta a una tabla de
staging: `persona` es propia aunque repita a `paciente`.
"""
from core.cacu.base import CaCuModel
from core.indicadores.cohortes import (
CohorteArmadoBase,
CohorteExclusionBase,
CohorteMiembroBase,
CohorteVariableBase,
EvaluacionRiesgoBase,
EvaluacionRiesgoLoteBase,
armado_unico,
evaluacion_unica,
variable_con_un_valor,
)
from core.indicadores.catalogos import (
CatEstudioBase,
CatResultadoBase,
CatValorBase,
estado_de_valor_conocido,
tipo_de_valor_conocido,
)
from core.indicadores.plata import (
ObservacionClinicaBase,
ProcedimientoClinicoBase,
clase_conocida,
indice_de_observacion,
indice_de_procedimiento,
observacion_en_catalogo,
llave_de_observacion,
llave_de_procedimiento,
)
from core.indicadores.comunes import CargaBase, PeriodoObservacionBase, PersonaDerechohabienteBase
from core.indicadores.registro import (
DefParametroBase,
DimFechaBase,
DimGrupoEdadBase,
DimPeriodoBase,
)
from core.indicadores.publicacion import (
CatEstratoBase,
CatEstratoValorBase,
CatMeasureBase,
CatMeasureEstratoBase,
CatMeasureGrupoBase,
CatMeasureResultadoBase,
CatMeasureValorBase,
MeasureReportUnidadBase,
MeasureReportUnidadEstratoBase,
contrato_y_unidad_conocidos,
origen_conocido,
poblacion_conocida,
una_poblacion_por_indicador,
unidad_de_estrato_conocida,
valor_de_estrato_en_catalogo,
)
from core.indicadores.reportes import (
MeasureReportBase,
)
class Persona(CaCuModel, PersonaDerechohabienteBase, table=True):
__tablename__ = "persona"
class PeriodoObservacion(CaCuModel, PeriodoObservacionBase, table=True):
__tablename__ = "periodo_observacion"
class Carga(CaCuModel, CargaBase, table=True):
__tablename__ = "carga"
class DefParametro(CaCuModel, DefParametroBase, table=True):
__tablename__ = "def_parametro"
class DimPeriodo(CaCuModel, DimPeriodoBase, table=True):
__tablename__ = "dim_periodo"
class DimFecha(CaCuModel, DimFechaBase, table=True):
__tablename__ = "dim_fecha"
class DimGrupoEdad(CaCuModel, DimGrupoEdadBase, table=True):
__tablename__ = "dim_grupo_edad"
class MeasureReport(CaCuModel, MeasureReportBase, table=True):
__tablename__ = "measure_report"
# --- El oro por unidad y su catálogo (§6f, MD-19) ---
class CatMeasure(CaCuModel, CatMeasureBase, table=True):
__tablename__ = "cat_measure"
__table_args__ = contrato_y_unidad_conocidos()
class CatMeasureResultado(CaCuModel, CatMeasureResultadoBase, table=True):
__tablename__ = "cat_measure_resultado"
__table_args__ = (poblacion_conocida(), una_poblacion_por_indicador())
class CatMeasureValor(CaCuModel, CatMeasureValorBase, table=True):
__tablename__ = "cat_measure_valor"
__table_args__ = (origen_conocido(),)
class CatMeasureGrupo(CaCuModel, CatMeasureGrupoBase, table=True):
__tablename__ = "cat_measure_grupo"
class CatEstrato(CaCuModel, CatEstratoBase, table=True):
__tablename__ = "cat_estrato"
__table_args__ = (unidad_de_estrato_conocida(),)
class CatEstratoValor(CaCuModel, CatEstratoValorBase, table=True):
__tablename__ = "cat_estrato_valor"
class CatMeasureEstrato(CaCuModel, CatMeasureEstratoBase, table=True):
__tablename__ = "cat_measure_estrato"
class MeasureReportUnidad(CaCuModel, MeasureReportUnidadBase, table=True):
__tablename__ = "measure_report_unidad"
class MeasureReportUnidadEstrato(CaCuModel, MeasureReportUnidadEstratoBase, table=True):
__tablename__ = "measure_report_unidad_estrato"
__table_args__ = (valor_de_estrato_en_catalogo(),)
# --- Catálogos de la plata (F1): estudio -> resultado -> valor, de core/catalogos/cacu.toml ---
class CatEstudio(CaCuModel, CatEstudioBase, table=True):
__tablename__ = "cat_estudio"
class CatResultado(CaCuModel, CatResultadoBase, table=True):
__tablename__ = "cat_resultado"
__table_args__ = (tipo_de_valor_conocido(),)
class CatValor(CaCuModel, CatValorBase, table=True):
__tablename__ = "cat_valor"
__table_args__ = (estado_de_valor_conocido(),)
# --- La plata de dos tablas (F5, ADR-MD-007) ---
class Procedimiento(CaCuModel, ProcedimientoClinicoBase, table=True):
__tablename__ = "procedimiento"
__table_args__ = (clase_conocida(), llave_de_procedimiento(), indice_de_procedimiento())
class Observacion(CaCuModel, ObservacionClinicaBase, table=True):
__tablename__ = "observacion_clinica" # `observacion` choca con la CTE `observacion` del motor (T-18r)
__table_args__ = (*observacion_en_catalogo(), llave_de_observacion(), indice_de_observacion())
# --- Cohortes para modelos y estimaciones de riesgo (oro restringido, ADR-MD-003) ---
class CohorteArmado(CaCuModel, CohorteArmadoBase, table=True):
__tablename__ = "cohorte_armado"
__table_args__ = (armado_unico(),)
class CohorteMiembro(CaCuModel, CohorteMiembroBase, table=True):
__tablename__ = "cohorte_miembro"
class CohorteExclusion(CaCuModel, CohorteExclusionBase, table=True):
__tablename__ = "cohorte_exclusion"
class CohorteVariable(CaCuModel, CohorteVariableBase, table=True):
__tablename__ = "cohorte_variable"
__table_args__ = (variable_con_un_valor(),)
class EvaluacionRiesgoLote(CaCuModel, EvaluacionRiesgoLoteBase, table=True):
__tablename__ = "evaluacion_riesgo_lote"
class EvaluacionRiesgo(CaCuModel, EvaluacionRiesgoBase, table=True):
__tablename__ = "evaluacion_riesgo"
__table_args__ = (evaluacion_unica(),)
-402
View File
@@ -1,402 +0,0 @@
"""CaCu's measures (`core.measures` evaluates them) and the follow-up status they stratify by."""
import statistics
from dataclasses import dataclass
from datetime import date
from core import cacu
from core.measures import (
NO_BIOPSY,
NO_DATA,
Composition,
Duration,
Measure,
Period,
Proportion,
Result,
RiskBand,
age_group,
as_day,
desc,
wilson,
)
def follow_up_status(row: dict, at: date, through: bool = False) -> str:
"""Where the patient was in her follow-up just before `at` (`through`: by the end of
`at`), from the first day of each step (`gold.cacu_follow_up`). A case already has
cancer; what follows her is survival."""
def by(first: str) -> bool:
day = as_day(row.get(first))
return day is not None and (day <= at if through else day < at)
for first, status in (("first_case", "case"), ("first_treatment", "post_treatment"),
("first_colposcopy", "post_colposcopy")): # fmt: skip
if by(first):
return status
return "pre_colposcopy"
def valid(row: dict) -> bool:
"""A cytology with a result, reported, of satisfactory (or unknown) adequacy."""
return row["result_date"] is not None and row.get("adequacy") != "unsatisfactory"
def latest(row: dict) -> tuple:
"""A patient's latest valid sample ranks highest."""
return valid(row), as_day(row["sample_date"]), row["sample_id"]
def latest_most_severe_biopsy(row: dict) -> tuple:
"""Her latest valid sample, then its most severe reported biopsy, the latest first."""
reported = row.get("biopsy_report_date") is not None
return (*latest(row), reported, row.get("severity") or 0,
desc(as_day(row.get("biopsy_report_date"))), desc(row.get("biopsy_id"))) # fmt: skip
def result(row: dict) -> str:
return row["result"] if valid(row) else NO_DATA
def histology(row: dict) -> str:
"""The chosen biopsy's histology (NO_BIOPSY without one reported)."""
if not valid(row):
return NO_DATA
if row.get("biopsy_report_date") is None:
return NO_BIOPSY
return row.get("histology") or NO_DATA
@dataclass(frozen=True)
class BiopsyRequests:
"""The biopsy requests on record, each classified at the event cutoff by its report (the
highest grade reported for the request's key). Recorded requests, not every referral the
hospital issued: the key may group orders, and cancellations are not known."""
kind: str = "composition"
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
chosen: dict[str, tuple[tuple, str]] = {}
severity = {grade: i for i, grade in enumerate(cacu.BIOPSY_SEVERITY, 1)}
for row in rows:
request = as_day(row.get("request_date"))
if request not in period or request > cutoff:
continue
reported = as_day(row.get("report_date"))
if (row.get("rows_merged") or 0) > 1:
category, rank = "ambiguous", (4, 0, date.min)
elif reported is None or reported > cutoff:
category, rank = "pending", (0, 0, date.min)
elif reported < request:
category, rank = "inconsistent", (1, 0, reported)
elif row.get("histology") is None:
category, rank = "no_grade", (2, 0, reported)
elif row["histology"] not in severity:
category, rank = "unclassified", (2, 0, reported)
else:
grade = row["histology"]
category = "high_grade" if grade in cacu.CIN2_PLUS else "below_high_grade"
rank = (3, severity[grade], reported)
key = row["request_id"]
if key not in chosen or rank > chosen[key][0]:
chosen[key] = (rank, category)
categories: dict[str, dict[str, int]] = {}
for _, category in chosen.values():
categories.setdefault(category, {"initial-population": 0})["initial-population"] += 1
count = len(chosen)
return Result({"initial-population": count, "measure-observation": count},
strata={"category": categories}) # fmt: skip
@dataclass(frozen=True)
class DiagnosisDurations:
"""Days from the sample to the diagnosis (the measure of the same name), and the median
and quartiles of each ICD-10 code the diagnosis note carries (a stratum with its own
score). Exploratory: the sample and its diagnosis are linked by their dates."""
kind: str = "continuous-variable"
strata: tuple = (("diagnosis_code", None),)
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
rule = Duration(
"days_sample_diagnosis", "diagnosis_date", "sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=lambda r: r["history"] == 0,
) # fmt: skip
overall = rule.evaluate(rows, period, cutoff)
grouped: dict[str, list[dict]] = {}
for row in {r["sample_id"]: r for r in rows}.values():
if (row["sample_date"] not in period or row["history"] != 0
or row.get("days_sample_diagnosis") is None
or as_day(row.get("diagnosis_date")) is None
or as_day(row["diagnosis_date"]) > cutoff): # fmt: skip
continue
grouped.setdefault(row.get("diagnosis_code") or "sin_codigo", []).append(row)
cells: dict[str, dict[str, int]] = {}
scores: dict[str, dict] = {}
for code, group in grouped.items():
values = sorted(float(r["days_sample_diagnosis"]) for r in group)
if len(values) == 1:
q1 = q3 = values[0]
else:
quartiles = statistics.quantiles(values, n=4, method="inclusive")
q1, q3 = quartiles[0], quartiles[2]
described = {
r["diagnosis_description"] for r in group if r.get("diagnosis_description")
}
label = code + (" | " + next(iter(described)) if len(described) == 1 else "")
cells[label] = {"measure-observation": len(values)}
scores[label] = {"value": statistics.median(values), "unit": "d", "extension": [
{"url": "https://isssteleon.org/fhir/StructureDefinition/q1", "valueDecimal": q1},
{"url": "https://isssteleon.org/fhir/StructureDefinition/q3", "valueDecimal": q3},
]} # fmt: skip
return Result(overall.populations, overall.score, overall.score_extensions, overall.unit,
strata={"diagnosis_code": cells},
stratum_scores={"diagnosis_code": scores}) # fmt: skip
def referring_cytology(cytologies: list[dict], day: date) -> dict | None:
"""Her latest valid cytology sampled and reported before `day` (a result of that same
day doesn't count: dates can't say which came first), its report at most
REFERRAL_CYTOLOGY_DAYS old."""
found = [
c for c in cytologies
if valid(c) and c.get("result") is not None
and as_day(c["date"]) < day and as_day(c["result_date"]) < day
and (day - as_day(c["result_date"])).days <= cacu.REFERRAL_CYTOLOGY_DAYS
] # fmt: skip
return max(found, key=lambda c: (as_day(c["date"]), as_day(c["result_date"]),
c["sample_id"]), default=None) # fmt: skip
def screening_round(cytology: dict | None) -> str:
"""`subsequent`: screened before (as her form says) or already past colposcopy or
treatment at the sample; `initial`: the first screening of her life, before colposcopy."""
if cytology is None:
return NO_DATA
# a referral fact is dated `date`; a gold sample `sample_date`
status = follow_up_status(cytology, as_day(cytology.get("date") or cytology["sample_date"]))
history = cytology.get("screening_history")
if history in cacu.PREVIOUS_SCREENING or status in ("post_colposcopy", "post_treatment"):
return "subsequent"
return "initial" if history == "first_time" else NO_DATA
def hpv_result(row: dict) -> str | None:
"""Her high-risk HPV result on a sample; none when it has none."""
return None if row.get("hpv") is None else "positive" if row["hpv"] else "negative"
def hpv_groups(cytology: dict | None) -> list[str]:
"""The referral PPVs' HPV groups of a referring cytology: its result and, apart, each
genotype it was positive for (they overlap with `positive`, and may with each other)."""
row = cytology or {}
found = [name for name in (hpv_result(row),) if name]
found += [name for name in ("hpv_16", "hpv_18") if row.get(name)]
return found or [NO_DATA]
@dataclass(frozen=True)
class ReferralPPV:
"""Of the patients with a procedure in the period, those whose histology confirms the
first level of PPV_HISTOLOGY. Rows are facts (`gold.cacu_referral_facts`: `fact` is
cytology, colposcopy or biopsy, each dated `date`), so the referring cytology is chosen
among those known at the evaluation's `as_of`.
A patient counts once, with her first procedure of the period that qualifies: she wasn't
a case already (at her referring sample, or at the procedure without one) and, for the
biopsy PPV, a biopsy requested that day has a histology. Its histology is that of the
biopsies requested that day and reported by the cut-off; with none, not confirmed."""
procedure: str # "colposcopy" or "biopsy"
kind: str = "proportion"
strata: tuple[tuple[str, None], ...] = (
("referral_cytology", None), ("referral_hpv", None), ("histology_level", None),
("screening_round", None),
) # fmt: skip
def _units(self, rows: list[dict], period: Period, cutoff: date):
"""Per patient counted: the histologies of her procedure and its referring cytology."""
mine: dict[str, dict[str, list[dict]]] = {}
for row in rows:
mine.setdefault(row["person_id"], {}).setdefault(row["fact"], []).append(row)
for facts in mine.values():
procedures: dict[date, list[dict]] = {}
for row in facts.get(self.procedure, []):
day = as_day(row["date"])
if day in period and day <= cutoff:
procedures.setdefault(day, []).append(row)
for day in sorted(procedures):
found = {
b["histology"] for b in facts.get("biopsy", [])
if as_day(b["date"]) == day and b.get("histology") is not None
and b.get("report_date") is not None
and day <= as_day(b["report_date"]) <= cutoff
} # fmt: skip
if self.procedure == "biopsy" and not found:
continue
cytology = referring_cytology(facts.get("cytology", []), day)
at = day if cytology is None else as_day(cytology["date"])
if follow_up_status(cytology or procedures[day][0], at) == "case":
continue
yield found, cytology
break
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
units = list(self._units(rows, period, cutoff))
def cell(members: list, level: list[str]) -> dict[str, int]:
n = len(members)
return {"initial-population": n, "denominator": n,
"numerator": sum(bool(found & set(level)) for found, _ in members)} # fmt: skip
score_level = next(iter(cacu.PPV_HISTOLOGY.values()))
total = cell(units, score_level)
strata: dict[str, dict] = {name: {} for name, _ in self.strata}
if not units:
return Result(total, strata=strata)
groups: dict[str, list] = {}
for unit in units:
cytology = unit[1]
names = (
[NO_DATA]
if cytology is None
else [g for g, codes in cacu.PPV_CYTOLOGY.items() if cytology["result"] in codes]
)
for name in names:
groups.setdefault(name, []).append(unit)
strata["referral_cytology"] = {g: cell(u, score_level) for g, u in groups.items()}
by_hpv: dict[str, list] = {}
for unit in units:
for name in hpv_groups(unit[1]):
by_hpv.setdefault(name, []).append(unit)
strata["referral_hpv"] = {g: cell(u, score_level) for g, u in by_hpv.items()}
strata["histology_level"] = {
name: cell(units, level) for name, level in cacu.PPV_HISTOLOGY.items()
}
rounds: dict[str, list] = {}
for unit in units:
rounds.setdefault(screening_round(unit[1]), []).append(unit)
strata["screening_round"] = {g: cell(u, score_level) for g, u in rounds.items()}
k, n = total["numerator"], total["denominator"]
low, high = wilson(k, n)
return Result(total, k / n, {"ic-bajo": low, "ic-alto": high}, strata=strata)
H = cacu.HORIZONS
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no cervical cancer note before
AGE = ("age_group", lambda row, p: age_group(row.get("birth_date"), p.start, cacu.AGE_GROUPS))
STATUS = ("follow_up_status", lambda row, p: follow_up_status(row, p.start))
RESULT = ("result", lambda row, p: row["result"])
SCREENING = ("screening_round", lambda row, p: screening_round(row))
def results_of(wanted: str):
"""The results of the patients in one screening round (the others are in no group)."""
return (f"result_{wanted}",
lambda row, p: result(row) if screening_round(row) == wanted else None) # fmt: skip
def genotype(name: str):
"""A genotype's result on the chosen sample (in no group when not reported)."""
return (name, lambda row, p: None if row.get(name) is None
else "positive" if row[name] else "negative") # fmt: skip
def hpv_of(wanted: str):
"""The HPV results of the patients in one screening round."""
return (f"hpv_{wanted}",
lambda row, p: hpv_result(row) if screening_round(row) == wanted else None) # fmt: skip
MEASURES = {m.id: m for m in [
Measure("IND1", "Pacientes con citología anormal", "samples",
Proportion(lambda r: r["result"] in cacu.ABNORMAL), "decrease", group="principal"),
Measure("CACU_EU13", "Tasa de detección histopatológica", "sample_biopsies",
Proportion(lambda r: r.get("histology") in cacu.DETECTION
and r.get("biopsy_report_date") is not None,
strata=(AGE, STATUS)), group="principal"),
Measure("CACU_EU7", "Pacientes evaluadas por resultado de citología", "samples",
Composition(latest, result, strata=(
AGE, STATUS, SCREENING, results_of("initial"), results_of("subsequent")))),
Measure("CACU_VPH_GENOTIPO", "Resultados de VPH por genotipo", "hpv_reports",
Composition(lambda r: (as_day(r["report_date"]),), lambda r: r["category"],
unit="sample_id", date="sample_date"),
description="Reportes VPH con fecha de reporte y algún resultado VPH, por paciente y "
"fecha de toma; periodo por toma. Los nulos no son negativos; el contrato "
"booleano actual no representa resultados indeterminados."),
Measure("CACU_BIOPSIA_RESULTADOS", "Resultados de biopsia cervical", "biopsy_reports",
Composition(lambda r: (as_day(r["report_date"]),), lambda r: r["category"],
unit="biopsy_id", date="report_date"),
description="Reportes de biopsia por paciente y fecha de solicitud, incluidos los no "
"vinculados a una toma; periodo por fecha de reporte. El estrato no_data "
"identifica reportes sin grado; la distribución clasificable lo excluye."),
Measure("CACU_BIOPSIA_SOLICITUD_CONFIRMACION",
"Resultados por solicitudes de biopsia registradas", "biopsy_requests",
BiopsyRequests(), known="order_known_at", supports_as_of=False,
description="Solicitudes de biopsia registradas por persona y fecha de solicitud, "
"según fecha de solicitud; resultados hasta el corte. La clave puede "
"agrupar órdenes y no se conocen cancelaciones ni cobertura de "
"referencias. No admite corte histórico de conocimiento as-of."),
# Her latest sample with an HPV result in the period, whatever its cytology says.
Measure("CACU_VPH", "Pacientes evaluadas por resultado de VPH", "samples",
Composition(lambda r: (as_day(r["sample_date"]), r["sample_id"]), hpv_result,
where=lambda r: r.get("hpv") is not None,
strata=(AGE, STATUS, genotype("hpv_16"), genotype("hpv_18"), SCREENING,
hpv_of("initial"), hpv_of("subsequent"))),
facts={"report_known_at": ("hpv", "hpv_16", "hpv_18")}),
Measure("CACU_CONFIRMACION_CITOLOGIA", "Confirmación histopatológica", "sample_biopsies",
Composition(latest_most_severe_biopsy, histology,
admit=lambda r: valid(r) and r["result"] in cacu.HIGH_GRADE,
strata=(RESULT,))),
# Rows become known with `known_at`; a report's values only with `report_known_at`.
*(Measure(f"CACU_VPP_{name}", f"VPP de la referencia a {title}", "referral_facts",
ReferralPPV(procedure),
facts={"report_known_at": ("result", "result_date", "adequacy",
"histology", "report_date",
"hpv", "hpv_16", "hpv_18")})
for name, title, procedure in (("COLPOSCOPIA", "colposcopía", "colposcopy"),
("BIOPSIA", "biopsia", "biopsy"))),
Measure("CACU_EU_TIEMPO_REPORTE", "Tiempo de toma a resultado de citología", "samples",
Duration("days_sample_result", "result_date", "sample_date", H["sample_to_report"],
ended="report_date"), "decrease"),
Measure("CACU_DIAS_TOMA_DIAGNOSTICO", "Tiempo de tamizaje a diagnóstico", "samples",
Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=NO_HISTORY), "decrease"),
Measure("CACU_TIEMPO_DIAGNOSTICO_CIE10", "Tiempo a diagnóstico por CIE-10 (exploratorio)",
"diagnosis_codes", DiagnosisDurations(),
description="Agrupa la fecha diagnóstica ya seleccionada por asociación temporal; "
"no confirma vínculo clínico."),
Measure("CACU_DIAS_TOMA_TRATAMIENTO", "Tiempo de tamizaje a tratamiento", "samples",
Duration("days_sample_treatment", "treatment_date", "sample_date",
H["sample_to_treatment"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_DIAGNOSTICO_TRATAMIENTO", "Tiempo de diagnóstico a tratamiento", "samples",
Duration("days_diagnosis_treatment", "diagnosis_treatment_date", "diagnosis_date",
H["diagnosis_to_treatment"],
units=lambda r: r["history"] == 0 and r["diagnosis_date"] is not None),
"decrease"),
Measure("CACU_DIAS_TOMA_COLPOSCOPIA", "Tiempo de toma de muestra a colposcopía", "samples",
Duration("days_sample_colposcopy", "colposcopy_date", "sample_date",
H["sample_to_colposcopy"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_TOMA_BIOPSIA", "Tiempo de toma de muestra a resultado de biopsia", "samples",
Duration("days_sample_biopsy", "biopsy_date", "sample_date",
H["sample_to_biopsy"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_RESULTADO_COLPOSCOPIA", "Tiempo de resultado a colposcopía", "samples",
Duration("days_result_colposcopy", "result_colposcopy_date", "result_date",
H["result_to_colposcopy"],
units=lambda r: r["history"] == 0 and r["result_date"] is not None),
"decrease"),
Measure("CACU_DIAS_COLPOSCOPIA_BIOPSIA", "Tiempo de colposcopía a biopsia", "samples",
Duration("days_colposcopy_biopsy", "biopsy_date", "result_colposcopy_date",
H["colposcopy_to_biopsy"],
units=lambda r: r["history"] == 0
and r["result_colposcopy_date"] is not None), "decrease"),
Measure("CACU_DIAS_BIOPSIA_DIAGNOSTICO", "Tiempo de biopsia a diagnóstico", "samples",
Duration("days_biopsy_diagnosis", "biopsy_diagnosis_date", "biopsy_date",
H["biopsy_to_diagnosis"],
units=lambda r: r["history"] == 0 and r["biopsy_date"] is not None),
"decrease"),
Measure("CACU_RIESGO_BANDA", "Banda de riesgo de CIN2+ en vigilancia", "risk",
RiskBand(tuple(cacu.RISK_BANDS)),
periods=("semester",), params={"model": cacu.RISK_BAND_MODEL}),
]} # fmt: skip
+17
View File
@@ -0,0 +1,17 @@
from core.cacu.paciente.model import Paciente
from core.cacu.ordenes_estudio.model import OrdenesEstudio
from core.cacu.citologia_cervical.model import CitologiaCervical
from core.cacu.biopsia_cervical.model import BiopsiaCervical
from core.cacu.nota_medica.model import NotaMedica
from core.cacu.biometria_hematica.model import BiometriaHematica
from core.cacu.episodio_clinico.model import EpisodioClinico
__all__ = [
"Paciente",
"OrdenesEstudio",
"CitologiaCervical",
"BiopsiaCervical",
"NotaMedica",
"BiometriaHematica",
"EpisodioClinico",
]
+35
View File
@@ -0,0 +1,35 @@
## nota_medica
| Columna | Fuente | Descripción |
|---|---|---|
| `nm_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | FK lógica hacia `paciente.pac_id` — resuelto en carga, nulo si no hay match |
| `pac_id_hospital` | Hospital, DG1 | Identificador hospitalario del paciente |
| `nm_id_hospital` | Hospital, — | Identificador original de la nota en el HIS |
| `nm_nota_previa_id` | Hospital, — | FK autorreferencial para cadena de seguimiento |
| `nm_tipo_nota` | Hospital, NM1 | Tipo de visita |
| `nm_especialidad` | Hospital, NM1 | Especialidad médica que emite la nota |
| `nm_fecha` | Hospital, NM3 | Fecha de la consulta o procedimiento |
| `nm_medico_tratante` | Hospital, NM4 | Médico que emite la nota |
| `nm_motivo_consulta` | Hospital, NM10 | Motivo de consulta referido o registrado |
| `nm_interrogatorio` | Hospital, NM11 | Antecedentes relevantes e historia clínica |
| `nm_diagnostico_texto` | Hospital, NM2 | Diagnóstico clínico en texto libre |
| `nm_cie_codigo` | Hospital, NM17 | Código CIE-10 del diagnóstico principal |
| `nm_cie_descripcion` | Hospital, NM17 | Descripción del código CIE-10 |
| `nm_tratamiento_texto` | Hospital, NM12 | Descripción del tratamiento indicado |
| `nm_receta` | Hospital, NM14 | Medicamentos prescritos |
| `nm_plan_estudios` | Hospital, NM15 | Estudios planeados con orden, fecha y resultado esperado |
| `nm_pronostico` | Hospital, NM13 | Pronóstico registrado por el médico |
| `nm_observaciones` | Hospital, NM16 | Observaciones adicionales del médico |
| `nm_masa_corporal` | Hospital, NM5 | Peso corporal en la visita (kg) |
| `nm_talla` | Hospital, NM5 | Talla registrada en la visita (m) |
| `nm_imc_visita` | Derivado, pipeline | IMC calculado a partir de peso y talla |
| `nm_frecuencia_cardiaca` | Hospital, NM6 | Frecuencia cardíaca (lpm) |
| `nm_frecuencia_respiratoria` | Hospital, NM7 | Frecuencia respiratoria (rpm) |
| `nm_presion_arterial_sistolica` | Hospital, NM8 | Presión arterial sistólica (mmHg) |
| `nm_presion_arterial_diastolica` | Hospital, NM8 | Presión arterial diastólica (mmHg) |
| `nm_temperatura` | Hospital, NM9 | Temperatura corporal (°C) |
---
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
+1
View File
@@ -0,0 +1 @@
from core.cacu.nota_medica.model import NotaMedica
+40
View File
@@ -0,0 +1,40 @@
from enum import Enum
class TipoNota(str, Enum):
CONSULTA = "CONSULTA"
EGRESO = "EGRESO"
INGRESO = "INGRESO"
URG_EGRESO = "URG_EGRESO"
TIPO_NOTA_ALIAS: dict[str, str] = {
"URG. EGRESO": "URG_EGRESO",
}
class Especialidad(str, Enum):
MEDICINA_FAMILIAR = "MEDICINA_FAMILIAR"
CIRUGIA_ONCOLOGICA = "CIRUGIA_ONCOLOGICA"
CLINICA_MUJER_COLPOSCOPIA = "CLINICA_MUJER_COLPOSCOPIA"
ESPECIALIDAD_ALIAS: dict[str, str] = {
"MEDICINA FAMILIAR": "MEDICINA_FAMILIAR",
"CIRUGIA ONCOLOGICA": "CIRUGIA_ONCOLOGICA",
"CLINICA DE MUJER Y COLPOSCOPIA": "CLINICA_MUJER_COLPOSCOPIA",
}
class Parentesco(str, Enum):
AFILIADO = "Afiliado"
# Other values pending confirmation with the HIS administrator.
PARENTESCO_ALIAS: dict[str, str] = {
"AFILIADO": "Afiliado",
}
class Dependencia(str, Enum):
GOBIERNO = "GOBIERNO"
CALLES_Y_CAMINOS = "CALLES Y CAMINOS"
# Tentative values, pending confirmation with the HIS administrator.
DEPENDENCIA_ALIAS: dict[str, str] = {
"CALLES Y CAMINOS": "CALLES Y CAMINOS",
}
+124
View File
@@ -0,0 +1,124 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import HOSPITAL_ID_LENGTH
class NotaMedica(CaCuModel, table=True):
"""
Notas medicas del paciente
"""
nm_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="rellenado por el loader via lookup en paciente.pac_id_hospital; puede quedar nulo",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
description="DG1: identificador hospitalario obligatorio para vincular estudios con pacientes",
)
# Bounded and indexed: part of the natural key (with pac_id_hospital)
# the import layer upserts/merges notes on.
nm_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
)
nm_nota_previa_id: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_tipo_nota: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_especialidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
nm_medico_tratante: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_motivo_consulta: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_interrogatorio: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_diagnostico_texto: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_cie_codigo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_cie_descripcion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_tratamiento_texto: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_receta: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_plan_estudios: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_pronostico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_masa_corporal: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
nm_talla: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
nm_imc_visita: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
nm_frecuencia_cardiaca: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_frecuencia_respiratoria: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_presion_arterial_sistolica: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_presion_arterial_diastolica: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_temperatura: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
+23
View File
@@ -0,0 +1,23 @@
## ordenes_estudio
Al parecer no aparece en la plataforma el pdf de la orden del estudio emitido.
Tabla de órdenes, 1 fila por solicitud médica. Fuente: TC2 parcial, TVPH2, HPC2, NM3, NM4
| Columna | Fuente | Descripción |
| ------------------------ | ---------------------------- | ----------------------------------------------------------------------------------------------------- |
| `ord_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | FK hacia paciente.pac_id, resuelto en carga por lookup en paciente |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, desnormalizado para joins sin pasar por paciente |
| `ord_numero_hospital` | Hospital, TC1, TVPH1, HPC1 | Número de orden de 5 dígitos asignado por el HIS, índice único, join lógico hacia tablas de resultado |
| `ord_tipo_estudio` | Hospital, TC1, TVPH1, HPC1 | Tipo de estudio solicitado, texto libre, enum pendiente de confirmar con administrador |
| `ord_fecha` | Hospital, TVPH2, HPC2 | Fecha en que el médico emitió la orden |
| `ord_fecha_solicitud` | Hospital, TVPH2, HPC2 | Fecha sugerida por el médico para realizar el estudio |
| `ord_fecha_resultado` | Hospital, HPC3, TVPH4 | Fecha en que el resultado estuvo disponible, nulo hasta que llegue |
| `ord_estatus` | Hospital, TVPH4, HPC3 | Estatus de la orden, texto libre, enum pendiente de confirmar con administrador |
| `ord_diagnostico` | Hospital, ord | Diagnóstico presuntivo del médico (pantalla Asignar diagnóstico) |
| `ord_observaciones` | Hospital, — | Observaciones generales de la orden |
| `ord_especialidad` | Hospital, NM1 | Especialidad del médico solicitante |
| `ord_medico_solicitante` | Hospital, NM4 | Nombre o clave del médico tratante que emite la orden |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
@@ -0,0 +1 @@
from core.cacu.ordenes_estudio.model import OrdenesEstudio
+11
View File
@@ -0,0 +1,11 @@
from enum import Enum
class TipoEstudio(str, Enum):
BIOPSIA_CHICA = "BIOPSIA_CHICA"
SOLICITUD_PAPANICOLAO_BASE_LIQUIDA = "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA"
TIPO_ESTUDIO_ALIAS: dict[str, str] = {
"BIOPSIA CHICA": "BIOPSIA_CHICA",
"SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
"Solicitud de Papanicolao en Base Liquida": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
}
+77
View File
@@ -0,0 +1,77 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import HOSPITAL_ID_LENGTH
class OrdenesEstudio(CaCuModel, table=True):
"""
Modelo ORM para órdenes de estudio.
Condensa cabecera y detalle en una sola tabla.
Una orden corresponde a un único tipo de estudio.
El resultado (citología, biopsia) referencia esta tabla via ord_numero_hospital (join logico).
"""
ord_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("paciente.pac_id"), index=True),
)
# Denormalized so studies join without going through paciente
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
ord_numero_hospital: int = Field(
sa_column=sa.Column(sa.Integer, unique=True, index=True, nullable=False),
description="TC1/TVPH1/HPC1: numero de orden de 5 digitos asignado por el HIS",
)
ord_tipo_estudio: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Citología Base líquida, Biopsia Cervical"
)
ord_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha de emisión de la orden por el médico",
)
ord_fecha_solicitud: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha sugerida por el médico para realizar el estudio",
)
ord_fecha_resultado: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha en que el resultado estuvo disponible, nulo hasta que llegue",
)
ord_estatus: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="REALIZADO E INTERPRETADO",
)
ord_diagnostico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Diagnóstico, pantalla: Asignar diagnostico",
)
ord_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
ord_especialidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="",
)
ord_medico_solicitante: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Nombre o clave del médico NM4",
)
+14
View File
@@ -0,0 +1,14 @@
## pacientes
| Columna | Fuente | Descripción |
| ---------------------- | ----------------------- | ---------------------------------------------------------------------------------------------- |
| `pac_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, índice único, permite lookup desde tablas de resultado |
| `pac_fecha_nacimiento` | Hospital, DG2 | Fecha de nacimiento |
| `pac_sexo` | Hospital, DG3 | Sexo biológico |
| `pac_codigo_postal` | Hospital, DG4 | Código postal de residencia |
| `pac_dependencia` | Hospital, DG5 | Unidad de cobertura o dependencia administrativa |
| `pac_parentesco` | Hospital, — | Parentesco del titular respecto al trabajador |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
+1
View File
@@ -0,0 +1 @@
from core.cacu.paciente.model import Paciente
+18
View File
@@ -0,0 +1,18 @@
from enum import Enum
class SexoBiologico(str, Enum):
"""
Sexo biológico del paciente.
Hasta ahora asumieremos que se guarda como texto en el mercado de datos:
("Femenino", "Masculino").
Solamente se usará en la capa de validación.
"""
F = "Femenino"
M = "Masculino"
SEXO_BIOLOGICO_ALIAS: dict[str, str] = {
"F": "Femenino",
"M": "Masculino",
"FEMENINO": "Femenino",
"MASCULINO": "Masculino",
}
+49
View File
@@ -0,0 +1,49 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import HOSPITAL_ID_LENGTH
class Paciente(CaCuModel, table=True):
"""
Modelo ORM, solamente almacena.
Se reservan las validaciones de dominio para otra capa.
"""
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# The patient's original HIS id (DG1), uniquely indexed for lookups
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), unique=True, index=True, nullable=False),
)
pac_sexo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
# IND-01: required; age at each event of interest (clinical episode) is
# computed from it.
pac_fecha_nacimiento: date = Field(
sa_column=sa.Column(sa.Date, nullable=False),
)
pac_codigo_postal: Optional[str] = Field(
default=None,
sa_column=sa.Column(
sa.CHAR(5),
),
description="Código postal de 5 dígitos",
)
pac_dependencia: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Dependencia",
)
pac_parentesco: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Parentesco",
)
-43
View File
@@ -1,43 +0,0 @@
"""The stages of one cytology's route after its sample (colposcopy, biopsy, diagnosis) as gold's
dates and the explicit biopsy links support them, known by a cut-off: each stage is
`inferred` (one source row dates it), `structured` (the biopsy is linked to the sample),
`pending` (ordered, not reported) or `ambiguous` (several sources or an impossible order).
A stage not listed is unknown."""
def _day(value) -> str | None:
return str(value)[:10] if value is not None else None
def stage_facts(sample: dict, biopsies: list[dict], events: list[dict], cutoff) -> dict:
"""Stage name -> (state, day or None) for one sample as known at `cutoff`."""
start, end = _day(sample["sample_date"]), str(cutoff)[:10]
out = {}
for kind, column in [("colposcopy", "colposcopy_date"), ("diagnosis", "diagnosis_date")]:
selected = _day(sample.get(column))
if selected and start < selected <= end:
sources = {
(e["source_table"], e["source_id"])
for e in events
if e["type"] == kind and _day(e["date"]) == selected
}
out[kind] = ("inferred", selected) if len(sources) == 1 else ("ambiguous", None)
linked = [
b
for b in biopsies
if _day(b.get("cytology_sample_date")) == start
and _day(b.get("request_date"))
and start <= _day(b["request_date"]) <= end
]
if len(linked) > 1 or any((b.get("rows_merged") or 0) > 1 for b in linked):
out["biopsy"] = ("ambiguous", None)
elif linked:
biopsy = linked[0]
reported = _day(biopsy.get("report_date"))
if reported and reported < _day(biopsy["request_date"]):
out["biopsy"] = ("ambiguous", None)
elif reported and reported <= end:
out["biopsy"] = ("structured", reported)
else:
out["biopsy"] = ("pending", None)
return out
-48
View File
@@ -1,48 +0,0 @@
"""CaMa clinical parameters: the one place they are set. dbt reads them as vars, the measures
and models import them. Codes are the platform's (core.catalog)."""
# BI-RADS, least to most severe: an incomplete study (0) asks for more and weighs more than a
# benign one; a 4 without subcategory weighs less than 4A.
BIRADS_SEVERITY = ["1", "2", "3", "0", "4", "4A", "4B", "4C", "5", "6"]
BIRADS_4_TO_6 = ["4", "4A", "4B", "4C", "5", "6"]
SUSPICIOUS = ["4", "4A", "4B", "4C", "5"] # should be confirmed by biopsy (not 6: already is)
# Biopsy grades, least to most severe.
BIOPSY_SEVERITY = ["benign", "in_situ", "invasive"]
CANCER = ["in_situ", "invasive"] # detected (detection rate)
INVASIVE = ["invasive"]
# Survival: indexed at the first biopsy reported with one of these, within the recruitment
# window (start inclusive, end exclusive).
SURVIVAL_GRADES = ["invasive"]
RECRUITMENT = ("2018-01-01", "2027-01-01")
# Inferred from clinical notes (ICD-10 without the dot; specialties are the platform's codes):
# - diagnosis: a note that resolves a mammogram, with a diagnosis ICD-10 by a diagnosing
# specialty;
# - history: a breast cancer note, whoever wrote it.
DIAGNOSIS_SPECIALTIES = ["oncology_surgery"]
HISTORY_ICD10 = [
"D05", "D050", "D051", "D057", "D059",
"C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509",
] # fmt: skip
DIAGNOSIS_ICD10 = [
"Z123", "N60", "N600", "N601", "N602", "N603", "N604", "N608", "N609", "N61", "N62", "N63",
"N64", "N640", "N641", "N642", "N643", "N644", "N645", "N648", "N649", "D24", "R92",
*HISTORY_ICD10,
] # fmt: skip
# Measures (core.measures): the horizons, in days; an interval that hasn't ended after its
# horizon counts as not ended. A diagnosis this soon after the mammogram resolves it.
HORIZONS = {"sample_to_report": 60, "to_diagnosis": 180}
AGE_GROUPS = [(40, 49), (50, 59), (60, 69)] # plus "<40" and "70+"
# The follow-up list: patients whose latest mammogram, taken within the window before the
# cut-off, is BI-RADS 4 to 6.
FOLLOW_UP_WINDOWS = [1, 3, 6, 12] # months
FOLLOW_UP_WINDOW = 3
def dbt_vars() -> dict:
"""What dbt reads (`var('cama')`)."""
return {k.lower(): v for k, v in globals().items() if k.isupper()}
+12
View File
@@ -0,0 +1,12 @@
import sqlalchemy.orm as orm
from sqlmodel import SQLModel
registry = orm.registry()
class CaMaModel(SQLModel, registry=registry):
"""Base class for every CaMa table.
Uses its own SQLAlchemy registry so table names such as `notamedica`
don't collide with CaCu's tables of the same name.
"""
@@ -0,0 +1,34 @@
## biometria_hematica
Tabla de resultados de laboratorio, 1 fila por reporte de biometría hemática.
Fuente: extracción OCR y NLP sobre PDF vinculado en Estudios Laboratorio (BH1).
Join hacia ordenes_estudio por ord_numero_hospital (lógico, sin FK constraint). Join hacia paciente por pac_id_hospital (resuelto en carga).
| Columna | Fuente | Descripción |
| ------------------------------ | -------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `bh_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | Join lógico hacia paciente.pac_id, resuelto en carga, nulo si no hay match al momento de ingesta |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, obligatorio para el join lógico hacia paciente |
| `ord_numero_hospital` | Hospital, BH4 | Número de orden HIS, join lógico hacia ordenes_estudio.ord_numero_hospital |
| `bh_fecha` | Hospital, BH2 | Fecha de solicitud del estudio; pendiente de distinción con BH3 (fecha resultado) según ETL |
| `eritrocitos_mill_ul` | Derivado, OCR sobre PDF BH1 | Conteo de eritrocitos (millones/µL) |
| `hemoglobina_g_dl` | Derivado, OCR sobre PDF BH1 | Concentración de hemoglobina (g/dL) |
| `hematocrito_pct` | Derivado, OCR sobre PDF BH1 | Hematocrito como porcentaje del volumen sanguíneo |
| `vcm_fl` | Derivado, OCR sobre PDF BH1 | Volumen corpuscular medio (fL) |
| `hcm_pg` | Derivado, OCR sobre PDF BH1 | Hemoglobina corpuscular media (pg) |
| `chcm_g_dl` | Derivado, OCR sobre PDF BH1 | Concentración de hemoglobina corpuscular media (g/dL) |
| `rdw_pct` | Derivado, OCR sobre PDF BH1 | Amplitud de distribución eritrocitaria (%) |
| `leucocitos_mil_ul` | Derivado, OCR sobre PDF BH1 | Conteo total de leucocitos (miles/µL) |
| `neutrofilos_pct` | Derivado, OCR sobre PDF BH1 | Neutrófilos totales como porcentaje del diferencial leucocitario |
| `linfocitos_pct` | Derivado, OCR sobre PDF BH1 | Linfocitos como porcentaje del diferencial leucocitario |
| `monocitos_pct` | Derivado, OCR sobre PDF BH1 | Monocitos como porcentaje del diferencial leucocitario |
| `eosinofilos_pct` | Derivado, OCR sobre PDF BH1 | Eosinófilos como porcentaje del diferencial leucocitario |
| `basofilos_pct` | Derivado, OCR sobre PDF BH1 | Basófilos como porcentaje del diferencial leucocitario |
| `neutrofilos_segmentados_pct` | Derivado, OCR sobre PDF BH1 | Neutrófilos segmentados, desglose del diferencial neutrofílico (%) |
| `neutrofilos_banda_pct` | Derivado, OCR sobre PDF BH1 | Neutrófilos en banda, desglose del diferencial neutrofílico (%) |
| `metamielocitos_pct` | Derivado, OCR sobre PDF BH1 | Metamielocitos, desglose del diferencial neutrofílico (%) |
| `mielocitos_pct` | Derivado, OCR sobre PDF BH1 | Mielocitos, desglose del diferencial neutrofílico (%) |
| `plaquetas_mil_ul` | Derivado, OCR sobre PDF BH1 | Conteo de plaquetas (miles/µL) |
| `vpm_fl` | Derivado, OCR sobre PDF BH1 | Volumen plaquetario medio (fL) |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
@@ -0,0 +1 @@
from core.cama.biometria_hematica.model import BiometriaHematica
@@ -0,0 +1,60 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import HOSPITAL_ID_LENGTH
class BiometriaHematica(CaMaModel, table=True):
"""
Modelo ORM para biometría hemática.
No hay validación en esta capa, se almacena laxamente.
"""
bh_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# Logical join, resolved on import by looking up paciente.pac_id_hospital
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
# Hospital patient id: links studies to patients
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# Logical join to ordenes_estudio.ord_numero_hospital, no FK constraint
ord_numero_hospital: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
bh_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
eritrocitos_mill_ul: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
hemoglobina_g_dl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
hematocrito_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
vcm_fl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
hcm_pg: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
chcm_g_dl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
rdw_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
leucocitos_mil_ul: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
linfocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
monocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
basofilos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
eosinofilos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
neutrofilos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
mielocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
metamielocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
neutrofilos_banda_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
neutrofilos_segmentados_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
plaquetas_mil_ul: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
vpm_fl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
+18
View File
@@ -0,0 +1,18 @@
## biopsia_mama
Una fila por reporte de biopsia mamaria · fuente: sistema estructurado + OCR/NLP sobre PDF histopatológico
| Columna | Fuente | Descripción |
| --------------------- | ------------------------------- | --------------------------------------------------------------------- |
| `bx_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital| FK hacia paciente, resuelto en el loader, nulo si no hay match |
| `pac_id_hospital` | Hospital, DG1 | Identificador hospitalario del paciente, desnormalizado |
| `ord_id` | Derivado, lookup en ordenes_estudio | FK formal a `ordenesestudio.ord_id`; el loader lo resuelve comparando `ord_numero_hospital` de este registro con `ordenes_estudio.ord_numero_hospital` |
| `ord_numero_hospital` | Hospital, BX1 | Número de orden asignado por el HIS; clave de join para resolver `ord_id` |
| `mast_id` | Derivado, lookup mast_id | FK hacia mastografia, nulo si la biopsia no tiene mastografía previa |
| `bx_fecha_solicitud` | Hospital, BX2 | Fecha de solicitud de la biopsia |
| `bx_fecha_reporte` | Hospital, BX3 | Fecha de emisión del reporte histopatológico |
| `bx_grado_histologico`| Derivado, OCR sobre PDF BX5 | Grado histológico del resultado |
| `bx_pdf_blob` | Hospital, BX5 | Contenido binario del PDF del reporte histopatológico |
| `bx_ocr_confianza` | Derivado, pipeline OCR | Score de confianza del OCR sobre este documento |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
+1
View File
@@ -0,0 +1 @@
from core.cama.biopsia_mama.model import BiopsiaMama
+19
View File
@@ -0,0 +1,19 @@
from enum import Enum
class GradoHistologicoMama(str, Enum):
BENIGNO = "BENIGNO"
CARCINOMA_IN_SITU = "CARCINOMA_IN_SITU"
CARCINOMA_INVASOR = "CARCINOMA_INVASOR"
DESCONOCIDO = "DESCONOCIDO"
class TipoEstudio(str, Enum):
BIOPSIA_CHICA = "BIOPSIA_CHICA"
SOLICITUD_PAPANICOLAO_BASE_LIQUIDA = "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA"
TIPO_ESTUDIO_ALIAS: dict[str, str] = {
"BIOPSIA CHICA": "BIOPSIA_CHICA",
"SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
"Solicitud de Papanicolao en Base Liquida": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
}
+81
View File
@@ -0,0 +1,81 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
class BiopsiaMama(CaMaModel, table=True):
"""
Modelo ORM para biopsia de mama. Fechas en sa.Date (sistema estructurado).
"""
bx_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
description="identificador hospitalario, obligatorio para vincular estudios con pacientes",
)
ord_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("ordenesestudio.ord_id"), index=True),
description="FK resuelto por el loader via lookup en ordenes_estudio.ord_numero_hospital",
)
ord_numero_hospital: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
mast_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("mastografia.mast_id"), index=True),
)
bx_fecha_solicitud: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
bx_fecha_reporte: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
bx_grado_histologico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_pdf_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(FileBlob),
)
bx_ocr_confianza: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
# VARM-04a
bx_ocr_estatus: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="valor de core.ocr.OcrEstatus guardado como texto",
)
bx_ocr_requiere_revision: Optional[bool] = Field(
default=None,
sa_column=sa.Column(sa.Boolean),
)
bx_ocr_metodo_principal: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_ocr_metodo_alternativo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
+6
View File
@@ -0,0 +1,6 @@
from core.cama.paciente.enums import SexoBiologico, SEXO_BIOLOGICO_ALIAS
from core.cama.nota_medica.enums import TipoNota, TIPO_NOTA_ALIAS, Especialidad, ESPECIALIDAD_ALIAS, Parentesco, PARENTESCO_ALIAS, Dependencia, DEPENDENCIA_ALIAS
from core.cama.ordenes_estudio.enums import TipoEstudio, TIPO_ESTUDIO_ALIAS
from core.cama.biopsia_mama.enums import GradoHistologicoMama
from core.cama.mastografia.enums import BIRADS, BIRADS_ALIAS
from core.cama.episodio_clinico.enums import TipoEpisodio, TIPO_EPISODIO_ALIAS
+17
View File
@@ -0,0 +1,17 @@
from enum import Enum
class TipoEpisodio(str, Enum):
"""IND-02: la unidad de análisis para evaluación de desempeño del
modelo es un episodio de tamizaje, diagnóstico o tratamiento."""
TAMIZAJE = "TAMIZAJE"
DIAGNOSTICO = "DIAGNOSTICO"
TRATAMIENTO = "TRATAMIENTO"
TIPO_EPISODIO_ALIAS: dict[str, str] = {
"SCREENING": "TAMIZAJE",
"DIAGNOSTIC": "DIAGNOSTICO",
"TREATMENT": "TRATAMIENTO",
}
+62
View File
@@ -0,0 +1,62 @@
from datetime import date, datetime, timezone
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import HOSPITAL_ID_LENGTH
class EpisodioClinico(CaMaModel, table=True):
"""IND-02/IND-03: clinical episode for CaMa. Same structure as
`core.cacu.episodio_clinico.model.EpisodioClinico`."""
episodio_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
)
tipo_episodio: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="valor de core.cama.episodio_clinico.enums.TipoEpisodio guardado como texto",
)
nm_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("notamedica.nm_id"), index=True),
description="nota médica cuyo contenido escrito origina/documenta el episodio",
)
cie10_codigo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
especialidad_medica: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
evento_fecha: date = Field(
sa_column=sa.Column(sa.Date, nullable=False),
description="fecha del evento de interés que define el episodio",
)
ventana_inicio: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
ventana_fin: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
episodio_anterior_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("episodioclinico.episodio_id"), index=True),
)
created_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_column=sa.Column(sa.DateTime, nullable=False),
)
-77
View File
@@ -1,77 +0,0 @@
"""CaMa's follow-up list (pure): the patients whose latest mammogram reported by the cut-off
is BI-RADS 4 to 6 and was taken within the window, with where her biopsy stands and how soon
she should be seen.
Status, from the biopsies that mammogram led to, reported by the cut-off:
- cancer: one found cancer (in situ or invasive);
- pending_biopsy: none reported;
- biopsy_no_result: the latest has no grade;
- benign_biopsy: otherwise.
Priority: high for a cancer, or a pending biopsy after a BI-RADS 5 or 6; medium for any other
pending biopsy or one without result; low otherwise."""
from datetime import date
from core import cama
from core.measures import as_day
WINDOWS = cama.FOLLOW_UP_WINDOWS
SORTS = ("-recent",)
DEFAULT_HORIZON = None
STATUS_SYSTEM = "cama-follow-up-status"
PROCEDURES = ("treatment",) # by kind (persistance.fhir: CaMa's procedure read)
REPORT_FACTS = {"mammography": "diagnosis_days"} # days from the mammogram to its diagnosis
URGENT = ["5", "6"] # BI-RADS whose pending biopsy is high priority
def _ranked(row: dict) -> tuple:
return as_day(row["exam_date"]), as_day(row["report_date"]), row["birads_rank"] or 0
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
"""From each reported mammogram and the biopsies it led to (`gold.cama_mammogram_biopsies`),
who is on the list, most recent mammogram first."""
latest: dict[str, dict] = {}
biopsies: dict[str, list[dict]] = {}
for row in rows:
exam, report = as_day(row["exam_date"]), as_day(row["report_date"])
if row["birads"] is None or report is None or not exam <= report <= cutoff:
continue
person = row["person_id"]
if person not in latest or _ranked(row) > _ranked(latest[person]):
latest[person] = row
found = as_day(row["biopsy_report_date"])
if found is not None and exam <= found <= cutoff:
biopsies.setdefault(row["mammogram_id"], []).append(row)
out = []
for person, row in latest.items():
if row["birads"] not in cama.BIRADS_4_TO_6 or not start <= as_day(row["exam_date"]):
continue
mine = biopsies.get(row["mammogram_id"], [])
shown = max(mine, key=lambda b: (as_day(b["biopsy_report_date"]), b["biopsy_id"]),
default=None) # fmt: skip
cancers = [as_day(b["biopsy_report_date"]) for b in mine if b["histology"] in cama.CANCER]
if cancers:
status, priority = "cancer", "high"
elif shown is None:
status = "pending_biopsy"
priority = "high" if row["birads"] in URGENT else "medium"
elif shown["histology"] is None:
status, priority = "biopsy_no_result", "medium"
else:
status, priority = "benign_biopsy", "low"
out.append({
"person_id": person, "birth_date": row["birth_date"], "status": status,
"priority": priority, "recent": as_day(row["exam_date"]),
"first_cancer": min(cancers, default=None),
}) # fmt: skip
return sorted(out, key=lambda r: (-r["recent"].toordinal(), r["person_id"]))
def status(row: dict, cutoff: date) -> None:
"""A patient's status exists only on the list."""
return None
def ordered(rows: list[dict], sort: str, risks: dict, horizon) -> list[dict]:
return rows
+200
View File
@@ -0,0 +1,200 @@
"""Las tablas de indicadores_kit en el dominio CaMa.
Viven en el registro de `CaMaModel`, en la misma base que el staging de
CaMa (ADR-004). Las columnas se declaran una vez en `core.indicadores`;
aquí solo se instancian. Ninguna llave foránea apunta a una tabla de
staging: `persona` es propia aunque repita a `paciente`.
"""
from core.cama.base import CaMaModel
from core.indicadores.cohortes import (
CohorteArmadoBase,
CohorteExclusionBase,
CohorteMiembroBase,
CohorteVariableBase,
EvaluacionRiesgoBase,
EvaluacionRiesgoLoteBase,
armado_unico,
evaluacion_unica,
variable_con_un_valor,
)
from core.indicadores.catalogos import (
CatEstudioBase,
CatResultadoBase,
CatValorBase,
estado_de_valor_conocido,
tipo_de_valor_conocido,
)
from core.indicadores.plata import (
ObservacionClinicaBase,
ProcedimientoClinicoBase,
clase_conocida,
indice_de_observacion,
indice_de_procedimiento,
observacion_en_catalogo,
llave_de_observacion,
llave_de_procedimiento,
)
from core.indicadores.comunes import CargaBase, PeriodoObservacionBase, PersonaDerechohabienteBase
from core.indicadores.registro import (
DefParametroBase,
DimFechaBase,
DimGrupoEdadBase,
DimPeriodoBase,
)
from core.indicadores.publicacion import (
CatEstratoBase,
CatEstratoValorBase,
CatMeasureBase,
CatMeasureEstratoBase,
CatMeasureGrupoBase,
CatMeasureResultadoBase,
CatMeasureValorBase,
MeasureReportUnidadBase,
MeasureReportUnidadEstratoBase,
contrato_y_unidad_conocidos,
origen_conocido,
poblacion_conocida,
una_poblacion_por_indicador,
unidad_de_estrato_conocida,
valor_de_estrato_en_catalogo,
)
from core.indicadores.reportes import (
MeasureReportBase,
)
class Persona(CaMaModel, PersonaDerechohabienteBase, table=True):
__tablename__ = "persona"
class PeriodoObservacion(CaMaModel, PeriodoObservacionBase, table=True):
__tablename__ = "periodo_observacion"
class Carga(CaMaModel, CargaBase, table=True):
__tablename__ = "carga"
class DefParametro(CaMaModel, DefParametroBase, table=True):
__tablename__ = "def_parametro"
class DimPeriodo(CaMaModel, DimPeriodoBase, table=True):
__tablename__ = "dim_periodo"
class DimFecha(CaMaModel, DimFechaBase, table=True):
__tablename__ = "dim_fecha"
class DimGrupoEdad(CaMaModel, DimGrupoEdadBase, table=True):
__tablename__ = "dim_grupo_edad"
class MeasureReport(CaMaModel, MeasureReportBase, table=True):
__tablename__ = "measure_report"
# --- El oro por unidad y su catálogo (§6f, MD-19) ---
class CatMeasure(CaMaModel, CatMeasureBase, table=True):
__tablename__ = "cat_measure"
__table_args__ = contrato_y_unidad_conocidos()
class CatMeasureResultado(CaMaModel, CatMeasureResultadoBase, table=True):
__tablename__ = "cat_measure_resultado"
__table_args__ = (poblacion_conocida(), una_poblacion_por_indicador())
class CatMeasureValor(CaMaModel, CatMeasureValorBase, table=True):
__tablename__ = "cat_measure_valor"
__table_args__ = (origen_conocido(),)
class CatMeasureGrupo(CaMaModel, CatMeasureGrupoBase, table=True):
__tablename__ = "cat_measure_grupo"
class CatEstrato(CaMaModel, CatEstratoBase, table=True):
__tablename__ = "cat_estrato"
__table_args__ = (unidad_de_estrato_conocida(),)
class CatEstratoValor(CaMaModel, CatEstratoValorBase, table=True):
__tablename__ = "cat_estrato_valor"
class CatMeasureEstrato(CaMaModel, CatMeasureEstratoBase, table=True):
__tablename__ = "cat_measure_estrato"
class MeasureReportUnidad(CaMaModel, MeasureReportUnidadBase, table=True):
__tablename__ = "measure_report_unidad"
class MeasureReportUnidadEstrato(CaMaModel, MeasureReportUnidadEstratoBase, table=True):
__tablename__ = "measure_report_unidad_estrato"
__table_args__ = (valor_de_estrato_en_catalogo(),)
# --- Catálogos de la plata (F1): estudio -> resultado -> valor, de core/catalogos/cama.toml ---
class CatEstudio(CaMaModel, CatEstudioBase, table=True):
__tablename__ = "cat_estudio"
class CatResultado(CaMaModel, CatResultadoBase, table=True):
__tablename__ = "cat_resultado"
__table_args__ = (tipo_de_valor_conocido(),)
class CatValor(CaMaModel, CatValorBase, table=True):
__tablename__ = "cat_valor"
__table_args__ = (estado_de_valor_conocido(),)
# --- La plata de dos tablas (F5, ADR-MD-007) ---
class Procedimiento(CaMaModel, ProcedimientoClinicoBase, table=True):
__tablename__ = "procedimiento"
__table_args__ = (clase_conocida(), llave_de_procedimiento(), indice_de_procedimiento())
class Observacion(CaMaModel, ObservacionClinicaBase, table=True):
__tablename__ = "observacion_clinica" # `observacion` choca con la CTE `observacion` del motor (T-18r)
__table_args__ = (*observacion_en_catalogo(), llave_de_observacion(), indice_de_observacion())
# --- Cohortes para modelos y estimaciones de riesgo (oro restringido, ADR-MD-003; CaMa desde MD-12) ---
class CohorteArmado(CaMaModel, CohorteArmadoBase, table=True):
__tablename__ = "cohorte_armado"
__table_args__ = (armado_unico(),)
class CohorteMiembro(CaMaModel, CohorteMiembroBase, table=True):
__tablename__ = "cohorte_miembro"
class CohorteExclusion(CaMaModel, CohorteExclusionBase, table=True):
__tablename__ = "cohorte_exclusion"
class CohorteVariable(CaMaModel, CohorteVariableBase, table=True):
__tablename__ = "cohorte_variable"
__table_args__ = (variable_con_un_valor(),)
class EvaluacionRiesgoLote(CaMaModel, EvaluacionRiesgoLoteBase, table=True):
__tablename__ = "evaluacion_riesgo_lote"
class EvaluacionRiesgo(CaMaModel, EvaluacionRiesgoBase, table=True):
__tablename__ = "evaluacion_riesgo"
__table_args__ = (evaluacion_unica(),)
+18
View File
@@ -0,0 +1,18 @@
## mastografia
Una fila por estudio de mastografía · fuente: DICOM + OCR/NLP sobre PDF de interpretación
| Columna | Fuente | Descripción |
| --------------------- | ------------------------------- | ------------------------------------------------------------------ |
| `mast_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital| FK hacia paciente, resuelto en el loader, nulo si no hay match |
| `pac_id_hospital` | Hospital, DG1 | Identificador hospitalario del paciente, desnormalizado |
| `ord_id` | Derivado, lookup en ordenes_estudio | FK formal a `ordenesestudio.ord_id`; el loader lo resuelve comparando `ord_numero_hospital` de este registro con `ordenes_estudio.ord_numero_hospital` |
| `ord_numero_hospital` | Hospital, IM1 | Número de orden asignado por el HIS; clave de join para resolver `ord_id` |
| `mast_fecha_toma` | Hospital, IM2 | Fecha de toma del estudio entregada por el sistema DICOM |
| `mast_fecha_reporte` | Hospital, IM5 | Fecha del reporte de interpretación |
| `mast_calidad_imagen` | Derivado, OCR sobre PDF IM5 | Calidad técnica del estudio para interpretación |
| `mast_birads` | Derivado, OCR sobre PDF IM5 | Clasificación BI-RADS del reporte de interpretación |
| `mast_dicom_blob` | Hospital, IM6 | Contenido binario del archivo DICOM |
| `mast_interpretacion` | Hospital, IM5 | Enlace o referencia a la interpretación del radiólogo |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
+1
View File
@@ -0,0 +1 @@
from core.cama.mastografia.model import Mastografia
+35
View File
@@ -0,0 +1,35 @@
from enum import Enum
class BIRADS(str, Enum):
B0 = "B0" # incomplete
B1 = "B1" # negative
B2 = "B2" # benign
B3 = "B3" # probably benign
B4 = "B4" # suspicious
B5 = "B5" # highly suggestive of malignancy
B6 = "B6" # known biopsy-proven malignancy
BIRADS_ALIAS: dict[str, str] = {
"BIRADS 0": "B0", "BIRADS 1": "B1", "BIRADS 2": "B2",
"BIRADS 3": "B3", "BIRADS 4": "B4", "BIRADS 5": "B5", "BIRADS 6": "B6",
"BI-RADS 0": "B0", "BI-RADS 1": "B1", "BI-RADS 2": "B2",
"BI-RADS 3": "B3", "BI-RADS 4": "B4", "BI-RADS 5": "B5", "BI-RADS 6": "B6",
"0": "B0", "1": "B1", "2": "B2", "3": "B3", "4": "B4", "5": "B5", "6": "B6",
# The 4A/4B/4C subcategories (ACR BI-RADS lexicon) are common in real
# reports; this schema doesn't track them separately, so they fold into
# the base B4 rather than being rejected as out-of-catalog.
"BIRADS 4A": "B4", "BIRADS 4B": "B4", "BIRADS 4C": "B4",
"BI-RADS 4A": "B4", "BI-RADS 4B": "B4", "BI-RADS 4C": "B4",
"4A": "B4", "4B": "B4", "4C": "B4",
# Raw hospital source values (mastografia.mast_birads) spell the
# subcategory directly onto the code, e.g. "B4A" rather than "4A".
"B4A": "B4", "B4B": "B4", "B4C": "B4",
}
class GradoHistologicoMama(str, Enum):
BENIGNO = "BENIGNO"
CARCINOMA_IN_SITU = "CARCINOMA_IN_SITU"
CARCINOMA_INVASOR = "CARCINOMA_INVASOR"
DESCONOCIDO = "DESCONOCIDO"
+62
View File
@@ -0,0 +1,62 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
class Mastografia(CaMaModel, table=True):
"""
Modelo ORM para mastografía.
"""
mast_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
description="identificador hospitalario, obligatorio para vincular estudios con pacientes",
)
ord_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("ordenesestudio.ord_id"), index=True),
description="FK resuelto por el loader via lookup en ordenes_estudio.ord_numero_hospital",
)
ord_numero_hospital: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
mast_fecha_toma: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
mast_fecha_reporte: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
mast_calidad_imagen: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
mast_birads: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
mast_dicom_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(FileBlob),
)
mast_interpretacion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="enlace o referencia a la interpretación del radiólogo; formato pendiente",
)
-114
View File
@@ -1,114 +0,0 @@
"""CaMa's measures (`core.measures` evaluates them), over the gold rows of
`persistance.measures`: mammograms, biopsies, and each mammogram with the biopsies it led to.
A mammogram's report, a biopsy's report and a diagnosis note can become known after the
mammogram itself; asked before then, a row has them empty (`facts`), so the mammogram counts
with no data instead of being left out."""
from core import cama
from core.measures import (
NO_BIOPSY,
NO_DATA,
Composition,
Duration,
Measure,
Proportion,
as_day,
desc,
)
H = cama.HORIZONS
REPORT = {"report_known_at": ("report_date", "birads", "birads_rank", "days_sample_report",
"report_diagnosis_date", "days_report_diagnosis")} # fmt: skip
DIAGNOSIS = {"diagnosis_known_at": ("diagnosis_date", "days_sample_diagnosis")}
BIOPSY = {"biopsy_known_at": ("biopsy_report_date", "histology", "histology_rank")}
def reported(row: dict) -> bool:
"""A mammogram with a reported BI-RADS."""
return row["birads"] is not None and row["report_date"] is not None
def most_severe(row: dict) -> tuple:
"""Her most severe reported mammogram ranks highest; on a tie, the latest."""
return reported(row), row["birads_rank"] or 0, as_day(row["exam_date"])
def then_its_most_severe_biopsy(row: dict) -> tuple:
"""Her most severe mammogram, then its most severe reported biopsy, the latest first."""
counted = row["biopsy_report_date"] is not None
return (*most_severe(row), counted, desc(row["histology_rank"]),
desc(as_day(row["biopsy_report_date"])), desc(row["biopsy_id"])) # fmt: skip
def birads(row: dict) -> str:
return row["birads"] if reported(row) else NO_DATA
def biopsy_histology(row: dict) -> str:
"""The chosen biopsy's grade (NO_BIOPSY when her mammogram led to none reported)."""
if row["biopsy_report_date"] is None:
return NO_BIOPSY
return row["histology"] or NO_DATA
def four_to_six(row: dict) -> bool:
return reported(row) and row["birads"] in cama.BIRADS_4_TO_6
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no breast cancer note before
BIRADS = ("birads", lambda row, p: row["birads"])
MEASURES = {m.id: m for m in [
Measure("CAMA_BIRADS", "Distribución de BI-RADS", "mammograms",
Composition(most_severe, birads, date="exam_date"), facts=REPORT),
Measure("CAMA_BIRADS456_PACIENTE",
"Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6", "mammograms",
Composition(most_severe, birads, admit=four_to_six, date="exam_date"), facts=REPORT),
Measure("CAMA_BIRADS456_MASTOGRAFIA",
"Porcentaje individual de mastografías con resultado BI-RADS 4, 5 y 6", "mammograms",
Composition(most_severe, birads, where=four_to_six, unit="mammogram_id",
date="exam_date"), facts=REPORT),
Measure("CAMA_BIRADS_CANCER_INVASOR", "BI-RADS de la mastografía previa a un cáncer invasor",
"biopsies",
Composition(lambda r: (r["birads"] is not None, as_day(r["report_date"]),
r["biopsy_id"]),
lambda r: r["birads"] or NO_DATA,
where=lambda r: r["histology"] in cama.INVASIVE, date="report_date"),
known="report_known_at"),
Measure("CAMA_BIOPSIAS", "Distribución de resultados de biopsia", "biopsies",
Composition(lambda r: (r["histology"] is not None, as_day(r["report_date"])),
lambda r: r["histology"] or NO_DATA, unit="biopsy_id",
date="report_date"),
known="report_known_at"),
Measure("CAMA_HISTOPATOLOGIA_BIRADS", "Resultado histopatológico por categoría BI-RADS",
"mammogram_biopsies",
Composition(then_its_most_severe_biopsy, biopsy_histology, admit=four_to_six,
strata=(BIRADS,), date="exam_date"),
facts=REPORT | BIOPSY),
Measure("CAMA_CONFIRMACION_BIRADS45", "Tasa de confirmación histopatológica",
"mammogram_biopsies",
Proportion(lambda r: r["biopsy_report_date"] is not None,
denominator=lambda r: r["report_date"] is not None
and r["birads"] in cama.SUSPICIOUS,
unit="mammogram_id", date="exam_date"),
"increase", group="principal", facts=REPORT | BIOPSY),
Measure("CAMA_TASA_DETECCION_HISTOPATOLOGICA", "Tasa de detección histopatológica",
"biopsies",
Proportion(lambda r: r["histology"] in cama.CANCER,
denominator=lambda r: r["histology"] in cama.BIOPSY_SEVERITY,
unit="biopsy_id", date="report_date"),
group="principal", known="report_known_at"),
Measure("CAMA_EU38A", "Días de la toma de la mastografía a su resultado", "mammograms",
Duration("days_sample_report", "report_date", "exam_date", H["sample_to_report"],
unit="mammogram_id", date="exam_date"), "decrease", facts=REPORT),
Measure("CAMA_DIAS_TOMA_DIAGNOSTICO", "Tiempo de tamizaje a diagnóstico", "mammograms",
Duration("days_sample_diagnosis", "diagnosis_date", "exam_date", H["to_diagnosis"],
units=NO_HISTORY, unit="mammogram_id", date="exam_date"),
"decrease", facts=DIAGNOSIS),
Measure("CAMA_DIAS_RESULTADO_DIAGNOSTICO", "Tiempo de resultado a diagnóstico", "mammograms",
Duration("days_report_diagnosis", "report_diagnosis_date", "report_date",
H["to_diagnosis"], units=NO_HISTORY, unit="mammogram_id",
date="report_date"),
"decrease", known="report_known_at"),
]} # fmt: skip
+17
View File
@@ -0,0 +1,17 @@
from core.cama.paciente.model import Paciente
from core.cama.ordenes_estudio.model import OrdenesEstudio
from core.cama.mastografia.model import Mastografia
from core.cama.biopsia_mama.model import BiopsiaMama
from core.cama.nota_medica.model import NotaMedica
from core.cama.biometria_hematica.model import BiometriaHematica
from core.cama.episodio_clinico.model import EpisodioClinico
__all__ = [
"Paciente",
"OrdenesEstudio",
"Mastografia",
"BiopsiaMama",
"NotaMedica",
"BiometriaHematica",
"EpisodioClinico",
]
+35
View File
@@ -0,0 +1,35 @@
## nota_medica
| Columna | Fuente | Descripción |
|---|---|---|
| `nm_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | FK lógica hacia `paciente.pac_id` — resuelto en carga, nulo si no hay match |
| `pac_id_hospital` | Hospital, DG1 | Identificador hospitalario del paciente |
| `nm_id_hospital` | Hospital, — | Identificador original de la nota en el HIS |
| `nm_nota_previa_id` | Hospital, — | FK autorreferencial para cadena de seguimiento |
| `nm_tipo_nota` | Hospital, NM1 | Tipo de visita |
| `nm_especialidad` | Hospital, NM1 | Especialidad médica que emite la nota |
| `nm_fecha` | Hospital, NM3 | Fecha de la consulta o procedimiento |
| `nm_medico_tratante` | Hospital, NM4 | Médico que emite la nota |
| `nm_motivo_consulta` | Hospital, NM10 | Motivo de consulta referido o registrado |
| `nm_interrogatorio` | Hospital, NM11 | Antecedentes relevantes e historia clínica |
| `nm_diagnostico_texto` | Hospital, NM2 | Diagnóstico clínico en texto libre |
| `nm_cie_codigo` | Hospital, NM17 | Código CIE-10 del diagnóstico principal |
| `nm_cie_descripcion` | Hospital, NM17 | Descripción del código CIE-10 |
| `nm_tratamiento_texto` | Hospital, NM12 | Descripción del tratamiento indicado |
| `nm_receta` | Hospital, NM14 | Medicamentos prescritos |
| `nm_plan_estudios` | Hospital, NM15 | Estudios planeados con orden, fecha y resultado esperado |
| `nm_pronostico` | Hospital, NM13 | Pronóstico registrado por el médico |
| `nm_observaciones` | Hospital, NM16 | Observaciones adicionales del médico |
| `nm_masa_corporal` | Hospital, NM5 | Peso corporal en la visita (kg) |
| `nm_talla` | Hospital, NM5 | Talla registrada en la visita (m) |
| `nm_imc_visita` | Derivado, pipeline | IMC calculado a partir de peso y talla |
| `nm_frecuencia_cardiaca` | Hospital, NM6 | Frecuencia cardíaca (lpm) |
| `nm_frecuencia_respiratoria` | Hospital, NM7 | Frecuencia respiratoria (rpm) |
| `nm_presion_arterial_sistolica` | Hospital, NM8 | Presión arterial sistólica (mmHg) |
| `nm_presion_arterial_diastolica` | Hospital, NM8 | Presión arterial diastólica (mmHg) |
| `nm_temperatura` | Hospital, NM9 | Temperatura corporal (°C) |
---
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
+1
View File
@@ -0,0 +1 @@
from core.cama.nota_medica.model import NotaMedica
+40
View File
@@ -0,0 +1,40 @@
from enum import Enum
class TipoNota(str, Enum):
CONSULTA = "CONSULTA"
EGRESO = "EGRESO"
INGRESO = "INGRESO"
URG_EGRESO = "URG_EGRESO"
TIPO_NOTA_ALIAS: dict[str, str] = {
"URG. EGRESO": "URG_EGRESO",
}
class Especialidad(str, Enum):
MEDICINA_FAMILIAR = "MEDICINA_FAMILIAR"
CIRUGIA_ONCOLOGICA = "CIRUGIA_ONCOLOGICA"
CLINICA_MUJER_COLPOSCOPIA = "CLINICA_MUJER_COLPOSCOPIA"
ESPECIALIDAD_ALIAS: dict[str, str] = {
"MEDICINA FAMILIAR": "MEDICINA_FAMILIAR",
"CIRUGIA ONCOLOGICA": "CIRUGIA_ONCOLOGICA",
"CLINICA DE MUJER Y COLPOSCOPIA": "CLINICA_MUJER_COLPOSCOPIA",
}
class Parentesco(str, Enum):
AFILIADO = "Afiliado"
# Other values pending confirmation with the HIS administrator.
PARENTESCO_ALIAS: dict[str, str] = {
"AFILIADO": "Afiliado",
}
class Dependencia(str, Enum):
GOBIERNO = "GOBIERNO"
CALLES_Y_CAMINOS = "CALLES Y CAMINOS"
# Tentative values, pending confirmation with the HIS administrator.
DEPENDENCIA_ALIAS: dict[str, str] = {
"CALLES Y CAMINOS": "CALLES Y CAMINOS",
}
+124
View File
@@ -0,0 +1,124 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import HOSPITAL_ID_LENGTH
class NotaMedica(CaMaModel, table=True):
"""
Notas medicas del paciente
"""
nm_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="rellenado por el loader via lookup en paciente.pac_id_hospital; puede quedar nulo",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
description="DG1: identificador hospitalario obligatorio para vincular estudios con pacientes",
)
# Bounded and indexed: part of the natural key (with pac_id_hospital)
# the import layer upserts/merges notes on.
nm_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
)
nm_nota_previa_id: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_tipo_nota: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_especialidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
nm_medico_tratante: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_motivo_consulta: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_interrogatorio: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_diagnostico_texto: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_cie_codigo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_cie_descripcion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_tratamiento_texto: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_receta: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_plan_estudios: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_pronostico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_masa_corporal: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
nm_talla: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
nm_imc_visita: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
nm_frecuencia_cardiaca: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_frecuencia_respiratoria: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_presion_arterial_sistolica: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_presion_arterial_diastolica: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_temperatura: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
+23
View File
@@ -0,0 +1,23 @@
## ordenes_estudio
Al parecer no aparece en la plataforma el pdf de la orden del estudio emitido.
Tabla de órdenes, 1 fila por solicitud médica. Fuente: TC2 parcial, TVPH2, HPC2, NM3, NM4
| Columna | Fuente | Descripción |
| ------------------------ | ---------------------------- | ----------------------------------------------------------------------------------------------------- |
| `ord_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | FK hacia paciente.pac_id, resuelto en carga por lookup en paciente |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, desnormalizado para joins sin pasar por paciente |
| `ord_numero_hospital` | Hospital, TC1, TVPH1, HPC1 | Número de orden de 5 dígitos asignado por el HIS, índice único, join lógico hacia tablas de resultado |
| `ord_tipo_estudio` | Hospital, TC1, TVPH1, HPC1 | Tipo de estudio solicitado, texto libre, enum pendiente de confirmar con administrador |
| `ord_fecha` | Hospital, TVPH2, HPC2 | Fecha en que el médico emitió la orden |
| `ord_fecha_solicitud` | Hospital, TVPH2, HPC2 | Fecha sugerida por el médico para realizar el estudio |
| `ord_fecha_resultado` | Hospital, HPC3, TVPH4 | Fecha en que el resultado estuvo disponible, nulo hasta que llegue |
| `ord_estatus` | Hospital, TVPH4, HPC3 | Estatus de la orden, texto libre, enum pendiente de confirmar con administrador |
| `ord_diagnostico` | Hospital, ord | Diagnóstico presuntivo del médico (pantalla Asignar diagnóstico) |
| `ord_observaciones` | Hospital, — | Observaciones generales de la orden |
| `ord_especialidad` | Hospital, NM1 | Especialidad del médico solicitante |
| `ord_medico_solicitante` | Hospital, NM4 | Nombre o clave del médico tratante que emite la orden |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
@@ -0,0 +1 @@
from core.cama.ordenes_estudio.model import OrdenesEstudio
+12
View File
@@ -0,0 +1,12 @@
from enum import Enum
class TipoEstudio(str, Enum):
MASTOGRAFIA = "MASTOGRAFIA" # the study this domain orders (indicadores_kit cama)
BIOPSIA_CHICA = "BIOPSIA_CHICA"
SOLICITUD_PAPANICOLAO_BASE_LIQUIDA = "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA"
TIPO_ESTUDIO_ALIAS: dict[str, str] = {
"BIOPSIA CHICA": "BIOPSIA_CHICA",
"SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
"Solicitud de Papanicolao en Base Liquida": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
}
+77
View File
@@ -0,0 +1,77 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import HOSPITAL_ID_LENGTH
class OrdenesEstudio(CaMaModel, table=True):
"""
Modelo ORM para órdenes de estudio.
Condensa cabecera y detalle en una sola tabla.
Una orden corresponde a un único tipo de estudio.
El resultado (citología, biopsia) referencia esta tabla via ord_numero_hospital (join logico).
"""
ord_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("paciente.pac_id"), index=True),
)
# Denormalized so studies join without going through paciente
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
ord_numero_hospital: int = Field(
sa_column=sa.Column(sa.Integer, unique=True, index=True, nullable=False),
description="TC1/TVPH1/HPC1: numero de orden de 5 digitos asignado por el HIS",
)
ord_tipo_estudio: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Citología Base líquida, Biopsia Cervical"
)
ord_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha de emisión de la orden por el médico",
)
ord_fecha_solicitud: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha sugerida por el médico para realizar el estudio",
)
ord_fecha_resultado: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha en que el resultado estuvo disponible, nulo hasta que llegue",
)
ord_estatus: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="REALIZADO E INTERPRETADO",
)
ord_diagnostico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Diagnóstico, pantalla: Asignar diagnostico",
)
ord_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
ord_especialidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="",
)
ord_medico_solicitante: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Nombre o clave del médico NM4",
)
+14
View File
@@ -0,0 +1,14 @@
## pacientes
| Columna | Fuente | Descripción |
| ---------------------- | ----------------------- | ---------------------------------------------------------------------------------------------- |
| `pac_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, índice único, permite lookup desde tablas de resultado |
| `pac_fecha_nacimiento` | Hospital, DG2 | Fecha de nacimiento |
| `pac_sexo` | Hospital, DG3 | Sexo biológico |
| `pac_codigo_postal` | Hospital, DG4 | Código postal de residencia |
| `pac_dependencia` | Hospital, DG5 | Unidad de cobertura o dependencia administrativa |
| `pac_parentesco` | Hospital, — | Parentesco del titular respecto al trabajador |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
+1
View File
@@ -0,0 +1 @@
from core.cama.paciente.model import Paciente
+18
View File
@@ -0,0 +1,18 @@
from enum import Enum
class SexoBiologico(str, Enum):
"""
Sexo biológico del paciente.
Hasta ahora asumieremos que se guarda como texto en el mercado de datos:
("Femenino", "Masculino").
Solamente se usará en la capa de validación.
"""
F = "Femenino"
M = "Masculino"
SEXO_BIOLOGICO_ALIAS: dict[str, str] = {
"F": "Femenino",
"M": "Masculino",
"FEMENINO": "Femenino",
"MASCULINO": "Masculino",
}
+49
View File
@@ -0,0 +1,49 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import HOSPITAL_ID_LENGTH
class Paciente(CaMaModel, table=True):
"""
Modelo ORM, solamente almacena.
Se reservan las validaciones de dominio para otra capa.
"""
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# The patient's original HIS id (DG1), uniquely indexed for lookups
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), unique=True, index=True, nullable=False),
)
pac_sexo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
# IND-01: required; age at each event of interest (clinical episode) is
# computed from it.
pac_fecha_nacimiento: date = Field(
sa_column=sa.Column(sa.Date, nullable=False),
)
pac_codigo_postal: Optional[str] = Field(
default=None,
sa_column=sa.Column(
sa.CHAR(5),
),
description="Código postal de 5 dígitos",
)
pac_dependencia: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Dependencia",
)
pac_parentesco: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Parentesco",
)
-188
View File
@@ -1,188 +0,0 @@
"""The platform's clinical catalog: every study, the events it is made of, its fields, and the
code systems their values come from. It is data (the YAML files beside this module) and
changes only by a reviewed commit; nothing ships that it doesn't name.
Everything that validates, stores or serves a clinical value reads it: the pydantic model of
each study (what a pipeline's target checks rows against), the long silver tables and their
wide views (dbt), and the FHIR conformance resources the API serves.
"""
from datetime import date
from functools import cache
from pathlib import Path
from typing import Annotated, Any, ClassVar, Literal
import yaml
from pydantic import BaseModel, ConfigDict, Field, create_model, model_validator
HERE = Path(__file__).parent
EventClass = Literal["order", "encounter", "sample", "report", "part"]
# `file`: a document or signal kept whole (an EEG); silver holds its content hash, the
# platform keeps the content once (persistance.files).
ValueType = Literal["code", "boolean", "number", "date", "text", "file"]
class System(BaseModel):
model_config = ConfigDict(extra="forbid")
url: str
title: str
external: bool = False # a standard system we name but don't publish
class Event(BaseModel):
model_config = ConfigDict(extra="forbid")
date: str # the field that dates it
parent: EventClass | None = None
class FieldDef(BaseModel):
model_config = ConfigDict(extra="forbid")
type: ValueType
event: EventClass
title: str
system: str | None = None
codes: dict[str, str] = {} # allowed code -> display; empty: any code of `system`
pattern: str | None = None
unit: str | None = None
required: bool = False
@model_validator(mode="after")
def _codes_have_a_system(self):
if self.type == "code" and self.system is None:
raise ValueError("a code field names its system")
if self.type != "code" and (self.codes or self.system):
raise ValueError("only code fields take a system and codes")
return self
class Study(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str
key: list[str] # fields that, with the person, identify one study instance
events: dict[EventClass, Event]
fields: dict[str, FieldDef]
@model_validator(mode="after")
def _consistent(self):
for name in self.key:
if name not in self.fields:
raise ValueError(f"key field {name} is not a field")
for cls, event in self.events.items():
if self.fields.get(event.date, None) is None or self.fields[event.date].type != "date":
raise ValueError(f"{cls}: its date {event.date} is not a date field")
if event.parent and event.parent not in self.events:
raise ValueError(f"{cls}: parent {event.parent} is not an event")
for name, f in self.fields.items():
if f.event not in self.events:
raise ValueError(f"{name}: event {f.event} is not one of the study's")
return self
def _load(name: str) -> dict:
return yaml.safe_load((HERE / f"{name}.yaml").read_text(encoding="utf-8"))
@cache
def systems() -> dict[str, System]:
return {k: System.model_validate(v) for k, v in _load("systems").items()}
@cache
def files() -> dict[str, list[str]]:
"""Each catalog file (a domain, or `common` to all) and the studies it defines."""
return {
path.stem: list(_load(path.stem))
for path in sorted(HERE.glob("*.yaml"))
if path.stem != "systems"
}
def of_domain(domain: str) -> list[str]:
"""The studies a domain serves: its own and the common ones."""
return [*files().get(domain, []), *files().get("common", [])]
@cache
def studies() -> dict[str, Study]:
"""Every study of every catalog file, by name (names are unique across files)."""
found: dict[str, Study] = {}
for path in sorted(HERE.glob("*.yaml")):
if path.stem == "systems":
continue
for name, spec in _load(path.stem).items():
if name in found:
raise ValueError(f"study {name} is defined twice")
study = Study.model_validate(spec)
unknown = {f.system for f in study.fields.values() if f.system} - set(systems())
if unknown:
raise ValueError(f"{name}: unknown systems {sorted(unknown)}")
found[name] = study
return found
class Record(BaseModel):
"""One row of a study, as a pipeline's target receives it."""
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
key: ClassVar[tuple[str, ...]] = ()
study: ClassVar[str] = ""
_TYPES: dict[str, Any] = {
"boolean": bool,
"number": float,
"date": date,
"text": str,
"file": str,
} # fmt: skip (a file field holds its content hash)
def _annotation(f: FieldDef) -> Any:
if f.type == "code" and f.codes:
kind: Any = Literal[tuple(f.codes)] # type: ignore[valid-type]
elif f.type == "code":
kind = Annotated[str, Field(pattern=f.pattern)] if f.pattern else str
else:
kind = _TYPES[f.type]
return kind if f.required else kind | None
@cache
def model(study: str) -> type[Record]:
"""The pydantic model a row of this study is checked against."""
spec = studies()[study]
fields = { # titled as the catalog names them (forms and review show the titles)
name: (_annotation(f), Field(... if f.required else None, title=f.title))
for name, f in spec.fields.items()
}
found = create_model(study, __base__=Record, **fields) # type: ignore[call-overload]
found.key = tuple(spec.key)
found.study = study
return found
def value_column(f: FieldDef) -> str:
"""The typed column of the long observation table a field's value is stored in."""
return {"boolean": "value_bool", "number": "value_num", "date": "value_date"}.get(
f.type, "value_text"
)
def dbt_vars() -> dict:
"""What dbt reads (`var('catalog')`): each study's key, events and typed fields."""
return {
name: {
"key": s.key,
"events": {c: e.model_dump() for c, e in s.events.items()},
"fields": {
f: {
"type": d.type,
"event": d.event,
"column": value_column(d),
"codes": list(d.codes),
}
for f, d in s.fields.items()
},
}
for name, s in studies().items()
}
-117
View File
@@ -1,117 +0,0 @@
# Cervical cancer screening.
cervical_cytology:
title: Citología cervical
key: [sample_date]
events:
sample: {date: sample_date}
report: {date: report_date, parent: sample}
fields:
sample_date: {type: date, event: sample, title: Fecha de toma, required: true}
screening_history:
type: code
event: sample
title: Detección de cáncer de cérvix
system: cervical-screening-history
codes:
first_time: Primera vez en la vida
1_year_or_less: Un año o menos
2_years: 2 años
3_years_or_more: 3 o más años
# Condiciones ginecoobstétricas a la detección, as recorded at the sample: true when the
# form says it; otherwise unknown, never false (the source records only one of them).
gyn_puerperium: {type: boolean, event: sample, title: "Puerperio postparto o postaborto"}
gyn_pregnancy: {type: boolean, event: sample, title: "Embarazo actual"}
gyn_iud: {type: boolean, event: sample, title: "DIU in situ"}
gyn_hormonal_treatment: {type: boolean, event: sample, title: "Tratamiento hormonal"}
gyn_other_treatment: {type: boolean, event: sample, title: "Otro tratamiento ginecológico"}
gyn_postmenopause: {type: boolean, event: sample, title: "Posmenopausia"}
gyn_hysterectomy: {type: boolean, event: sample, title: "Histerectomía"}
gyn_not_applicable: {type: boolean, event: sample, title: "Condiciones ginecoobstétricas: no aplica"}
# Actualmente presenta, recorded like the conditions above: true or unknown, never false.
presents_discharge: {type: boolean, event: sample, title: "Actualmente presenta: flujo"}
presents_vulvar_pruritus: {type: boolean, event: sample, title: "Actualmente presenta: prurito o ardor vulvar"}
presents_abnormal_bleeding: {type: boolean, event: sample, title: "Actualmente presenta: sangrado anormal"}
presents_none: {type: boolean, event: sample, title: "Actualmente presenta: ninguno"}
cervix_exam:
type: code
event: sample
title: A la exploración se observa
system: cervix-exam
codes:
healthy: Cuello sano
abnormal_with_lesion: Cuello anormal con lesión
not_visible: No se observa cuello
report_date: {type: date, event: report, title: Fecha de reporte}
adequacy:
type: code
event: report
title: Calidad de la muestra
system: adequacy
codes: {satisfactory: Satisfactoria, unsatisfactory: Insatisfactoria}
result:
type: code
event: report
title: Resultado (Bethesda)
system: bethesda
codes:
NILM: Negativo para lesión intraepitelial o malignidad
ASC-US: Células escamosas atípicas de significado indeterminado
ASC-H: Células escamosas atípicas, no se descarta LIEAG
LSIL: Lesión intraepitelial escamosa de bajo grado
HSIL: Lesión intraepitelial escamosa de alto grado
CIS: Carcinoma in situ
hpv: {type: boolean, event: report, title: VPH de alto riesgo}
hpv_16: {type: boolean, event: report, title: VPH 16}
hpv_18: {type: boolean, event: report, title: VPH 18}
# The cytologist's additional findings, free text on the form (known with the report).
# A finding is true when the text states it; otherwise unknown, never false.
cyto_findings_text: {type: text, event: report, title: Hallazgos adicionales}
cyto_inflammation: {type: boolean, event: report, title: "Inflamación"}
cyto_reactive_changes: {type: boolean, event: report, title: "Cambios reactivos"}
cyto_bacterial_vaginosis_flora: {type: boolean, event: report, title: "Flora sugestiva de vaginosis bacteriana"}
cyto_candida: {type: boolean, event: report, title: "Microorganismos compatibles con Candida sp"}
cyto_bacillary_flora_cytolysis: {type: boolean, event: report, title: "Aumento de la flora bacilar con citólisis"}
cyto_intermediate_cytolysis: {type: boolean, event: report, title: "Citólisis de las células intermedias"}
cyto_trichomonas: {type: boolean, event: report, title: "Trichomonas vaginalis"}
cyto_leptothrix: {type: boolean, event: report, title: "Microorganismos compatibles con Leptothrix"}
cyto_actinomyces_organisms: {type: boolean, event: report, title: "Microorganismos compatibles con Actinomyces sp"}
cyto_actinomyces_changes: {type: boolean, event: report, title: "Cambios celulares compatibles con Actinomyces sp"}
cyto_herpes_simplex_changes: {type: boolean, event: report, title: "Cambios celulares compatibles con virus herpes simple"}
cyto_squamous_tubular_metaplasia: {type: boolean, event: report, title: "Metaplasia escamosa tubular"}
cyto_keratotic_changes: {type: boolean, event: report, title: "Cambios queratósicos"}
cyto_pregnancy_changes: {type: boolean, event: report, title: "Cambios asociados al embarazo"}
cyto_atrophy: {type: boolean, event: report, title: "Atrofia"}
cyto_hypoestrogenism: {type: boolean, event: report, title: "Hipoestrogenismo"}
cyto_radiotherapy_effect: {type: boolean, event: report, title: "Efecto de radioterapia"}
cyto_iud_changes: {type: boolean, event: report, title: "Cambios compatibles con dispositivo intrauterino"}
cyto_post_hysterectomy_glandular_cells: {type: boolean, event: report, title: "Células glandulares post-histerectomía"}
cyto_bacteria: {type: boolean, event: report, title: "Bacterias"}
cyto_herpes_image: {type: boolean, event: report, title: "Imagen del virus del herpes"}
cyto_fungi: {type: boolean, event: report, title: "Hongos"}
cyto_radiation: {type: boolean, event: report, title: "Cambios reactivos: radiación"}
cyto_repair: {type: boolean, event: report, title: "Cambios reactivos: reparación"}
cyto_iud_effect: {type: boolean, event: report, title: "Efecto del DIU"}
cyto_endometrial_cells_40_plus: {type: boolean, event: report, title: "Células endometriales, 40 años o más"}
cyto_findings_none: {type: boolean, event: report, title: "Hallazgos adicionales: ninguno"}
cervical_biopsy:
title: Biopsia cervical
key: [request_date]
events:
order: {date: request_date}
report: {date: report_date, parent: order}
fields:
request_date: {type: date, event: order, title: Fecha de solicitud, required: true}
cytology_sample_date: {type: date, event: order, title: Toma de la citología que la originó}
report_date: {type: date, event: report, title: Fecha de reporte}
histology:
type: code
event: report
title: Histología
system: who-cervical-histology
codes:
normal: Sin lesión
LSIL: Lesión intraepitelial escamosa de bajo grado (CIN 1)
HSIL: Lesión intraepitelial escamosa de alto grado (CIN 2-3)
CIS: Carcinoma in situ
carcinoma: Carcinoma invasor
-134
View File
@@ -1,134 +0,0 @@
# Breast cancer screening.
mammography:
title: Mastografía
key: [exam_date]
events:
sample: {date: exam_date}
report: {date: report_date, parent: sample}
fields:
exam_date: {type: date, event: sample, title: Fecha del estudio, required: true}
report_date: {type: date, event: report, title: Fecha de reporte}
adequacy:
type: code
event: report
title: Calidad de la imagen
system: adequacy
codes: {satisfactory: Satisfactoria, unsatisfactory: Insatisfactoria}
birads:
type: code
event: report
title: BI-RADS
system: bi-rads
codes:
'0': Incompleta, requiere estudios adicionales
'1': Negativa
'2': Hallazgos benignos
'3': Probablemente benigna
'4': Sospechosa
4A: Sospecha baja de malignidad
4B: Sospecha moderada de malignidad
4C: Sospecha alta de malignidad
'5': Altamente sugestiva de malignidad
'6': Malignidad confirmada por biopsia
breast_biopsy:
title: Biopsia de mama
key: [request_date, mammogram_exam_date]
events:
order: {date: request_date}
report: {date: report_date, parent: order}
fields:
request_date: {type: date, event: order, title: Fecha de solicitud, required: true}
mammogram_exam_date: {type: date, event: order, title: Mastografía que la originó}
report_date: {type: date, event: report, title: Fecha de reporte}
histology:
type: code
event: report
title: Histología
system: breast-histology
codes: {benign: Benigno, in_situ: In situ, invasive: Invasor}
histologic_type:
type: code
event: report
title: Tipo histológico (CIE-O-3)
system: icd-o-3
grade:
type: code
event: report
title: Grado histológico (Nottingham)
system: nottingham-grade
codes: {'1': Grado 1, '2': Grado 2, '3': Grado 3}
er:
type: code
event: report
title: Receptor de estrógeno
system: receptor-status
codes: &receptor {positive: Positivo, negative: Negativo}
pr:
type: code
event: report
title: Receptor de progesterona
system: receptor-status
codes: *receptor
her2:
type: code
event: report
title: HER2
system: receptor-status
codes: *receptor
ki67_pct: {type: number, event: report, title: Ki-67, unit: '%'}
size_mm: {type: number, event: report, title: Tamaño del tumor, unit: mm}
positive_nodes: {type: number, event: report, title: Ganglios linfáticos positivos}
stage:
type: code
event: report
title: Estadio clínico (AJCC)
system: ajcc-stage
codes:
'0': Estadio 0
I: Estadio I (sin subgrupo)
II: Estadio II (sin subgrupo)
III: Estadio III (sin subgrupo)
IA: Estadio IA
IB: Estadio IB
IIA: Estadio IIA
IIB: Estadio IIB
IIIA: Estadio IIIA
IIIB: Estadio IIIB
IIIC: Estadio IIIC
IV: Estadio IV
breast_treatment:
title: Tratamiento de cáncer de mama
key: [start_date, kind]
events:
encounter: {date: start_date}
fields:
start_date: {type: date, event: encounter, title: Fecha de inicio, required: true}
kind:
type: code
event: encounter
title: Tratamiento
system: breast-treatment
required: true
codes:
breast_conserving_surgery: Cirugía conservadora
mastectomy: Mastectomía
chemotherapy: Quimioterapia
radiotherapy: Radioterapia
hormone_therapy: Hormonoterapia
anti_her2: Terapia anti-HER2
breast_recurrence:
title: Recurrencia de cáncer de mama
key: [diagnosis_date]
events:
encounter: {date: diagnosis_date}
fields:
diagnosis_date: {type: date, event: encounter, title: Fecha de diagnóstico, required: true}
site:
type: code
event: encounter
title: Sitio de la recurrencia
system: breast-recurrence-site
codes: {local: Local, regional: Regional, distant: A distancia}
-36
View File
@@ -1,36 +0,0 @@
# Studies every domain shares.
clinical_note:
title: Nota médica
key: [note_date, specialty]
events:
encounter: {date: note_date}
fields:
note_date: {type: date, event: encounter, title: Fecha de la nota}
specialty:
type: code
event: encounter
title: Especialidad
system: specialty
codes:
colposcopy: Clínica de la mujer y colposcopia
oncology_surgery: Cirugía oncológica
medical_oncology: Oncología médica
radiation_oncology: Radio-oncología
family_medicine: Medicina familiar
pediatric_neurology: Neurología pediátrica
icd10:
type: code
event: encounter
title: Diagnóstico (CIE-10)
system: icd-10
pattern: '^[A-Z]\d{2}(\.\d{1,2})?$'
reason: {type: text, event: encounter, title: Motivo de consulta}
diagnosis_text: {type: text, event: encounter, title: Diagnóstico como se escribió}
death:
title: Defunción
key: []
events:
encounter: {date: death_date}
fields:
death_date: {type: date, event: encounter, title: Fecha de defunción, required: true}
-52
View File
@@ -1,52 +0,0 @@
# The code systems the platform's fields take their codes from. External systems are named by
# their canonical URI; only the codes a field allows are listed with the field.
bethesda:
url: https://isssteleon.org/fhir/CodeSystem/bethesda
title: Sistema Bethesda (citología cervical)
who-cervical-histology:
url: https://isssteleon.org/fhir/CodeSystem/who-cervical-histology
title: Clasificación OMS de lesiones cervicales (histología)
cervical-screening-history:
url: https://isssteleon.org/fhir/CodeSystem/cervical-screening-history
title: Antecedente de detección de cáncer de cérvix
cervix-exam:
url: https://isssteleon.org/fhir/CodeSystem/cervix-exam
title: Exploración del cuello uterino
bi-rads:
url: https://isssteleon.org/fhir/CodeSystem/bi-rads
title: BI-RADS
icd-10:
url: http://hl7.org/fhir/sid/icd-10
title: CIE-10
external: true
adequacy:
url: https://isssteleon.org/fhir/CodeSystem/adequacy
title: Calidad de la muestra
specialty:
url: https://isssteleon.org/fhir/CodeSystem/specialty
title: Especialidades
breast-histology:
url: https://isssteleon.org/fhir/CodeSystem/breast-histology
title: Histología de mama
ados2-module:
url: https://isssteleon.org/fhir/CodeSystem/ados2-module
title: Módulos del ADOS-2
icd-o-3:
url: http://terminology.hl7.org/CodeSystem/icd-o-3
title: CIE-O-3 (morfología)
external: true
nottingham-grade:
url: https://isssteleon.org/fhir/CodeSystem/nottingham-grade
title: Grado histológico de Nottingham
receptor-status:
url: https://isssteleon.org/fhir/CodeSystem/receptor-status
title: Estado de receptores hormonales y HER2
ajcc-stage:
url: https://isssteleon.org/fhir/CodeSystem/ajcc-stage
title: Estadio clínico AJCC (grupo)
breast-treatment:
url: https://isssteleon.org/fhir/CodeSystem/breast-treatment
title: Tratamientos de cáncer de mama
breast-recurrence-site:
url: https://isssteleon.org/fhir/CodeSystem/breast-recurrence-site
title: Sitio de la recurrencia de cáncer de mama
-60
View File
@@ -1,60 +0,0 @@
# Autism (TEA) screening: M-CHAT, ADOS-2, EEG; the neurology note that confirms the diagnosis
# is the common clinical note (specialty pediatric_neurology).
mchat:
title: M-CHAT-R/F
key: [screening_date]
events:
encounter: {date: screening_date}
fields:
screening_date: {type: date, event: encounter, title: Fecha del M-CHAT, required: true}
score: {type: number, event: encounter, title: Puntaje total (0 a 20)}
ados2:
title: ADOS-2
key: [evaluation_date]
events:
encounter: {date: evaluation_date}
fields:
evaluation_date: {type: date, event: encounter, title: Fecha de evaluación, required: true}
module:
type: code
event: encounter
title: Módulo
system: ados2-module
codes: {toddler: Módulo para niños pequeños, module_1: Módulo 1, module_2: Módulo 2, module_3: Módulo 3}
# The 22 items by what they observe (the same meaning in every module), each 0 to 3.
vocalization_directed: {type: number, event: encounter, title: Frecuencia de la vocalización espontánea dirigida a otros}
pointing: {type: number, event: encounter, title: Señalar}
gestures: {type: number, event: encounter, title: Gestos}
unusual_eye_contact: {type: number, event: encounter, title: Contacto visual inusual}
facial_expressions: {type: number, event: encounter, title: Expresiones faciales dirigidas a otros}
gaze_integration: {type: number, event: encounter, title: Integración de la mirada y otras conductas}
shared_enjoyment: {type: number, event: encounter, title: Disfrute compartido durante la interacción}
response_to_name: {type: number, event: encounter, title: Respuesta al nombre}
ignoring: {type: number, event: encounter, title: Ignorar}
requesting: {type: number, event: encounter, title: Pedir}
showing: {type: number, event: encounter, title: Mostrar}
joint_attention_initiation: {type: number, event: encounter, title: Iniciación espontánea de la atención conjunta}
joint_attention_response: {type: number, event: encounter, title: Respuesta a la atención conjunta}
social_overtures_quality: {type: number, event: encounter, title: Características de las iniciaciones sociales}
social_overtures_caregiver: {type: number, event: encounter, title: Cantidad de acercamientos sociales al cuidador}
reciprocal_communication: {type: number, event: encounter, title: Cantidad de comunicación social recíproca}
rapport_quality: {type: number, event: encounter, title: Calidad general de la relación}
intonation: {type: number, event: encounter, title: Entonación de las vocalizaciones o verbalizaciones}
stereotyped_language: {type: number, event: encounter, title: Uso estereotipado o idiosincrásico de palabras o frases}
unusual_sensory_interest: {type: number, event: encounter, title: Interés sensorial inusual}
hand_finger_mannerisms: {type: number, event: encounter, title: Manierismos de manos y dedos}
repetitive_interests: {type: number, event: encounter, title: Intereses inusualmente repetitivos}
social_affect_total: {type: number, event: encounter, title: Total de afectación social (impreso)}
restricted_repetitive_total: {type: number, event: encounter, title: Total de comportamiento restringido y repetitivo (impreso)}
overall_total: {type: number, event: encounter, title: Puntuación total global (impresa)}
eeg:
title: Electroencefalograma
key: [study_date]
events:
sample: {date: study_date}
fields:
study_date: {type: date, event: sample, title: Fecha del estudio, required: true}
lab_record_id: {type: text, event: sample, title: Registro del laboratorio}
edf: {type: file, event: sample, title: Registro EDF}
+23
View File
@@ -0,0 +1,23 @@
# Catálogos de la plata (F1)
Un TOML por proyecto: estudio → resultado → valor.
El paso `catalogos` de `webapi.orquestacion` los materializa en `cat_estudio`, `cat_resultado` y `cat_valor`
(`core/indicadores/catalogos.py`) antes de cargar. Un valor que sale del TOML pasa a `retirado`; nunca se borra.
```toml
[<estudio>]
etiqueta = "..."
codigos_hospital = ["..."] # cómo lo nombra el hospital (tipo de estudio de la orden, instrumento)
[<estudio>.resultados.<resultado>] # resultado_id = "<estudio>.<resultado>"
etiqueta = "..."
tipo_valor = "codigo" # codigo, booleano, numero, fecha, texto, externo
unidad = "min" # opcional (numero)
sistema = "CIE-10" # solo externo
valores = [ # solo codigo; el orden de la lista es el de presentación
{ valor = "NORMAL", etiqueta = "Normal" },
]
```
Los valores son los que llegan del hospital (los enums de Core). Las etiquetas y los colores de las figuras
siguen en `parametros.toml` del kit hasta F3; `indicadores_kit/tests/test_catalogos.py` exige que coincidan.
+145
View File
@@ -0,0 +1,145 @@
# Catálogo de CaCu (F1). Valores: los enums de Core (`core/cacu/*/enums.py`) y lo que guarda la carga.
[citologia]
etiqueta = "Citología cervical"
codigos_hospital = ["SOLICITUD_PAPANICOLAO_BASE_LIQUIDA", "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA"]
[citologia.resultados.calidad_muestra]
etiqueta = "Calidad de la muestra"
tipo_valor = "codigo"
valores = [
{ valor = "SATISFACTORIO", etiqueta = "Satisfactoria" },
{ valor = "INSATISFACTORIO", etiqueta = "Insatisfactoria" },
]
[citologia.resultados.bethesda]
etiqueta = "Células escamosas (Bethesda)"
tipo_valor = "codigo"
valores = [
{ valor = "NORMAL", etiqueta = "Normal" },
{ valor = "ASC-US", etiqueta = "ASC-US" },
{ valor = "LIEBG", etiqueta = "LIEBG" },
{ valor = "ASC-H", etiqueta = "ASC-H" },
{ valor = "LIEAG", etiqueta = "LIEAG" },
{ valor = "CIS", etiqueta = "Carcinoma in situ" },
]
[citologia.resultados.celulas_glandulares]
etiqueta = "Células glandulares"
tipo_valor = "texto"
[citologia.resultados.carcinoma_invasor]
etiqueta = "Carcinoma invasor"
tipo_valor = "texto"
[citologia.resultados.dx_lesion]
etiqueta = "Diagnóstico de la lesión"
tipo_valor = "texto"
[vph]
etiqueta = "Prueba de VPH"
[vph.resultados.resultado]
etiqueta = "VPH de alto riesgo"
tipo_valor = "codigo"
valores = [
{ valor = "NEGATIVO", etiqueta = "Negativo" },
{ valor = "POSITIVO", etiqueta = "Positivo" },
{ valor = "INDETERMINADO", etiqueta = "Indeterminado" },
]
[vph.resultados.genotipo_16_18]
etiqueta = "Genotipo 16 o 18"
tipo_valor = "booleano"
[vph.resultados.genotipo_16]
etiqueta = "Genotipo 16"
tipo_valor = "booleano"
[vph.resultados.genotipo_18]
etiqueta = "Genotipo 18"
tipo_valor = "booleano"
[biopsia]
etiqueta = "Biopsia cervical"
codigos_hospital = ["BIOPSIA_CHICA"]
[biopsia.resultados.grado]
etiqueta = "Grado histológico"
tipo_valor = "codigo"
valores = [
{ valor = "NORMAL", etiqueta = "Normal" },
{ valor = "LIEBG", etiqueta = "LIEBG (CIN 1)" },
{ valor = "LIEAG", etiqueta = "LIEAG (CIN 2 y 3)" },
{ valor = "CIS", etiqueta = "Carcinoma in situ" },
{ valor = "CARCINOMA", etiqueta = "Carcinoma invasor" },
{ valor = "DESCONOCIDO", etiqueta = "Desconocido" },
]
[biopsia.resultados.fecha_solicitud]
etiqueta = "Fecha de solicitud"
tipo_valor = "fecha"
[nota_medica]
etiqueta = "Nota médica"
[nota_medica.resultados.diagnostico]
etiqueta = "Diagnóstico"
tipo_valor = "externo"
sistema = "CIE-10"
# El motivo de consulta, tal como lo escribe el hospital (p. ej. «ACUDE A COLPOSCOPIA»). La plata no lo
# normaliza (I-K61): quien lo compare (el estatus de seguimiento, T-24c) lo normaliza con sus reglas.
[nota_medica.resultados.motivo]
etiqueta = "Motivo de consulta"
tipo_valor = "texto"
# El diagnóstico en texto, tal como lo escribe el hospital: la nota de colposcopia puede traer
# el CIE-10 como «S/C» y el diagnóstico solo aquí (p. ej. «VIRUS DEL PAPILOMA HUMANO»; usuario,
# 2026-10-22). Sin normalizar, como el motivo.
[nota_medica.resultados.diagnostico_texto]
etiqueta = "Diagnóstico (texto)"
tipo_valor = "texto"
[nota_medica.resultados.especialidad]
etiqueta = "Especialidad que la escribe"
tipo_valor = "codigo"
valores = [
{ valor = "MEDICINA_FAMILIAR", etiqueta = "Medicina familiar" },
{ valor = "CIRUGIA_ONCOLOGICA", etiqueta = "Cirugía oncológica" },
{ valor = "CLINICA_MUJER_COLPOSCOPIA", etiqueta = "Clínica de la mujer (colposcopia)" },
]
# Los datos de una orden (procedimiento con clase `orden`; su `estudio_id` es el estudio pedido, de
# `codigos_hospital`). ADR-MD-007.
[orden]
etiqueta = "Orden de estudio"
[orden.resultados.intencion]
etiqueta = "Intención (FHIR intent)"
tipo_valor = "texto"
[orden.resultados.fecha_solicitud]
etiqueta = "Fecha para la que se pidió"
tipo_valor = "fecha"
[orden.resultados.fecha_resultado]
etiqueta = "Fecha del resultado"
tipo_valor = "fecha"
[orden.resultados.estatus]
etiqueta = "Estatus de la orden"
tipo_valor = "texto"
[orden.resultados.diagnostico]
etiqueta = "Diagnóstico con que se pidió"
tipo_valor = "texto"
[orden.resultados.especialidad]
etiqueta = "Especialidad que la pidió"
tipo_valor = "codigo"
valores = [
{ valor = "MEDICINA_FAMILIAR", etiqueta = "Medicina familiar" },
{ valor = "CIRUGIA_ONCOLOGICA", etiqueta = "Cirugía oncológica" },
{ valor = "CLINICA_MUJER_COLPOSCOPIA", etiqueta = "Clínica de la mujer (colposcopia)" },
]
+100
View File
@@ -0,0 +1,100 @@
# Catálogo de CaMa (F1). Valores: los enums de Core (`core/cama/*/enums.py`) y lo que guarda la carga.
# BI-RADS: el hospital reporta 4A, 4B y 4C, normalizados (usuario, 2026-10-16); un 4 sin subcategoría
# también puede llegar (`cama.birads_gravedad` en parametros.toml).
[mastografia]
etiqueta = "Mastografía"
codigos_hospital = ["MASTOGRAFIA"]
[mastografia.resultados.calidad_imagen]
etiqueta = "Calidad de la imagen"
tipo_valor = "codigo"
valores = [
{ valor = "SATISFACTORIO", etiqueta = "Satisfactoria" },
{ valor = "INSATISFACTORIO", etiqueta = "Insatisfactoria" },
]
[mastografia.resultados.birads]
etiqueta = "BI-RADS"
tipo_valor = "codigo"
valores = [
{ valor = "B0", etiqueta = "BI-RADS 0" },
{ valor = "B1", etiqueta = "BI-RADS 1" },
{ valor = "B2", etiqueta = "BI-RADS 2" },
{ valor = "B3", etiqueta = "BI-RADS 3" },
{ valor = "B4", etiqueta = "BI-RADS 4 (sin subcategoría)" },
{ valor = "B4A", etiqueta = "BI-RADS 4A" },
{ valor = "B4B", etiqueta = "BI-RADS 4B" },
{ valor = "B4C", etiqueta = "BI-RADS 4C" },
{ valor = "B5", etiqueta = "BI-RADS 5" },
{ valor = "B6", etiqueta = "BI-RADS 6" },
]
[biopsia]
etiqueta = "Biopsia de mama"
codigos_hospital = ["BIOPSIA_CHICA"]
[biopsia.resultados.grado]
etiqueta = "Grado histológico"
tipo_valor = "codigo"
valores = [
{ valor = "BENIGNO", etiqueta = "Benigno" },
{ valor = "CARCINOMA_IN_SITU", etiqueta = "Carcinoma in situ" },
{ valor = "CARCINOMA_INVASOR", etiqueta = "Carcinoma invasor" },
{ valor = "DESCONOCIDO", etiqueta = "Desconocido" },
]
[biopsia.resultados.fecha_solicitud]
etiqueta = "Fecha de solicitud"
tipo_valor = "fecha"
[nota_medica]
etiqueta = "Nota médica"
[nota_medica.resultados.diagnostico]
etiqueta = "Diagnóstico"
tipo_valor = "externo"
sistema = "CIE-10"
[nota_medica.resultados.especialidad]
etiqueta = "Especialidad que la escribe"
tipo_valor = "codigo"
valores = [
{ valor = "MEDICINA_FAMILIAR", etiqueta = "Medicina familiar" },
{ valor = "CIRUGIA_ONCOLOGICA", etiqueta = "Cirugía oncológica" },
{ valor = "CLINICA_MUJER_COLPOSCOPIA", etiqueta = "Clínica de la mujer (colposcopia)" },
]
# Los datos de una orden (procedimiento con clase `orden`; su `estudio_id` es el estudio pedido, de
# `codigos_hospital`). ADR-MD-007.
[orden]
etiqueta = "Orden de estudio"
[orden.resultados.intencion]
etiqueta = "Intención (FHIR intent)"
tipo_valor = "texto"
[orden.resultados.fecha_solicitud]
etiqueta = "Fecha para la que se pidió"
tipo_valor = "fecha"
[orden.resultados.fecha_resultado]
etiqueta = "Fecha del resultado"
tipo_valor = "fecha"
[orden.resultados.estatus]
etiqueta = "Estatus de la orden"
tipo_valor = "texto"
[orden.resultados.diagnostico]
etiqueta = "Diagnóstico con que se pidió"
tipo_valor = "texto"
[orden.resultados.especialidad]
etiqueta = "Especialidad que la pidió"
tipo_valor = "codigo"
valores = [
{ valor = "MEDICINA_FAMILIAR", etiqueta = "Medicina familiar" },
{ valor = "CIRUGIA_ONCOLOGICA", etiqueta = "Cirugía oncológica" },
{ valor = "CLINICA_MUJER_COLPOSCOPIA", etiqueta = "Clínica de la mujer (colposcopia)" },
]
+267
View File
@@ -0,0 +1,267 @@
# Catálogo de TEA (F1). Valores: los enums de Core (`core/tea/enums.py`) y lo que guarda la carga.
# Los instrumentos aplicados (M-CHAT-R/F, Ramos) son un estudio cada uno: una aplicación por informante y área.
[evaluacion_psicologica]
etiqueta = "Evaluación psicológica"
codigos_hospital = ["EVALUACION_PSICOLOGICA_TEA"]
[evaluacion_psicologica.resultados.instrumento_tamizaje]
etiqueta = "Instrumento de tamizaje"
tipo_valor = "codigo"
valores = [
{ valor = "M_CHAT_R", etiqueta = "M-CHAT-R" },
{ valor = "M_CHAT_RF", etiqueta = "M-CHAT-R/F" },
{ valor = "OTRO", etiqueta = "Otro" },
{ valor = "NO_REGISTRADO", etiqueta = "No registrado" },
]
[evaluacion_psicologica.resultados.edad_meses]
etiqueta = "Edad del niño"
tipo_valor = "numero"
unidad = "meses"
[evaluacion_psicologica.resultados.fecha_evaluacion]
etiqueta = "Fecha de la evaluación"
tipo_valor = "fecha"
[evaluacion_psicologica.resultados.fecha_entrevista_inicial]
etiqueta = "Fecha de la entrevista inicial"
tipo_valor = "fecha"
[ados2]
etiqueta = "ADOS-2"
[ados2.resultados.css]
etiqueta = "Puntaje de severidad (CSS)"
tipo_valor = "numero"
unidad = "puntos"
[mchat]
etiqueta = "M-CHAT-R/F aplicado"
codigos_hospital = ["M_CHAT_R_F"]
[mchat.resultados.informante]
etiqueta = "Informante"
tipo_valor = "codigo"
valores = [
{ valor = "MADRE", etiqueta = "Madre" },
{ valor = "PADRE", etiqueta = "Padre" },
{ valor = "OTRO_CUIDADOR", etiqueta = "Otro cuidador" },
{ valor = "MAESTRO", etiqueta = "Maestro" },
{ valor = "OBSERVACION_CLINICA", etiqueta = "Observación clínica" },
{ valor = "NO_REGISTRADO", etiqueta = "No registrado" },
]
[mchat.resultados.area]
etiqueta = "Área"
tipo_valor = "codigo"
valores = [
{ valor = "TOTAL", etiqueta = "Total" },
]
[mchat.resultados.interpretacion]
etiqueta = "Interpretación"
tipo_valor = "codigo"
valores = [
{ valor = "RIESGO_BAJO", etiqueta = "Riesgo bajo" },
{ valor = "RIESGO_MEDIO", etiqueta = "Riesgo medio" },
{ valor = "RIESGO_ALTO", etiqueta = "Riesgo alto" },
]
[ramos]
etiqueta = "Escala de Ramos aplicada"
codigos_hospital = ["RAMOS"]
[ramos.resultados.informante]
etiqueta = "Informante"
tipo_valor = "codigo"
valores = [
{ valor = "MADRE", etiqueta = "Madre" },
{ valor = "PADRE", etiqueta = "Padre" },
{ valor = "OTRO_CUIDADOR", etiqueta = "Otro cuidador" },
{ valor = "MAESTRO", etiqueta = "Maestro" },
{ valor = "OBSERVACION_CLINICA", etiqueta = "Observación clínica" },
{ valor = "NO_REGISTRADO", etiqueta = "No registrado" },
]
[ramos.resultados.area]
etiqueta = "Área"
tipo_valor = "codigo"
valores = [
{ valor = "ADAPTATIVO", etiqueta = "Adaptativo" },
{ valor = "COGNOSCITIVO", etiqueta = "Cognoscitivo" },
{ valor = "FISICO", etiqueta = "Físico" },
{ valor = "LINGUISTICO", etiqueta = "Lingüístico" },
{ valor = "SOCIOEMOCIONAL", etiqueta = "Socioemocional" },
{ valor = "TOTAL", etiqueta = "Total" },
]
[ramos.resultados.interpretacion]
etiqueta = "Interpretación"
tipo_valor = "codigo"
valores = [
{ valor = "DESARROLLO_ADECUADO", etiqueta = "Desarrollo adecuado" },
{ valor = "MONITOREO", etiqueta = "Monitoreo" },
{ valor = "RETRASO", etiqueta = "Retraso" },
]
[eeg]
etiqueta = "Electroencefalograma"
codigos_hospital = ["ELECTROENCEFALOGRAMA"]
[eeg.resultados.duracion_min]
etiqueta = "Duración"
tipo_valor = "numero"
unidad = "min"
[eeg.resultados.utilizable]
etiqueta = "Utilizable"
tipo_valor = "booleano"
[eeg.resultados.fecha_nacimiento_archivo]
etiqueta = "Fecha de nacimiento en el archivo del equipo"
tipo_valor = "fecha"
# Un segmento es una parte del EEG (procedimiento con clase `parte`).
[eeg.resultados.estado_segmento]
etiqueta = "Estado del segmento"
tipo_valor = "codigo"
valores = [
{ valor = "NO_MARCADO", etiqueta = "No marcado" },
{ valor = "OJOS_CERRADOS", etiqueta = "Ojos cerrados" },
{ valor = "FOTOESTIMULACION", etiqueta = "Fotoestimulación" },
{ valor = "SUENO", etiqueta = "Sueño" },
]
[eeg.resultados.duracion_segmento]
etiqueta = "Duración del segmento"
tipo_valor = "numero"
unidad = "s"
[pea]
etiqueta = "Potenciales evocados auditivos"
codigos_hospital = ["POTENCIALES_EVOCADOS_AUDITIVOS", "POTENCIALES_EVOCADOS"] # el segundo, como llega (responsable de TEA, 2026-10-21)
[pea.resultados.grado_hipoacusia]
etiqueta = "Grado de hipoacusia"
tipo_valor = "codigo"
valores = [
{ valor = "NORMAL", etiqueta = "Normal" },
{ valor = "LEVE", etiqueta = "Leve" },
{ valor = "MODERADA", etiqueta = "Moderada" },
{ valor = "SEVERA", etiqueta = "Severa" },
{ valor = "PROFUNDA", etiqueta = "Profunda" },
{ valor = "NO_CONCLUYENTE", etiqueta = "No concluyente" },
]
[parto]
etiqueta = "Parto"
[parto.resultados.apgar_5min]
etiqueta = "APGAR a los 5 minutos"
tipo_valor = "numero"
unidad = "puntos"
[parto.resultados.ingreso_ucin]
etiqueta = "Ingreso a UCIN"
tipo_valor = "booleano"
[historia_perinatal]
etiqueta = "Antecedentes maternos de la gestación"
[historia_perinatal.resultados.antecedente_aborto]
etiqueta = "Antecedente de aborto"
tipo_valor = "booleano"
[historia_perinatal.resultados.asma]
etiqueta = "Asma"
tipo_valor = "booleano"
[historia_perinatal.resultados.crisis_convulsivas]
etiqueta = "Crisis convulsivas"
tipo_valor = "booleano"
[historia_perinatal.resultados.diabetes_gestacional]
etiqueta = "Diabetes gestacional"
tipo_valor = "booleano"
[historia_perinatal.resultados.embarazo_multiple]
etiqueta = "Embarazo múltiple"
tipo_valor = "booleano"
[historia_perinatal.resultados.enfermedad_autoinmune]
etiqueta = "Enfermedad autoinmune"
tipo_valor = "booleano"
[historia_perinatal.resultados.estres_agudo]
etiqueta = "Estrés agudo"
tipo_valor = "booleano"
[historia_perinatal.resultados.farmaco_riesgo_neurodesarrollo]
etiqueta = "Fármaco de riesgo para el neurodesarrollo"
tipo_valor = "booleano"
[historia_perinatal.resultados.hipertension_preeclampsia]
etiqueta = "Hipertensión o preeclampsia"
tipo_valor = "booleano"
[historia_perinatal.resultados.hipertiroidismo]
etiqueta = "Hipertiroidismo"
tipo_valor = "booleano"
[historia_perinatal.resultados.hipotiroidismo]
etiqueta = "Hipotiroidismo"
tipo_valor = "booleano"
[historia_perinatal.resultados.hipoxia_materna]
etiqueta = "Hipoxia materna"
tipo_valor = "booleano"
[historia_perinatal.resultados.incompatibilidad_rh]
etiqueta = "Incompatibilidad Rh"
tipo_valor = "booleano"
[historia_perinatal.resultados.infeccion_gestacion]
etiqueta = "Infección en la gestación"
tipo_valor = "booleano"
[historia_perinatal.resultados.liquido_amniotico]
etiqueta = "Alteración del líquido amniótico"
tipo_valor = "booleano"
[historia_perinatal.resultados.migrana]
etiqueta = "Migraña"
tipo_valor = "booleano"
[historia_perinatal.resultados.proceso_proinflamatorio]
etiqueta = "Proceso proinflamatorio"
tipo_valor = "booleano"
[historia_perinatal.resultados.tabaquismo_gestacion]
etiqueta = "Tabaquismo en la gestación"
tipo_valor = "booleano"
[historia_perinatal.resultados.trastorno_neurologico]
etiqueta = "Trastorno neurológico"
tipo_valor = "booleano"
[nota_medica]
etiqueta = "Nota médica"
[nota_medica.resultados.diagnostico]
etiqueta = "Diagnóstico"
tipo_valor = "externo"
sistema = "CIE-10"
# Los datos de una orden (procedimiento con clase `orden`; su `estudio_id` es el estudio pedido, de
# `codigos_hospital`). ADR-MD-007.
[orden]
etiqueta = "Orden de estudio"
[orden.resultados.intencion]
etiqueta = "Intención (FHIR intent)"
tipo_valor = "texto"
[orden.resultados.fecha_realizacion]
etiqueta = "Fecha de realización"
tipo_valor = "fecha"
+12
View File
@@ -0,0 +1,12 @@
"""Column types and sizes shared across domains, so the storage schema and
the import validation in WebApi use the same limits."""
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# Hospital patient identifiers are indexed in CaCu/CaMa, and MySQL can't
# index an unbounded TEXT column (error 1170), so they are a bounded VARCHAR.
HOSPITAL_ID_LENGTH = 64
# Stored files (PDF reports, DICOM, EDF). Plain LargeBinary is a 64 KB BLOB
# on MySQL/MariaDB; LONGBLOB holds up to 4 GB.
FileBlob = sa.LargeBinary().with_variant(mysql.LONGBLOB(), "mysql", "mariadb")
-88
View File
@@ -1,88 +0,0 @@
"""A site's codes in platform terms: FHIR ConceptMaps (R4B), as data a site's configuration
holds, never code. A new laboratory that writes "Negativo para lesión" for NILM, or "F" for
female, is one more element in its ConceptMap.
Each group maps the site's codes (`source`, any URI the site uses) onto one system the
platform's fields take their codes from (`target`): a catalog system (core.catalog), FHIR's
administrative gender (identity `sex`), or the platform's yes/no system (boolean fields).
"""
from collections.abc import Iterable
from fhir.resources.R4B.conceptmap import ConceptMap
from core import catalog
GENDER = "http://hl7.org/fhir/administrative-gender"
BOOLEAN = "https://isssteleon.org/fhir/CodeSystem/boolean"
_GENDER_CODES = {"female", "male"}
_BOOLEAN_CODES = {"true", "false"}
def systems(field: str) -> dict[str, set[str] | None]:
"""The systems a field of this name takes codes from, each with its allowed codes
(None: any code of the system)."""
found: dict[str, set[str] | None] = {}
if field == "sex":
found[GENDER] = _GENDER_CODES
for study in catalog.studies().values():
f = study.fields.get(field)
if f is None:
continue
if f.type == "boolean":
found[BOOLEAN] = _BOOLEAN_CODES
elif f.type == "code":
url = catalog.systems()[f.system].url
codes = set(f.codes) or None
known = found.get(url, set())
found[url] = None if codes is None or known is None else known | codes
return found
def problems(cm: ConceptMap) -> list[str]:
"""Why this map can't be used: a group onto a system no field takes, or a target code
its field doesn't allow."""
allowed: dict[str, set[str] | None] = {GENDER: _GENDER_CODES, BOOLEAN: _BOOLEAN_CODES}
for study in catalog.studies().values():
for name in study.fields:
allowed |= systems(name)
found = []
for group in cm.group or []:
if group.target not in allowed:
found.append(f"{group.target}: no platform field takes codes from it")
continue
codes = allowed[group.target]
for element in group.element:
for target in element.target or []:
if codes is not None and target.code not in codes:
found.append(f"{group.target}: {target.code} is not an allowed code")
return found
def table(maps: Iterable[ConceptMap], field: str) -> dict[str, str]:
"""A field's translations, site code (case ignored) -> platform code, from the groups
of these maps that target a system the field takes."""
targets = systems(field)
found = {}
for cm in maps:
for group in cm.group or []:
if group.target not in targets:
continue
for element in group.element:
for target in element.target or []:
if target.equivalence in ("equivalent", "equal", "wider", "subsumes"):
found[element.code.casefold()] = target.code
return found
def translate(maps: Iterable[ConceptMap], source: str, code: str) -> tuple[str, str] | None:
"""A sender's coding (system, code) as (platform system, code), when a map knows it."""
for cm in maps:
for group in cm.group or []:
if group.source != source:
continue
for element in group.element:
if element.code.casefold() == code.casefold():
for target in element.target or []:
return group.target, target.code
return None
-30
View File
@@ -1,30 +0,0 @@
"""The platform's domains. A domain is a package `core.<domain>` holding its parameters
(`__init__`: what dbt reads through `dbt_vars()`), and when it has them, its measures
(`measures.MEASURES`) and its follow-up list (`follow_up`)."""
import importlib
from enum import StrEnum
from types import ModuleType
class Domain(StrEnum):
CACU = "cacu"
CAMA = "cama"
TEA = "tea"
def part(domain: Domain, name: str = "") -> ModuleType | None:
"""The domain's module `name` (its package without one), or None while it has none."""
path = f"core.{domain.value}" + (f".{name}" if name else "")
try:
return importlib.import_module(path)
except ModuleNotFoundError as e:
if e.name is not None and path.startswith(e.name):
return None
raise
def measures(domain: Domain) -> dict:
"""The domain's measures by id (none for a domain without them yet)."""
found = part(domain, "measures")
return found.MEASURES if found else {}
-537
View File
@@ -1,537 +0,0 @@
"""Platform rows as FHIR R4B resources (pure, no IO), and the conformance resources that
declare what ours are: the local code systems, our extensions and our search parameters.
Every mapper builds a `fhir.resources.R4B` model, so a resource that breaks FHIR's structure
fails here, before it is served. Clinical resources other than Patient are found by search
only; their ids are stable (a UUID of their natural key), not addresses.
"""
import uuid
from collections.abc import Iterable
from datetime import UTC, date, datetime
from fhir.resources.R4B.codesystem import CodeSystem
from fhir.resources.R4B.condition import Condition
from fhir.resources.R4B.diagnosticreport import DiagnosticReport
from fhir.resources.R4B.encounter import Encounter
from fhir.resources.R4B.measure import Measure
from fhir.resources.R4B.observation import Observation
from fhir.resources.R4B.patient import Patient
from fhir.resources.R4B.procedure import Procedure
from fhir.resources.R4B.resource import Resource
from fhir.resources.R4B.riskassessment import RiskAssessment
from fhir.resources.R4B.searchparameter import SearchParameter
from fhir.resources.R4B.structuredefinition import StructureDefinition
from core import catalog, models
FHIR_VERSION = "4.3.0"
BASE = "https://isssteleon.org/fhir"
EXTENSION = f"{BASE}/StructureDefinition/"
CODES = f"{BASE}/CodeSystem/"
ICD10 = "http://hl7.org/fhir/sid/icd-10"
UCUM = "http://unitsofmeasure.org"
_IDS = uuid.uuid5(uuid.NAMESPACE_URL, BASE)
# Local code systems: code -> display (Spanish, as the screens show them).
CODE_SYSTEMS: dict[str, tuple[str, dict[str, str]]] = {
"cacu-procedure": ("Procedimientos de CaCu", {
"colposcopy": "Colposcopia", "treatment": "Tratamiento",
}),
"cacu-follow-up-status": ("Estatus de seguimiento", {
"case": "Caso (cáncer)", "pre_colposcopy": "Pre colposcopia",
"post_colposcopy": "Post colposcopia", "post_treatment": "Post tratamiento",
}),
"cama-follow-up-status": ("Estatus de seguimiento", {
"cancer": "Diagnóstico confirmado", "pending_biopsy": "Pendiente de biopsia",
"biopsy_no_result": "Biopsia sin resultado", "benign_biopsy": "Biopsia benigna",
}),
"tea-follow-up-status": ("Estatus de seguimiento", {
"mchat_only": "Solo M-CHAT", "psychology": "Hasta evaluación psicológica",
"neuropediatrics": "Hasta evaluación neuropediátrica", "eeg": "Con EEG",
}),
"tea-case": ("Estado del caso", {
"confirmed": "Diagnóstico confirmado", "in_process": "En proceso",
"not_confirmed": "Sin TEA",
}),
"tea-eeg-status": ("Estatus de EEG", {
"normal": "Normal", "abnormal": "Anormal", "no_valid_eeg": "Sin EEG válido",
}),
# an EEG metric outside its age band: `<metric>:above` or `<metric>:below`
"tea-eeg-alteration": ("Alteración del EEG", {}),
"follow-up-priority": ("Prioridad de seguimiento", {
"high": "Alta", "medium": "Media", "low": "Baja",
}),
"measure-stratifier": ("Estratos de indicadores", {
"category": "Categoría", "age_group": "Grupo de edad",
"follow_up_status": "Estatus de seguimiento", "result": "Citología de alto grado",
"diagnosis_code": "Diagnóstico CIE-10",
"birads": "BI-RADS de la mastografía",
"referral_cytology": "Citología previa", "histology_level": "Histología",
"screening_round": "Tamizaje inicial o subsecuente",
"result_initial": "Resultado en tamizaje inicial",
"result_subsequent": "Resultado en tamizaje subsecuente",
"referral_hpv": "VPH de la citología previa", "hpv_16": "VPH 16", "hpv_18": "VPH 18",
"hpv_initial": "VPH en tamizaje inicial",
"hpv_subsequent": "VPH en tamizaje subsecuente",
}),
"risk-model": ("Modelos de riesgo", {}), # open: a model's name is its code
} # fmt: skip
def _catalog_systems() -> dict[str, tuple[str, dict[str, str]]]:
"""The catalog's own code systems, with every code some field allows."""
found: dict[str, tuple[str, dict[str, str]]] = {}
for name, system in catalog.systems().items():
if not system.external:
codes = {c: d for s in catalog.studies().values() for f in s.fields.values()
if f.system == name for c, d in f.codes.items()} # fmt: skip
found[name] = (system.title, codes)
return found
CODE_SYSTEMS |= _catalog_systems()
CODE_SYSTEMS["cama-procedure"] = ("Procedimientos de CaMa", CODE_SYSTEMS["breast-treatment"][1])
# What the catalog names: its studies, and every field as `<study>.<field>`.
CODE_SYSTEMS["study"] = ("Estudios", {n: s.title for n, s in catalog.studies().items()})
CODE_SYSTEMS["catalog-field"] = ("Campos de los estudios", {
f"{n}.{f}": d.title for n, s in catalog.studies().items() for f, d in s.fields.items()
}) # fmt: skip
GROUP_SCORE = "MeasureReport.group.measureScore"
STRATUM_SCORE = "MeasureReport.group.stratifier.stratum.measureScore" # a stratum's own score
# Our extensions: name -> (value type, the elements they extend).
EXTENSIONS: dict[str, tuple[str, list[str]]] = {
"ic-bajo": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
"ic-alto": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
"q1": ("decimal", [GROUP_SCORE, STRATUM_SCORE]),
"q3": ("decimal", [GROUP_SCORE, STRATUM_SCORE]),
"corte-conocimiento": ("dateTime", ["MeasureReport"]),
"period-type": ("code", ["Measure"]),
"follow-up-status": ("Coding", ["Patient"]),
"follow-up-priority": ("Coding", ["Patient"]),
"report-date": ("date", ["DiagnosticReport"]),
"days-to-diagnosis": ("integer", ["DiagnosticReport"]),
# The state ("inferred", "structured", "pending", "ambiguous") and day of a stage of the
# route that follows a cytology (core.cacu.stages).
"stage-colposcopy-state": ("code", ["DiagnosticReport"]),
"stage-colposcopy-date": ("date", ["DiagnosticReport"]),
"stage-biopsy-state": ("code", ["DiagnosticReport"]),
"stage-biopsy-date": ("date", ["DiagnosticReport"]),
"stage-diagnosis-state": ("code", ["DiagnosticReport"]),
"stage-diagnosis-date": ("date", ["DiagnosticReport"]),
# a clinical scenario of the model's report the person falls in (its curves)
"escenario-clinico": ("string", ["RiskAssessment"]),
# a child on TEA's list: her age group, case, EEG and scores
"tea-age-group": ("string", ["Patient"]),
"tea-case": ("Coding", ["Patient"]),
"tea-eeg-status": ("Coding", ["Patient"]),
"tea-eeg-alteration": ("Coding", ["Patient"]),
"tea-last-eeg": ("date", ["Patient"]),
"mchat-score": ("integer", ["Patient"]),
"ados2-css": ("integer", ["Patient"]),
} # fmt: skip
def _name(code: str) -> str:
"""A conformance resource's computable name (CamelCase)."""
return "".join(part.capitalize() for part in code.replace("_", "-").split("-"))
def _id(*key) -> str:
return str(uuid.uuid5(_IDS, "|".join(str(k) for k in key)))
def _day(value) -> str | None:
if value is None:
return None
return value.isoformat()[:10] if isinstance(value, date) else str(value)[:10]
def _instant(value) -> str | None:
"""A stored moment as an instant; one stored without an offset is UTC."""
if value is None:
return None
found = value if isinstance(value, datetime) else datetime.fromisoformat(str(value))
return (found if found.tzinfo else found.replace(tzinfo=UTC)).isoformat()
def coding(system: str, code: str) -> dict:
display = CODE_SYSTEMS[system][1].get(code) if system in CODE_SYSTEMS else None
return {"system": CODES + system, "code": code, **({"display": display} if display else {})}
def concept(system: str, code: str) -> dict:
found = coding(system, code)
return {"coding": [found], "text": found.get("display", code)}
def ext(name: str, value_type: str, value) -> dict:
return {"url": EXTENSION + name, f"value{value_type[0].upper()}{value_type[1:]}": value}
def subject(person_id: str) -> dict:
return {"reference": f"Patient/{person_id}"}
# --- clinical resources ----------------------------------------------------------------
def patient(row: dict, status_system: str | None = None) -> Patient:
"""A person: what her records agree on, her names and identifiers, the ids she
replaced; on a follow-up list, her status there (`status_system`) and priority."""
found: dict = {"resourceType": "Patient", "id": row["person_id"]}
if row.get("sex"):
found["gender"] = row["sex"]
if row.get("birth_date"):
found["birthDate"] = _day(row["birth_date"])
if row.get("death_date"):
found["deceasedDateTime"] = _day(row["death_date"])
if row.get("status") and status_system:
found["extension"] = [ext("follow-up-status", "Coding",
coding(status_system, row["status"]))] # fmt: skip
if row.get("priority"):
priority = coding("follow-up-priority", row["priority"])
found["extension"].append(ext("follow-up-priority", "Coding", priority))
found.setdefault("extension", []).extend(_tea_listed(row))
if not found["extension"]:
del found["extension"]
if row.get("names"):
found["name"] = [{"text": n} for n in row["names"]]
if row.get("identifiers"):
found["identifier"] = [{"system": s, "value": v} for s, v in row["identifiers"]]
if row.get("replaces"):
found["link"] = [{"other": {"reference": f"Patient/{old}"}, "type": "replaces"}
for old in row["replaces"]] # fmt: skip
return Patient.model_validate(found)
def _tea_listed(row: dict) -> list[dict]:
"""What TEA's list shows of a child, when she is on it (core.tea.follow_up)."""
found = []
if row.get("age_group"):
found.append(ext("tea-age-group", "string", row["age_group"]))
for key, system in (("case", "tea-case"), ("eeg_status", "tea-eeg-status")):
if row.get(key):
found.append(ext(system, "Coding", coding(system, row[key])))
for altered in row.get("alterations") or []:
found.append(ext("tea-eeg-alteration", "Coding", coding("tea-eeg-alteration", altered)))
if row.get("last_eeg"):
found.append(ext("tea-last-eeg", "date", _day(row["last_eeg"])))
for key, name in (("mchat_score", "mchat-score"), ("ados2_css", "ados2-css")):
if row.get(key) is not None:
found.append(ext(name, "integer", int(row[key])))
return found
def replaced_patient(person_id: str, replaced_by: str) -> Patient:
"""A person a review merged into another: no longer active, pointing at who replaced
her, so her id keeps resolving."""
return Patient.model_validate({
"resourceType": "Patient", "id": person_id, "active": False,
"link": [{"other": {"reference": f"Patient/{replaced_by}"}, "type": "replaced-by"}],
}) # fmt: skip
def _value(f: catalog.FieldDef, value) -> dict:
"""A field's value as the Observation value of its type."""
if f.type == "code":
system = catalog.systems()[f.system]
if system.external:
return {"valueCodeableConcept": {"coding": [{"system": system.url, "code": value}],
"text": value}} # fmt: skip
return {"valueCodeableConcept": concept(f.system, value)}
if f.type == "boolean":
return {"valueBoolean": bool(value)}
if f.type == "number":
return {"valueQuantity": {"value": value, **({"unit": f.unit} if f.unit else {})}}
if f.type == "date":
return {"valueDateTime": _day(value)}
return {"valueString": str(value)}
def known(study: str, row: dict, cutoff) -> dict:
"""A study instance as the platform knew it by the end of `cutoff`: the fields of an
event that has no date yet, or a later one, are not known."""
spec = catalog.studies()[study]
out = dict(row)
for cls, event in spec.events.items():
day = _day(row.get(event.date))
if event.parent is not None and (day is None or day > _day(cutoff)):
for name, f in spec.fields.items():
if f.event == cls:
out[name] = None
return out
def instance(study: str, row: dict, report_extensions: Iterable[dict] = ()) -> list[Resource]:
"""One study instance (a row of `silver.<study>`) as FHIR, from the catalog: an
Observation per field that is not an event's date, and, when the study has a report,
the DiagnosticReport that gathers them."""
spec = catalog.studies()[study]
person = row["person_id"]
key = [_day(row[k]) if spec.fields[k].type == "date" else row[k] for k in spec.key]
dates = {e.date for e in spec.events.values()}
root = next(e for e in spec.events.values() if e.parent is None)
effective = _day(row.get(root.date))
container = _id(study, person, *key) # its report, or the encounter its notes are of
visit = "report" not in spec.events
observations = []
for name, f in spec.fields.items():
if name in dates or row.get(name) is None or f.type == "file":
continue
observations.append(Observation.model_validate({
"resourceType": "Observation",
"id": _id(study, name, person, *key),
"status": "final",
"code": concept("catalog-field", f"{study}.{name}"),
"subject": subject(person),
**({"encounter": {"reference": f"Encounter/{container}"}} if visit else {}),
**({"effectiveDateTime": effective} if effective else {}),
**_value(f, row[name]),
})) # fmt: skip
if visit: # a study without a report (a consultation): the encounter its values are of
if not observations:
return []
encounter = Encounter.model_validate({
"resourceType": "Encounter", "id": container, "status": "finished",
"class": {"system": "http://terminology.hl7.org/CodeSystem/v3-ActCode",
"code": "AMB"},
"type": [concept("study", study)],
"subject": subject(person),
**({"period": {"start": effective}} if effective else {}),
}) # fmt: skip
return [encounter, *observations]
reported = _day(row.get(spec.events["report"].date))
extensions = ([ext("report-date", "date", reported)] if reported else []) + list(
report_extensions
)
report = DiagnosticReport.model_validate({
"resourceType": "DiagnosticReport",
"id": container,
"status": "final" if reported else "registered",
"code": concept("study", study),
"subject": subject(person),
**({"effectiveDateTime": effective} if effective else {}),
**({"extension": extensions} if extensions else {}),
"result": [{"reference": f"Observation/{o.id}"} for o in observations] or None,
}) # fmt: skip
return [report, *observations]
def condition(row: dict) -> Condition:
"""What a clinical note diagnosed (`silver.clinical_note`), by ICD-10 or as written; or
a study of the catalog that is a diagnosis (`study`: a breast recurrence), by its name
and its coded field (`code`: where it recurred)."""
person, day = row["person_id"], _day(row["note_date"])
code: dict = {"text": row.get("diagnosis_text") or row.get("icd10")}
if row.get("icd10"):
code["coding"] = [{"system": ICD10, "code": row["icd10"]}]
if study := row.get("study"):
code = concept("study", study)
system = next((f.system for f in catalog.studies()[study].fields.values()
if f.type == "code"), None) # fmt: skip
if system and row.get("code"):
where = coding(system, row["code"])
code["coding"].append(where)
code["text"] += f" ({where.get('display', row['code']).lower()})"
found: dict = {
"resourceType": "Condition",
"id": _id("condition", person, day, row.get("specialty") or study),
"category": [{"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/condition-category",
"code": "encounter-diagnosis"}]}],
"code": code,
"subject": subject(person),
"recordedDate": day,
} # fmt: skip
if row.get("reason"):
found["note"] = [{"text": row["reason"]}]
return Condition.model_validate(found)
def procedure(row: dict, domain: str = "cacu") -> Procedure:
"""A procedure the timeline inferred (`gold.<domain>_events`; CaCu: colposcopy,
treatment; CaMa: each treatment by its kind), coded in `<domain>-procedure`."""
person, day = row["person_id"], _day(row["date"])
return Procedure.model_validate({
"resourceType": "Procedure",
"id": _id("procedure", row["type"], person, day),
"status": "completed",
"code": concept(f"{domain}-procedure", row["type"]),
"subject": subject(person),
"performedDateTime": day,
}) # fmt: skip
SCENARIO_SEPARATOR = " | " # as models.survival joins them
def risk_assessment(row: dict, horizons: Iterable[dict]) -> RiskAssessment:
"""A model's risk for one person at her index date (`gold.cacu_risk`): one prediction
per horizon, in years, with its 95% interval; and the clinical scenarios of the model's
report she falls in (an extension each), for her record to draw their curves."""
predictions = []
for h in sorted(horizons, key=lambda h: h["horizon_years"]):
bounds = (("ic-bajo", "ci_low"), ("ic-alto", "ci_high"))
interval = [ext(name, "decimal", h[key]) for name, key in bounds
if h.get(key) is not None] # fmt: skip
predictions.append({
"probabilityDecimal": h["probability"],
"whenRange": {"high": {"value": h["horizon_years"], "unit": "a", "system": UCUM,
"code": "a"}},
**({"extension": interval} if interval else {}),
}) # fmt: skip
model = row["model"]
return RiskAssessment.model_validate({
"resourceType": "RiskAssessment",
"id": _id("risk", model, row["version"], row["person_id"], _day(row["index_date"])),
"meta": {"lastUpdated": _instant(row["scored_at"])},
"status": "final",
"method": {"coding": [{"system": CODES + "risk-model", "code": model,
"display": models.title(model)}],
"text": f"{models.title(model)} v{row['version']}"},
"subject": subject(row["person_id"]),
"occurrenceDateTime": _day(row["index_date"]),
"prediction": predictions,
**({"extension": [ext("escenario-clinico", "string", name) for name in scenarios]}
if (scenarios := [n for n in (row.get("scenarios") or "").split(SCENARIO_SEPARATOR)
if n]) else {}),
}) # fmt: skip
SCORING = {"proportion": "proportion", "continuous-variable": "continuous-variable",
"composition": "cohort"} # fmt: skip
def measure_id(code: str) -> str:
"""A measure's FHIR id (ids allow no underscore)."""
return code.lower().replace("_", "-")
def measure_url(code: str) -> str:
return f"{BASE}/Measure/{code}"
# The populations each kind of measure counts (core.measures emits exactly these).
POPULATIONS = {"proportion": ["initial-population", "denominator", "numerator"],
"continuous-variable": ["initial-population", "measure-observation"],
"composition": ["initial-population", "measure-observation"]} # fmt: skip
POPULATION = "http://terminology.hl7.org/CodeSystem/measure-population"
def stratifiers(m) -> list[str]:
"""A measure's strata: a composition's categories first, then its declared strata."""
first = ["category"] if m.rule.kind == "composition" else []
return first + [name for name, _ in getattr(m.rule, "strata", ())]
def stratifier_code(name: str) -> dict:
return concept("measure-stratifier", name)
def measure(m, domain: str) -> Measure:
"""A measure definition (`core.measures.Measure`): how it is computed is Core's code,
which `criteria` points to."""
criteria = {"language": "text/x-python",
"expression": f"core.{domain}.measures.MEASURES['{m.id}']"} # fmt: skip
group: dict = {
"id": m.group,
"population": [{"code": {"coding": [{"system": POPULATION, "code": c}]},
"criteria": criteria} for c in POPULATIONS[m.rule.kind]],
} # fmt: skip
if strata := stratifiers(m):
group["stratifier"] = [{"id": s, "code": stratifier_code(s), "criteria": criteria}
for s in strata] # fmt: skip
found: dict = {
"resourceType": "Measure",
"id": measure_id(m.id),
"url": measure_url(m.id),
"version": m.version,
"name": m.id,
"title": m.title,
"status": "active",
"scoring": {"coding": [{"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": SCORING[m.rule.kind]}]},
"extension": [ext("period-type", "code", p) for p in m.periods],
"group": [group],
} # fmt: skip
if m.improvement:
found["improvementNotation"] = {"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": m.improvement}]} # fmt: skip
if m.description:
found["description"] = m.description
return Measure.model_validate(found)
# --- conformance: what our resources declare ---------------------------------------------
def code_systems() -> list[CodeSystem]:
return [CodeSystem.model_validate({
"resourceType": "CodeSystem", "id": name, "url": CODES + name,
"name": _name(name),
"title": title, "status": "active", "caseSensitive": True,
"content": "complete" if concepts else "not-present",
"concept": [{"code": c, "display": d} for c, d in concepts.items()],
}) for name, (title, concepts) in CODE_SYSTEMS.items()] # fmt: skip
def extensions() -> list[StructureDefinition]:
found = []
for name, (value_type, contexts) in EXTENSIONS.items():
url = EXTENSION + name
found.append(StructureDefinition.model_validate({
"resourceType": "StructureDefinition", "id": name, "url": url,
"name": _name(name), "status": "active", "fhirVersion": FHIR_VERSION,
"kind": "complex-type", "abstract": False, "type": "Extension",
"context": [{"type": "element", "expression": c} for c in contexts],
"baseDefinition": "http://hl7.org/fhir/StructureDefinition/Extension",
"derivation": "constraint",
"differential": {"element": [
{"id": "Extension", "path": "Extension", "max": "*" if name == "period-type"
else "1"},
{"id": "Extension.extension", "path": "Extension.extension", "max": "0"},
{"id": "Extension.url", "path": "Extension.url", "fixedUri": url},
{"id": "Extension.value[x]", "path": "Extension.value[x]", "min": 1,
"type": [{"code": value_type}]},
]},
})) # fmt: skip
return found
# Our search parameters: code -> (resource, type, description).
SEARCH_PARAMETERS: dict[str, tuple[str, str, str]] = {
"stage-cutoff": ("DiagnosticReport", "date", "The day the route stages are known by"),
"follow-up-age-min": ("Patient", "number", "Minimum completed age at the cut-off (CaCu)"),
"follow-up-age-max": ("Patient", "number", "Maximum completed age at the cut-off (CaCu)"),
"follow-up-status": ("Patient", "token", "Follow-up status at the cut-off"),
"follow-up-cutoff": ("Patient", "date", "The day the follow-up list is taken at"),
"follow-up-window": ("Patient", "number",
"Months before the cut-off a cytology puts a patient on the list"),
"recent": ("Patient", "date", "Her latest cytology in the window (sort only)"),
"risk-cin2": ("Patient", "number", "Her current CIN2+ risk (sort only)"),
"risk-cancer": ("Patient", "number", "Her current cancer risk (sort only)"),
"risk-horizon": ("Patient", "number", "The horizon, in years, risks are sorted at"),
"reporting-period": ("MeasureReport", "token",
"A semester (2025-S1) or a month (2025-03) the report covers"),
"as-of": ("MeasureReport", "date", "Count only what the platform knew by then"),
"event-cutoff": ("MeasureReport", "date", "Durations count to this day"),
} # fmt: skip
def search_parameters() -> list[SearchParameter]:
return [SearchParameter.model_validate({
"resourceType": "SearchParameter", "id": code,
"url": f"{BASE}/SearchParameter/{code}", "name": _name(code),
"status": "active", "description": description, "code": code, "base": [base],
"type": kind,
}) for code, (base, kind, description) in SEARCH_PARAMETERS.items()] # fmt: skip
def conformance() -> list[Resource]:
"""Everything our resources declare: what the validator loads, and what the
CapabilityStatement points to."""
return [*code_systems(), *extensions(), *search_parameters()]
-157
View File
@@ -1,157 +0,0 @@
"""FHIR in: what a standard hospital sends (R4 Bundles), as the rows a pipeline's link and
target nodes take, the same rows a site's map and extract nodes give. One silver,
two doors.
A record is one resource the hospital sent: a Patient, and each DiagnosticReport or
Encounter (one study instance). Every report also gives an identity row, its subject's, so
the link node joins it to its person the way it joins any document: by identifiers, name and
birth date. Codes in the platform's own systems pass as they are; any other code goes through
the sender's ConceptMaps (core.concept_map), and one no map knows is kept as sent, so the
target holds the row saying why.
"""
import hashlib
from collections.abc import Iterable
from typing import Any
from fhir.resources.R4B.conceptmap import ConceptMap
from core import catalog, concept_map
from core.fhir import CODES
from core.pipeline import RECORD
from core.schema import IDENTIFIER_SYSTEMS
STUDY = CODES + "study"
FIELD = CODES + "catalog-field"
def record(sender: str, reference: str) -> str:
"""A sent resource's record id: stable across resends of the same resource."""
return hashlib.sha256(f"{sender}|{reference}".encode()).hexdigest()
def resources(bundle: dict) -> dict[str, dict]:
"""The Bundle's resources by `Type/id`: what its references name, whether they use that
form or the entry's `fullUrl` (`urn:uuid:...`, as transaction Bundles do)."""
return {f"{r['resourceType']}/{r['id']}": r for r in _entries(bundle).values()}
def _entries(bundle: dict) -> dict[str, dict]:
"""Every resource under each name a reference may use: `Type/id` and its fullUrl."""
found = {}
for entry in bundle.get("entry", []):
r = entry.get("resource") or {}
if r.get("resourceType") and r.get("id"):
found[f"{r['resourceType']}/{r['id']}"] = r
if entry.get("fullUrl"):
found[entry["fullUrl"]] = r
return found
def _translated(maps: Iterable[ConceptMap], coding: dict, system: str) -> str | None:
"""A coding as a code of `system`: as it is when already there, else through the maps."""
if coding.get("system") == system:
return coding.get("code")
found = concept_map.translate(maps, coding.get("system", ""), coding.get("code", ""))
return found[1] if found and found[0] == system else None
def _codings(concept: dict | None) -> list[dict]:
return (concept or {}).get("coding", [])
def identity(patient: dict) -> dict[str, Any]:
"""What a Patient says about whom she is: identifiers by system, name, birth date, sex."""
found: dict[str, Any] = {}
by_system = {v: k for k, v in IDENTIFIER_SYSTEMS.items()}
for i in patient.get("identifier", []):
field = by_system.get(i.get("system"), "record_number")
found.setdefault(field, i.get("value"))
if names := patient.get("name"):
name = names[0]
found["full_name"] = name.get("text") or " ".join(
[*name.get("given", []), *([name["family"]] if name.get("family") else [])]
)
if patient.get("birthDate"):
found["birth_date"] = patient["birthDate"]
if patient.get("gender") in ("female", "male"):
found["sex"] = patient["gender"]
return found
def _value(observation: dict, f: catalog.FieldDef, maps) -> Any:
if "valueCodeableConcept" in observation:
codings = _codings(observation["valueCodeableConcept"])
url = catalog.systems()[f.system].url if f.system else None
for coding in codings:
if url and (code := _translated(maps, coding, url)) is not None:
return code
return codings[0].get("code") if codings else None # kept as sent: held, saying why
for key in ("valueBoolean", "valueString", "valueInteger"):
if key in observation:
return observation[key]
if "valueQuantity" in observation:
return observation["valueQuantity"].get("value")
if "valueDateTime" in observation:
return observation["valueDateTime"][:10]
return None
def rows(bundle: dict, entity: str, sender: str, maps: Iterable[ConceptMap] = ()) -> list[dict]:
"""The Bundle's rows of one entity: `identity` (each Patient, and each report's
subject), `death` (Patients who died), or a study of the catalog (each report or
encounter of it, with its results as fields)."""
maps = list(maps)
sent = resources(bundle)
named = _entries(bundle) # what a reference may name
def subject(r: dict) -> dict | None:
return named.get((r.get("subject") or {}).get("reference", ""))
if entity == "identity":
out = [{**identity(r), RECORD: record(sender, ref)}
for ref, r in sent.items() if r["resourceType"] == "Patient"] # fmt: skip
for ref, r in sent.items():
if r["resourceType"] in ("DiagnosticReport", "Encounter") and (p := subject(r)):
out.append({**identity(p), RECORD: record(sender, ref)})
return out
if entity == "death":
return [{"death_date": r["deceasedDateTime"][:10], RECORD: record(sender, ref)}
for ref, r in sent.items()
if r["resourceType"] == "Patient" and r.get("deceasedDateTime")] # fmt: skip
spec = catalog.studies()[entity]
kind = "DiagnosticReport" if "report" in spec.events else "Encounter"
root = next(e for e in spec.events.values() if e.parent is None)
out = []
for ref, r in sent.items():
if r["resourceType"] != kind:
continue
code = r.get("code") if kind == "DiagnosticReport" else (r.get("type") or [None])[0]
if not any(_translated(maps, c, STUDY) == entity for c in _codings(code)):
continue
row: dict[str, Any] = {RECORD: record(sender, ref)}
start = r.get("effectiveDateTime") if kind == "DiagnosticReport" else (
(r.get("period") or {}).get("start")) # fmt: skip
if start:
row[root.date] = start[:10]
if kind == "DiagnosticReport":
reported = next((x.get("valueDate") for x in r.get("extension", [])
if x.get("url", "").endswith("/report-date")), None) # fmt: skip
reported = reported or (r.get("issued") or "")[:10] or None
if reported:
row[spec.events["report"].date] = reported
results = [named.get(x.get("reference", "")) for x in r.get("result", [])]
else:
mine = {ref, *(k for k, v in named.items() if v is r)}
results = [o for o in sent.values() if o["resourceType"] == "Observation"
and (o.get("encounter") or {}).get("reference") in mine] # fmt: skip
for o in filter(None, results):
for coding in _codings(o.get("code")):
name = _translated(maps, coding, FIELD) or ""
study, _, field = name.partition(".")
if study == entity and field in spec.fields:
row[field] = _value(o, spec.fields[field], maps)
break
out.append(row)
return out
-26
View File
@@ -1,26 +0,0 @@
"""What every domain's follow-up list shares (pure). A domain with a list has a module
`core.<domain>.follow_up` with:
- `WINDOWS`: the windows (months) the list can be asked for; `SORTS` and `DEFAULT_HORIZON`
(years, for orders by risk; None without one);
- `STATUS_SYSTEM`: the code system of a patient's status on the list;
- `listed(rows, start, cutoff)`: who is on the list in reading order (most recent first),
each with her `status` (and `priority`, when the domain ranks them), from the rows of its
`follow_up` read (persistance.fhir);
- `status(row, cutoff)`: a person's status at the cut-off from her person row, or None;
- `ordered(rows, sort, risks, horizon)`: the list in another sort;
- `PROCEDURES`: the timeline's inferred procedures served as FHIR Procedures;
- `REPORT_FACTS`: facts gold adds to a study's report, by study.
"""
import calendar
from datetime import date
def window_start(cutoff: date, months: int) -> date:
"""The first day of the window: `months` before the cut-off (the month's last day when
shorter), plus one day."""
total = cutoff.year * 12 + cutoff.month - 1 - months
year, month = divmod(total, 12)
day = min(cutoff.day, calendar.monthrange(year, month + 1)[1])
return date.fromordinal(date(year, month + 1, day).toordinal() + 1)
View File
+16
View File
@@ -0,0 +1,16 @@
import sqlalchemy.orm as orm
from sqlmodel import SQLModel
registry = orm.registry()
class GovernanceModel(SQLModel, registry=registry):
"""Base class for the governance domain: the OCR extraction log and stored
predictions (VAR, EL and MLD requirements). Model versions and artifacts
live in MLflow; cohorts for models are the indicator kit's builds
(`cohorte_armado`) in each domain's database.
Governance is its own database. Rows refer to CaCu/CaMa/TEA patients and
episodes by natural key (`pac_id_hospital`, `episodio_id`) because foreign
keys can't cross databases.
"""
+29
View File
@@ -0,0 +1,29 @@
from enum import Enum
class Environment(str, Enum):
"""ML-02: development versions are tagged separately from production."""
DEV = "DEV"
PROD = "PROD"
class ArtifactKind(str, Enum):
"""ML-01a: kinds of artifacts saved from the routines around training,
in addition to the final model."""
MUESTREO = "MUESTREO"
DATOS_FALTANTES = "DATOS_FALTANTES"
METODO_ANALITICO = "METODO_ANALITICO"
BALANCE_CLASES = "BALANCE_CLASES"
CONFIANZA_SALIDA = "CONFIANZA_SALIDA"
ONNX_CHECKPOINT = "ONNX_CHECKPOINT"
OTRO = "OTRO"
class EstatusExtraccion(str, Enum):
"""VAR-07/VAR-09: status of an extraction run."""
EN_PROGRESO = "EN_PROGRESO"
COMPLETADA = "COMPLETADA"
FALLIDA = "FALLIDA"
@@ -0,0 +1,70 @@
from datetime import datetime, timezone
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.governance.base import GovernanceModel
class ExtractionRun(GovernanceModel, table=True):
"""VAR-07/VAR-08/VAR-09: log of each extraction run (OCR or other).
Records the data source and date range (VAR-08), the transformation and
quality check applied (VAR-07), and serves as an idempotency log (VAR-09):
callers check for a `COMPLETADA` run on the same `(domain, entity,
entity_pk)` before extracting again. The extracted value itself lives in
the source row's `*_ocr_*` columns.
"""
extraction_run_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
domain: str = Field(
sa_column=sa.Column(sa.String(16), nullable=False, index=True),
description="cacu | cama | tea",
)
entity: str = Field(
sa_column=sa.Column(sa.String(64), nullable=False, index=True),
description="nombre de la tabla/entidad de Core sobre la que corrió la extracción",
)
entity_pk: str = Field(
sa_column=sa.Column(sa.String(64), nullable=False, index=True),
description="valor de la llave primaria de la fila extraída, como texto",
)
column_extracted: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="columna destino que esta corrida pobló (p.ej. cit_vph_resultado)",
)
source_description: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="VAR-08: fuente de los datos crudos",
)
source_started_at: Optional[datetime] = Field(
default=None,
sa_column=sa.Column(sa.DateTime),
description="VAR-08: inicio del periodo que cubren los datos crudos cargados",
)
source_ended_at: Optional[datetime] = Field(
default=None,
sa_column=sa.Column(sa.DateTime),
)
transform_description: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="VAR-07: descripción de la transformación de datos crudos aplicada",
)
quality_validation: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="VAR-07: resultado de la validación de calidad de los datos, texto libre o JSON serializado",
)
estatus: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="valor de core.governance.enums.EstatusExtraccion guardado como texto",
)
executed_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_column=sa.Column(sa.DateTime, nullable=False),
)
@@ -0,0 +1,83 @@
from datetime import datetime, timezone
from typing import Optional
import sqlalchemy as sa
from core.columns import HOSPITAL_ID_LENGTH
from sqlmodel import Field
from core.governance.base import GovernanceModel
class ModelPrediction(GovernanceModel, table=True):
"""MLD-4/MLD-5: a persisted prediction, linked to the MLflow model
version that produced it.
Model training, versioning and promotion live in MLflow, not here
(`models.io.registry`); this row only carries the keys to find that version
again (`mlflow_run_id`, `modelo_nombre`, `modelo_version`), the same
reference-only pattern `core.indicadores.cohortes.EvaluacionRiesgoLoteBase`
already uses for its own risk evaluations.
`interpretability` stores the MLD-03 fields (OR, HR, cumulative
probability) with the estimate. `applicability_passed` is False when the
input failed the EL-04b applicability check; the prediction is kept for
traceability but should not be used clinically.
"""
model_prediction_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
mlflow_run_id: str = Field(
sa_column=sa.Column(sa.String(64), nullable=False, index=True),
description="la corrida de MLflow que entrenó el modelo",
)
modelo_nombre: str = Field(
sa_column=sa.Column(sa.String(128), nullable=False, index=True),
description="nombre del modelo registrado en MLflow",
)
modelo_version: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="versión del modelo registrado en MLflow",
)
domain: str = Field(
sa_column=sa.Column(sa.String(16), nullable=False, index=True),
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
)
episodio_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
input_hash: str = Field(
sa_column=sa.Column(sa.String(128), nullable=False, index=True),
description="sha256 del vector de entrada, para detectar predicciones duplicadas",
)
output: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="JSON serializado: salida cruda del modelo",
)
prediccion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="etiqueta/puntaje principal, en texto, para filtrar sin deserializar `output`",
)
confianza: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
description="0..1, nivel de confianza casuístico de esta estimación (MLD-01)",
)
interpretability: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description='JSON serializado (MLD-03): {"odds_ratio":, "hazard_ratio":, "probabilidad_acumulada":}',
)
applicability_passed: bool = Field(
sa_column=sa.Column(sa.Boolean, nullable=False),
description="EL-04b: resultado de evaluar los criterios de aplicabilidad de producción contra esta fila",
)
created_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_column=sa.Column(sa.DateTime, nullable=False),
)

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