Compare commits

..

38 Commits

Author SHA1 Message Date
edgar c0979dd0ed chore(webapp): actualizar submódulo con los periodos personalizados de Histórico
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 15:21:18 -06:00
edgar 23f529e85c chore(webapp): actualizar submódulo con las alteraciones del EEG abiertas
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 13:46:26 -06:00
edgar 7ea755d3aa chore(webapp): actualizar submódulo con los cambios de la reunión del 5 de noviembre
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 13:38:53 -06:00
edgar 8802b804ac chore(webapp): actualizar submódulo con la calidad del EEG por criterios
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 12:46:01 -06:00
edgar 3b9099f6bf chore(webapp): actualizar submódulo con las nuevas alteraciones del EEG
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 11:55:07 -06:00
edgar 35bcd2fdcc chore(webapp): actualizar submódulo con la dona de un anillo de M23
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:56:54 -06:00
edgar 6f656cec6d chore(webapp): actualizar submódulo con la nueva redacción del resumen de TEA
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:48:19 -06:00
edgar 0c970b0080 chore(webapp): actualizar submódulo con los filtros de Seguimiento de TEA
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 23:06:37 -06:00
edgar f318fb89da chore(webapp): actualizar submódulo con husos del sueño por etapa
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:56:25 -06:00
edgar 6470e99ea5 chore(webapp): actualizar submódulo con Histórico y acordeón en Seguimiento
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:41:05 -06:00
edgar 0351476ec9 chore(webapp): actualizar submódulo con la pestaña Evolución y la nueva paleta
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:09:02 -06:00
edgar 444c806d5c chore(webapp): actualizar submódulo con botones para resaltar partes de las figuras de TEA 2026-11-03 21:22:51 +00:00
edgar 7fcc7bdfe9 chore(webapp): actualizar submódulo con ficha en tres columnas y dona de M21 2026-11-03 20:28:14 +00:00
edgar 4ab37f8433 chore(webapp): actualizar submódulo con la ficha de paciente de TEA 2026-11-03 19:58:30 +00:00
edgar 92eae777c9 chore(webapp): actualizar submódulo con dona y barras por grupo de edad de TEA 2026-11-03 19:45:32 +00:00
edgar 8b0c0c6733 chore(webapp): actualizar submódulo con enlace «Ir», seguimiento compacto y donas de TEA 2026-11-03 19:23:00 +00:00
edgar 798ba005cd chore(webapp): actualizar submódulo con intervalo de análisis y alteraciones del EEG de TEA
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 00:07:22 +00:00
edgar abd056aa8a chore(webapp): actualizar submódulo con seguimiento, resumen de TEA, periodo único y selector de indicadores
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 23:28:09 +00: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
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
404 changed files with 15499 additions and 113136 deletions
+12 -7
View File
@@ -1,7 +1,12 @@
.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
dist/
**/node_modules/
+36
View File
@@ -0,0 +1,36 @@
# 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
# Model and cohort versions, artifacts, predictions, 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,oracle
# Optional host allowlist (unset = any host reachable from the server).
# WEBAPI_SQL_ALLOWED_HOSTS=10.0.10.41,his-db.internal
# --- Model artifacts (checkpoints, training by-products) ---
# Must live on a persisted volume, not the container's filesystem.
MODELS_ARTIFACT_ROOT=/data/artifacts
# --- 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
+22 -9
View File
@@ -1,10 +1,23 @@
.venv/
__pycache__/
data/
*.db
.dlt/
.pytest_cache/
.ruff_cache/
compose.override.yml
!tests/fixtures/**/*.db
# Local agent notes, not committed.
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
# Agent-session scratch: a scripted/browser E2E harness built up as an
# ad hoc proof-of-work diary across sessions, not project deliverables.
# Equivalent synthetic-data/smoke-test tooling on the team's side lives in
# its own separate repo (dev-data), never inside the main one.
e2e/
.DS_Store
# Deliverable bundle: images and local state are built/created, not versioned.
dist/imagenes/
dist/.env
dist/datos/
dist/*.tar.gz
+7 -6
View File
@@ -1,12 +1,13 @@
[submodule "WebApi"]
path = WebApi
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApi.git
branch = rebuild
[submodule "WebApp"]
path = WebApp
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApp.git
branch = rebuild
[submodule "WebApi"]
path = WebApi
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApi.git
[submodule "models"]
path = models
url = ssh://git@10.0.10.41:2222/ISSSTELEON/models.git
branch = rebuild
[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,62 @@
## 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) |
Validadores:
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| ----------------------------- | ------- | ------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| `bh_id` | INTEGER | entero positivo, no nulo | `BH_ID_AUSENTE` si el campo llega nulo, detectado por `fv:before` al requerir tipo `int` | |
| `ord_numero_hospital` | INTEGER | entero positivo, no nulo, join lógico hacia ordenesstudio | `ORD_NUMERO_AUSENTE` si el campo llega nulo, `ORD_NUMERO_INVALIDO` si no es convertible a int | |
| `pac_id` | INTEGER | entero positivo, nulo permitido si el lookup por pac_id_hospital no resuelve al momento de carga | `PAC_ID_INVALIDO` si el valor no es convertible a int | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo | `PAC_ID_HOSPITAL_AUSENTE` si el campo llega nulo | |
| `bh_fecha` | DATE | fecha de solicitud del estudio, nulo permitido | sin validador implementado | |
| `eritrocitos_mill_ul` | FLOAT | rango [0, 25] millones/µL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera del rango [0, 25] | |
| `hemoglobina_g_dl` | FLOAT | rango [0.5, 75] g/dL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera del rango [0.5, 75]. `BH_HEMOGLOBINA_HEMATOCRITO` cuando `\|hto − 3×hb\| > 10`, evaluado en `mv:after validar_indices_eritrocitarios` | |
| `hematocrito_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_HEMOGLOBINA_HEMATOCRITO` cuando `\|hto − 3×hb\| > 10`, evaluado en `mv:after validar_indices_eritrocitarios` | |
| `vcm_fl` | FLOAT | rango [0, 400] fL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 400]. `BH_VCM_INCOHERENTE` cuando `vcm ≠ 10×hto/rbc` (tolerancia ±15% o ±5 fL), evaluado en `mv:after validar_indices_eritrocitarios` | |
| `hcm_pg` | FLOAT | rango [0, 100] pg, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_HCM_INCOHERENTE` cuando `hcm ≠ 10×hb/rbc` (tolerancia ±15% o ±3 pg), evaluado en `mv:after validar_indices_eritrocitarios` | |
| `chcm_g_dl` | FLOAT | rango [0, 100] g/dL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_CHCM_INCOHERENTE` cuando `chcm ≠ 100×hb/hto` (tolerancia ±15% o ±3 g/dL), evaluado en `mv:after validar_indices_eritrocitarios` | |
| `rdw_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100] | |
| `leucocitos_mil_ul` | FLOAT | rango [0, 500] miles/µL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 500] | |
| `neutrofilos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_DIFERENCIAL_INVALIDO` cuando los cinco componentes básicos (neutrófilos, linfocitos, monocitos, eosinófilos, basófilos) suman ≠ 100% ± 2 pp, evaluado en `mv:after validar_diferencial` | |
| `linfocitos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DIFERENCIAL_INVALIDO` en neutrofilos_pct | |
| `monocitos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DIFERENCIAL_INVALIDO` en neutrofilos_pct | |
| `eosinofilos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DIFERENCIAL_INVALIDO` en neutrofilos_pct | |
| `basofilos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DIFERENCIAL_INVALIDO` en neutrofilos_pct | |
| `neutrofilos_segmentados_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_DESGLOSE_NEUTROFILICO` cuando segmentados + banda + metamielocitos + mielocitos ≠ neutrofilos_pct ± 2 pp, evaluado en `mv:after validar_diferencial` | |
| `neutrofilos_banda_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DESGLOSE_NEUTROFILICO` en neutrofilos_segmentados_pct | |
| `metamielocitos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DESGLOSE_NEUTROFILICO` en neutrofilos_segmentados_pct | |
| `mielocitos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DESGLOSE_NEUTROFILICO` en neutrofilos_segmentados_pct | |
| `plaquetas_mil_ul` | FLOAT | valor ≥ 0 miles/µL, sin máximo de plausibilidad, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor es negativo | |
| `vpm_fl` | FLOAT | valor ≥ 0 fL, sin máximo de plausibilidad, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor es negativo | |
@@ -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),
)
# join logico, resuelto por el loader via lookup en paciente.pac_id_hospital
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
# Identificador del hospital; permite vincular estudios con pacientes
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# join logico hacia ordenes_estudio.ord_numero_hospital, sin 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))
+36
View File
@@ -0,0 +1,36 @@
## 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 |
Validadores:
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| --------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `bx_id` | INTEGER | entero positivo, no nulo | `BX_ID_AUSENTE` si el campo llega nulo, detectado por `fv:before` al requerir tipo `int` | |
| `ord_numero_hospital` | INTEGER | entero positivo, no nulo, join lógico hacia ordenesstudio | `ORD_NUMERO_AUSENTE` si el campo llega nulo, `ORD_NUMERO_INVALIDO` si no es convertible a int | |
| `pac_id` | INTEGER | entero positivo, nulo permitido si el lookup por pac_id_hospital no resuelve al momento de carga | | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo | | |
| `cit_id` | INTEGER | entero positivo, FK hacia citologiacervical, nulo permitido porque una biopsia puede existir sin citología previa documentada | | |
| `bx_fecha_solicitud` | DATE | fecha entregada por sistema estructurado, nulo permitido | `BX_FECHA_SOLICITUD_FUTURA` cuando la fecha es posterior a hoy, verificado en `fv:before fechas_no_futuras` | |
| `bx_fecha_reporte` | DATE | fecha entregada por sistema estructurado, nulo permitido | `BX_FECHA_REPORTE_FUTURA` cuando la fecha es posterior a hoy, verificado en `fv:before fechas_no_futuras`. `BX_REPORTE_ANTES_SOLICITUD` cuando el reporte es anterior a la solicitud, evaluado en `mv:after reporte_no_antes_de_solicitud` | |
| `bx_cin_grado` | TEXT | `GradoCIN` enum, nulo permitido | `BX_CIN_GRADO_INVALIDO` cuando el valor no corresponde al enum tras normalización en `fv:before normalizar_cin_grado` | |
| `bx_ocr_confianza` | FLOAT | valor entre 0.0 y 1.0, nulo permitido | `BX_OCR_CONFIANZA_FUERA_RANGO` cuando el valor cae fuera de 0.0 a 1.0, verificado en `fv:before confianza_en_rango` | `BX_OCR_CONFIANZA_BAJA` cuando el valor es inferior al umbral `BX_OCR_THRESHOLD` (actualmente 0.0, pendiente de ajustar a 0.700 según especificación externa), evaluado en `mv:after ocr_confianza_suficiente` |
| `bx_observaciones` | TEXT | texto libre, nulo permitido | sin validador implementado | |
| `bx_pdf_blob` | BLOB | contenido binario del PDF del reporte histopatológico, nulo permitido | | |
@@ -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" # invasor
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),
)
# join logico, resuelto por el loader via lookup en paciente.pac_id_hospital
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
# Identificador del hospital, obligatorio; permite vincular estudios con pacientes
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# join logico hacia ordenes_estudio.ord_numero_hospital, sin 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,53 @@
## 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 |
Validadores:
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| --------------------------- | ------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `cit_id` | INTEGER | entero positivo, no nulo | `CIT_ID_AUSENTE` si el campo llega nulo, detectado por `fv:before` al requerir tipo `int` | |
| `ord_numero_hospital` | INTEGER | entero positivo, no nulo, join lógico hacia ordenesstudio | `ORD_NUMERO_AUSENTE` si el campo llega nulo, `ORD_NUMERO_INVALIDO` si no es convertible a int | |
| `pac_id` | INTEGER | entero positivo, nulo permitido si el lookup por pac_id_hospital no resuelve al momento de carga | | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo | | |
| `cit_fecha_toma` | DATE | fecha entregada por sistema estructurado, no nulo | `CIT_FECHA_TOMA_FUTURA` cuando la fecha es posterior a hoy, evaluado en `mv:after fechas_plausibles` | |
| `cit_fecha_reporte` | DATE | fecha entregada por sistema estructurado, no nulo | `CIT_FECHA_REPORTE_FUTURA` cuando la fecha es posterior a hoy, `CIT_FECHA_REPORTE_ANTERIOR` cuando el reporte es anterior a la toma, evaluado en `mv:after fechas_plausibles` | |
| `cit_calidad_especimen` | TEXT | SATISFACTORIO, INSATISFACTORIO, nulo permitido | `CALIDAD_INSATISFACTORIA` cuando el valor no corresponde a ninguna entrada conocida tras normalización en `fv:before normalizar_calidad_especimen` | |
| `cit_celulas_escamosas` | TEXT | `CelulasEscamosas` enum, nulo permitido | `CEL_ESC_INVALIDA` cuando el valor no corresponde al enum tras normalización en `fv:before normalizar_celulas_escamosas` | |
| `cit_vph_resultado` | TEXT | `ResultadoVPH` enum, nulo permitido | `VPH_RESULTADO_INVALIDO` cuando el valor no es reconocible tras normalización en `fv:before normalizar_vph_resultado` | `VPH_NO_SOLICITADO` cuando el resultado es nulo y no hay PDF adjunto, `VPH_EXTRACCION_FALLIDA` cuando el resultado es nulo pero hay PDF adjunto, evaluados en `mv:after vph_disponibilidad` |
| `cit_vph_ocr_confianza` | FLOAT | valor entre 0.0 y 1.0, nulo permitido | `CIT_VPH_OCR_SCORE_FUERA_RANGO` cuando el valor cae fuera de 0.0 a 1.0, verificado en `fv:before ocr_score_en_rango` | `VPH_OCR_SCORE_BAJO` cuando el valor es inferior al umbral `VPH_OCR_THRESHOLD`, evaluado en `mv:after vph_ocr_score_suficiente` |
| `cit_vph_genotipo_16` | INTEGER | 0 o 1, nulo permitido | | `VPH_GENOTIPO_INCOHERENTE` cuando el genotipo es positivo pero el resultado VPH es NEGATIVO, evaluado en `mv:after vph_genotipo_coherente` |
| `cit_vph_genotipo_18` | INTEGER | 0 o 1, nulo permitido | | `VPH_GENOTIPO_INCOHERENTE` mismo validador que genotipo 16 |
| `cit_condiciones_ginecoobs` | TEXT | TC2, valores pendientes de confirmar, nulo permitido | sin validador implementado | |
| `cit_dx_lesion` | TEXT | TC6, NEGATIVO, LIEBG, LIEAG, CARCINOMA_EPIDERMOIDE, AGC, ADENOCARCINOMA, OTRAS_NEOPLASIAS, NO_VALORABLE, nulo permitido | sin validador implementado | |
| `cit_celulas_glandulares` | TEXT | TC9, valores pendientes de confirmar, nulo permitido | sin validador implementado | |
| `cit_carcinoma_invasor` | TEXT | TC8, almacenado como TEXT, nulo permitido | sin validador implementado | |
| `cit_exploracion` | TEXT | TC4, texto libre para NLP, nulo permitido | sin validador implementado | |
| `cit_observaciones` | TEXT | TC10, texto libre para NLP, nulo permitido | sin validador implementado | |
| `cit_pdf_blob` | BLOB | contenido binario del PDF del resultado citológico, nulo permitido | | |
| `cit_vph_pdf_blob` | BLOB | contenido binario del PDF del resultado VPH, nulo permitido | | |
@@ -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] = {
# Se tienen las formas largas, asumiendo que aparecerán igual que en la plataforma
"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", # sin tilde
"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 "negativo para lesión intraepitelial o malignidad" (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] = {
# Formas en cadenas asumidas por plataformas
"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),
)
# join logico, resuelto por el loader via lookup en paciente.pac_id_hospital
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
# Identificador del hospital, obligatorio; permite vincular estudios con pacientes
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# join logico hacia ordenes_estudio.ord_numero_hospital, sin 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; hacer enum cuando se conozcan valores",
)
cit_condiciones_ginecoobs: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Condiciones gineco-obstétricas: embarazo, DIU, etc.; hacer enum",
)
cit_exploracion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Hallazgos en exploración; hacer enum",
)
cit_dx_lesion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="TC6 Diagnóstico citológico para lesión; hacer enum",
)
cit_celulas_glandulares: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="TC9 Anomalías del epitelio glandular; hacer enum",
)
cit_carcinoma_invasor: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="TC8 Carcinoma epidermoide invasor, hacer enum",
)
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: además de la confianza se guarda el estatus, la bandera de
# revisión manual y el método (principal o alternativo) que produjo el valor.
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(),)
-386
View File
@@ -1,386 +0,0 @@
"""CaCu's measures (`core.measures` evaluates them) and the follow-up status they stratify by."""
from dataclasses import dataclass
from datetime import date
import statistics
from core import cacu
from core.measures import (
NO_BIOPSY,
NO_DATA,
Composition,
Duration,
Measure,
Period,
Proportion,
Result,
RiskBand,
Result,
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:
"""Recorded request units, classified at the event cutoff, not all HIS referrals."""
kind: str = "composition"
def evaluate(self, rows, period, cutoff):
chosen = {}
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 = {}
for _, category in chosen.values():
cell = categories.setdefault(category, {"initial-population": 0})
cell["initial-population"] += 1
count = len(chosen)
return Result({"initial-population": count, "measure-observation": count},
strata={"category": categories})
@dataclass(frozen=True)
class DiagnosisDurations:
kind: str = "continuous-variable"
strata: tuple = (("diagnosis_code", None),)
def evaluate(self, rows, period, cutoff):
rule = Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=lambda r: r["history"] == 0)
overall = rule.evaluate(rows, period, cutoff)
grouped = {}
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):
continue
code = row.get("diagnosis_code") or "sin_codigo"
grouped.setdefault(code, []).append(row)
cells, scores = {}, {}
for code, group in grouped.items():
values = sorted(float(r["days_sample_diagnosis"]) for r in group)
median = statistics.median(values)
q1, q3 = (values[0], values[0]) if len(values) == 1 else (statistics.quantiles(values, n=4, method="inclusive")[0], statistics.quantiles(values, n=4, method="inclusive")[2])
descriptions = {r.get("diagnosis_description") for r in group if r.get("diagnosis_description")}
label = code + (" | " + next(iter(descriptions)) if len(descriptions) == 1 else "")
cells[label] = {"measure-observation": len(values)}
scores[label] = {"value": median, "unit": "d", "extension": [
{"url": "https://isssteleon.org/fhir/StructureDefinition/q1", "valueDecimal": q1},
{"url": "https://isssteleon.org/fhir/StructureDefinition/q3", "valueDecimal": q3}]}
return Result(overall.populations, overall.score, overall.score_extensions, overall.unit,
{"diagnosis_code": cells}, {"diagnosis_code": scores})
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",
]
+63
View File
@@ -0,0 +1,63 @@
## 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) |
---
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
|---|---|---|---|---|
| `nm_id` | INTEGER | entero positivo, autoincrement, no nulo | `NM_ID_AUSENTE` si el campo llega nulo | |
| `pac_id` | INTEGER | entero positivo, indexado, nulo permitido | `PAC_ID_AUSENTE`, `PAC_ID_INVALIDO` | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, indexado, no nulo en schema de validación | | |
| `nm_id_hospital` | TEXT | alfanumérico, no nulo en schema de validación; normalizado con strip y uppercase | `NM_ID_HOSPITAL_AUSENTE` cuando llega nulo | |
| `nm_nota_previa_id` | TEXT | alfanumérico, nulo si es nota inaugural; normalizado con strip | | |
| `nm_tipo_nota` | TEXT | `TipoNota` enum: CONSULTA, EGRESO, INGRESO, URG_EGRESO; alias TIPO_NOTA_ALIAS resuelve variantes HIS ("URG. EGRESO"); no nulo | `NM_TIPO_NOTA_AUSENTE` cuando llega nulo, `NM_TIPO_NOTA_INVALIDA` cuando el valor no corresponde al enum tras normalización | |
| `nm_especialidad` | TEXT | `Especialidad` enum: MEDICINA_FAMILIAR, CIRUGIA_ONCOLOGICA, CLINICA_MUJER_COLPOSCOPIA; alias ESPECIALIDAD_ALIAS resuelve variantes HIS; no nulo | `NM_ESPECIALIDAD_AUSENTE` cuando llega nulo, `NM_ESPECIALIDAD_INVALIDA` cuando el valor no corresponde al enum tras normalización | |
| `nm_fecha` | DATE | fecha de la consulta, no nulo en schema de validación | `NM_FECHA_AUSENTE` cuando llega nulo, `NM_FECHA_FUTURA` cuando es posterior a hoy | |
| `nm_medico_tratante` | TEXT | texto libre, máximo 100 caracteres, nulo permitido | `NM_MEDICO_TRATANTE_INVALIDO` cuando supera 100 caracteres | |
| `nm_motivo_consulta` | TEXT | texto libre, no nulo en schema de validación; normalizado con strip | `NM_MOTIVO_CONSULTA_AUSENTE` cuando llega nulo | |
| `nm_interrogatorio` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_diagnostico_texto` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_cie_codigo` | TEXT | formato `[A-Z][0-9]{2}(\.[0-9]{1,2})?`, nulo permitido | `NM_CIE_CODIGO_INVALIDO` cuando no cumple el formato regex | |
| `nm_cie_descripcion` | TEXT | texto libre, máximo 200 caracteres, nulo permitido | `NM_CIE_DESCRIPCION_INVALIDA` cuando supera 200 caracteres | |
| `nm_tratamiento_texto` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_receta` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_plan_estudios` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_pronostico` | TEXT | texto libre normalizado con strip y uppercase, nulo permitido | | |
| `nm_observaciones` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_masa_corporal` | FLOAT | rango [20.0, 300.0] kg, nulo permitido | `NM_MASA_CORPORAL_FUERA_RANGO` cuando cae fuera del rango | |
| `nm_talla` | FLOAT | rango [100, 250] cm, nulo permitido | `NM_TALLA_FUERA_RANGO` cuando cae fuera del rango | |
| `nm_imc_visita` | FLOAT | rango [12.0, 90.0], nulo si peso o talla ausentes | `NM_IMC_FUERA_RANGO` cuando cae fuera del rango, `NM_IMC_INCOHERENTE` cuando no corresponde a peso/talla registrados (tolerancia ±0.5) | |
| `nm_frecuencia_cardiaca` | INTEGER | rango [0, 500] lpm, nulo permitido | `NM_FRECUENCIA_CARDIACA_FUERA_RANGO` cuando cae fuera del rango | |
| `nm_frecuencia_respiratoria` | INTEGER | rango [0, 200] rpm, nulo permitido | `NM_FRECUENCIA_RESPIRATORIA_FUERA_RANGO` cuando cae fuera del rango | |
| `nm_presion_arterial_sistolica` | INTEGER | rango [0, 560] mmHg, nulo permitido | `NM_PRESION_SISTOLICA_FUERA_RANGO` cuando cae fuera del rango, `NM_PRESION_INCOHERENTE` cuando la sistólica no supera a la diastólica | |
| `nm_presion_arterial_diastolica` | INTEGER | rango [0, 360] mmHg, nulo permitido | `NM_PRESION_DIASTOLICA_FUERA_RANGO` cuando cae fuera del rango, `NM_PRESION_INCOHERENTE` cuando la sistólica no supera a la diastólica | |
| `nm_temperatura` | FLOAT | rango [24.0, 45.0] °C, nulo permitido | `NM_TEMPERATURA_FUERA_RANGO` cuando cae fuera del rango | |
+1
View File
@@ -0,0 +1 @@
from core.cacu.nota_medica.model import NotaMedica
+41
View File
@@ -0,0 +1,41 @@
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"
# TODO: otros valores pendientes de confirmar con el HIS
PARENTESCO_ALIAS: dict[str, str] = {
"AFILIADO": "Afiliado",
}
class Dependencia(str, Enum):
GOBIERNO = "GOBIERNO"
CALLES_Y_CAMINOS = "CALLES Y CAMINOS"
# TODO: valores tentativos — confirmar con administrador del HIS
DEPENDENCIA_ALIAS: dict[str, str] = {
"CALLES Y CAMINOS": "CALLES Y CAMINOS",
}
# TODO: EstatusOrden -- valores pendientes de confirmar con administrador del HIS
+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),
)
+40
View File
@@ -0,0 +1,40 @@
## 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 |
Validadores:
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| --------------------- | ------- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ----------------------------- |
| `ord_id` | INTEGER | entero positivo, autoincrement, no nulo | | |
| `pac_id` | INTEGER | entero positivo, FK hacia paciente, nulo si el lookup falla al momento de ingesta | | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo | | |
| `ord_numero_hospital` | INTEGER | entero de 5 dígitos, identificador de la orden en el HIS, índice único, no nulo | `ORD_NUMERO_AUSENTE` cuando la clave llega ausente del dict, `ORD_NUMERO_INVALIDO` cuando el valor no es convertible a entero | |
| `ord_tipo_estudio` | TEXT | valores pendientes de confirmar con administrador, nulo permitido. Candidatos: CITOLOGIA_CERVICAL, TAMIZAJE_VPH, BIOPSIA_CERVICAL | sin validador implementado | |
| `ord_fecha` | DATE | fecha de emisión de la orden por el médico, nulo permitido | sin validador implementado | |
| `ord_fecha_solicitud` | DATE | fecha sugerida por el médico para realizar el estudio, nulo permitido | sin validador implementado | |
| `ord_fecha_resultado` | DATE | fecha en que el resultado estuvo disponible, nulo permitido porque la orden puede existir sin resultado | sin validador implementado | |
| `ord_estatus` | TEXT | valores pendientes de confirmar con administrador, nulo permitido. Candidatos: SOLICITADO, EN_PROCESO, RESULTADO_DISPONIBLE, CANCELADO | sin validador implementado | |
| `ord_diagnostico` | TEXT | diagnóstico presuntivo del médico, pantalla Asignar diagnóstico, texto libre, nulo permitido | sin validador implementado | |
| `ord_observaciones` | TEXT | texto libre, nulo permitido | sin validador implementado | |
| `ord_especialidad` | TEXT | valores pendientes de confirmar con administrador, nulo permitido. Candidatos: GINECOLOGIA, ONCOLOGIA, MEDICINA_FAMILIAR, COLPOSCOPIA, OTRO | sin validador implementado | |
| `ord_medico_solicitante` | TEXT | nombre o clave del médico tratante, texto libre, nulo permitido | sin validador implementado | |
@@ -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),
)
# Desnormalizado para joins directos sin pasar por 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",
)
+27
View File
@@ -0,0 +1,27 @@
## 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 |
Validadores:
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| ---------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pac_id` | INTEGER | entero positivo, no nulo | `PAC_ID_AUSENTE` si el campo llega nulo, detectado por `fv:before` al requerir tipo `int` | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo | | |
| `pac_sexo` | TEXT | `SexoBiologico` enum, nulo permitido | `SEXO_INVALIDO` cuando el valor no corresponde a ninguna entrada del enum, normalizado en `fv:before` con strip y uppercase antes de la coerción | |
| `pac_fecha_nacimiento` | DATE | fecha, nulo permitido | `FECHA_NACIMIENTO_FUTURA` cuando la fecha es posterior a hoy, verificado en `fv:before fecha_nacimiento_no_futura` | `EDAD_FUERA_DE_RANGO` cuando la edad implícita cae fuera del rango de 1 a 110 años, evaluado en `mv:after edad_plausible_para_registro` una vez que la fecha fue validada |
| `pac_codigo_postal` | CHAR(5) | CP de 5 dígitos, nulo permitido. El ORM tiene una `CheckConstraint` REGEXP para el formato pero no está disponible en SQLite | sin validador implementado en schema | |
| `pac_dependencia` | TEXT | valores pendientes de confirmar con administrador, nulo permitido | sin validador implementado | |
| `pac_parentesco` | TEXT | texto libre, nulo permitido, sin fuente documentada | sin validador implementado | |
+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",
}
+50
View File
@@ -0,0 +1,50 @@
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),
)
# Identificador original del paciente en el HIS (DG1), con indice unico para busquedas
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: obligatoria; el sistema calcula la edad en cada evento de
# interés (episodio clínico) a partir de esta fecha.
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),
# sa.CheckConstraint("pac_codigo_postal REGEXP '^[0-9]{5}$'"), # CheckConstraint con REGEXP no aplica en SQLite
),
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",
)
-27
View File
@@ -1,27 +0,0 @@
"""Stage facts for a sample, using gold's dates and explicit biopsy links."""
def stage_facts(sample, biopsies, events, cutoff):
def day(value):
return str(value)[:10] if value is not None else None
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:
matches = {(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(matches) == 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:
b = linked[0]
reported = day(b.get('report_date'))
if reported and reported < day(b['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,62 @@
## 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) |
Validadores:
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| ----------------------------- | ------- | ------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| `bh_id` | INTEGER | entero positivo, no nulo | `BH_ID_AUSENTE` si el campo llega nulo, detectado por `fv:before` al requerir tipo `int` | |
| `ord_numero_hospital` | INTEGER | entero positivo, no nulo, join lógico hacia ordenesstudio | `ORD_NUMERO_AUSENTE` si el campo llega nulo, `ORD_NUMERO_INVALIDO` si no es convertible a int | |
| `pac_id` | INTEGER | entero positivo, nulo permitido si el lookup por pac_id_hospital no resuelve al momento de carga | `PAC_ID_INVALIDO` si el valor no es convertible a int | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo | `PAC_ID_HOSPITAL_AUSENTE` si el campo llega nulo | |
| `bh_fecha` | DATE | fecha de solicitud del estudio, nulo permitido | sin validador implementado | |
| `eritrocitos_mill_ul` | FLOAT | rango [0, 25] millones/µL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera del rango [0, 25] | |
| `hemoglobina_g_dl` | FLOAT | rango [0.5, 75] g/dL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera del rango [0.5, 75]. `BH_HEMOGLOBINA_HEMATOCRITO` cuando `\|hto − 3×hb\| > 10`, evaluado en `mv:after validar_indices_eritrocitarios` | |
| `hematocrito_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_HEMOGLOBINA_HEMATOCRITO` cuando `\|hto − 3×hb\| > 10`, evaluado en `mv:after validar_indices_eritrocitarios` | |
| `vcm_fl` | FLOAT | rango [0, 400] fL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 400]. `BH_VCM_INCOHERENTE` cuando `vcm ≠ 10×hto/rbc` (tolerancia ±15% o ±5 fL), evaluado en `mv:after validar_indices_eritrocitarios` | |
| `hcm_pg` | FLOAT | rango [0, 100] pg, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_HCM_INCOHERENTE` cuando `hcm ≠ 10×hb/rbc` (tolerancia ±15% o ±3 pg), evaluado en `mv:after validar_indices_eritrocitarios` | |
| `chcm_g_dl` | FLOAT | rango [0, 100] g/dL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_CHCM_INCOHERENTE` cuando `chcm ≠ 100×hb/hto` (tolerancia ±15% o ±3 g/dL), evaluado en `mv:after validar_indices_eritrocitarios` | |
| `rdw_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100] | |
| `leucocitos_mil_ul` | FLOAT | rango [0, 500] miles/µL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 500] | |
| `neutrofilos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_DIFERENCIAL_INVALIDO` cuando los cinco componentes básicos (neutrófilos, linfocitos, monocitos, eosinófilos, basófilos) suman ≠ 100% ± 2 pp, evaluado en `mv:after validar_diferencial` | |
| `linfocitos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DIFERENCIAL_INVALIDO` en neutrofilos_pct | |
| `monocitos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DIFERENCIAL_INVALIDO` en neutrofilos_pct | |
| `eosinofilos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DIFERENCIAL_INVALIDO` en neutrofilos_pct | |
| `basofilos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DIFERENCIAL_INVALIDO` en neutrofilos_pct | |
| `neutrofilos_segmentados_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_DESGLOSE_NEUTROFILICO` cuando segmentados + banda + metamielocitos + mielocitos ≠ neutrofilos_pct ± 2 pp, evaluado en `mv:after validar_diferencial` | |
| `neutrofilos_banda_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DESGLOSE_NEUTROFILICO` en neutrofilos_segmentados_pct | |
| `metamielocitos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DESGLOSE_NEUTROFILICO` en neutrofilos_segmentados_pct | |
| `mielocitos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DESGLOSE_NEUTROFILICO` en neutrofilos_segmentados_pct | |
| `plaquetas_mil_ul` | FLOAT | valor ≥ 0 miles/µL, sin máximo de plausibilidad, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor es negativo | |
| `vpm_fl` | FLOAT | valor ≥ 0 fL, sin máximo de plausibilidad, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor es negativo | |
@@ -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),
)
# join logico, resuelto por el loader via lookup en paciente.pac_id_hospital
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
# Identificador del hospital; permite vincular estudios con pacientes
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# join logico hacia ordenes_estudio.ord_numero_hospital, sin 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))
+30
View File
@@ -0,0 +1,30 @@
## 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 generada por SQLite |
| `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 |
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| --------------------- | ------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| `bx_id` | INTEGER | entero positivo, autoincrement, no nulo | `BX_ID_AUSENTE` si el campo llega nulo, detectado por `fv:before` al requerir tipo `int` | |
| `pac_id` | INTEGER | entero positivo, sin FK constraint, indexado, nulo permitido si el lookup falla al momento de ingesta | | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo en schema de validación, indexado | | |
| `ord_id` | INTEGER | FK formal a `ordenesestudio.ord_id`, indexado, nulo si el lookup falla | | |
| `ord_numero_hospital` | INTEGER | entero, clave de join para resolver `ord_id`, indexado, nulo permitido | | |
| `mast_id` | INTEGER | entero positivo, FK formal hacia mastografia con integridad referencial en SQLite, nulo permitido | | |
| `bx_fecha_solicitud` | DATE | fecha del sistema estructurado, nulo permitido | `BX_FECHA_SOLICITUD_FUTURA` cuando la fecha es posterior a hoy, verificado en `fv:before fechas_no_futuras` | |
| `bx_fecha_reporte` | DATE | fecha del sistema estructurado, nulo permitido | `BX_FECHA_REPORTE_FUTURA` cuando la fecha es posterior a hoy, verificado en `fv:before fechas_no_futuras`, `BX_REPORTE_ANTES_SOLICITUD` cuando el reporte es anterior a la solicitud, evaluado en `mv:after reporte_no_antes_de_solicitud` | |
| `bx_grado_histologico`| TEXT | `GradoHistologicoMama` enum, valores BENIGNO, CARCINOMA_IN_SITU, CARCINOMA_INVASOR, DESCONOCIDO, no nulo | `BX_GRADO_HISTOLOGICO_INVALIDO` cuando el valor no corresponde al enum tras normalización con strip y uppercase, evaluado en `fv:before normalizar_grado_histologico` | |
| `bx_pdf_blob` | BLOB | contenido binario del PDF, nulo permitido | | |
| `bx_ocr_confianza` | FLOAT | valor entre 0.0 y 1.0, nulo permitido | `BX_OCR_CONFIANZA_FUERA_RANGO` cuando cae fuera de [0.0, 1.0], verificado en `fv:before confianza_en_rango`, `BX_OCR_CONFIANZA_BAJA` cuando es inferior al umbral `BX_OCR_THRESHOLD` y el grado está presente, evaluado en `mv:after ocr_confianza_suficiente` | |
+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: tuple[str, ...] = ()
REPORT_FACTS: dict[str, str] = {}
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(),)
+30
View File
@@ -0,0 +1,30 @@
## 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 generada por SQLite |
| `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 |
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| --------------------- | ------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| `mast_id` | INTEGER | entero positivo, autoincrement, no nulo | `MAST_ID_AUSENTE` si el campo llega nulo, detectado por `fv:before` al requerir tipo `int` | |
| `pac_id` | INTEGER | entero positivo, sin FK constraint, indexado, nulo permitido si el lookup falla al momento de ingesta | | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo en schema de validación, indexado | | |
| `ord_id` | INTEGER | FK formal a `ordenesestudio.ord_id`, indexado, nulo si el lookup falla | | |
| `ord_numero_hospital` | INTEGER | entero, join lógico hacia ordenes_estudio sin FK constraint, indexado, nulo permitido | | |
| `mast_fecha_toma` | DATE | fecha entregada por DICOM, nulo permitido | `MAST_FECHA_TOMA_FUTURA` cuando la fecha es posterior a hoy, evaluado en `mv:after fechas_plausibles` | |
| `mast_fecha_reporte` | DATE | fecha del reporte, nulo permitido | `MAST_FECHA_REPORTE_FUTURA` cuando la fecha es posterior a hoy, `MAST_FECHA_REPORTE_ANTERIOR` cuando es anterior a la toma, ambos evaluados en `mv:after fechas_plausibles` | |
| `mast_calidad_imagen` | TEXT | texto libre normalizado con strip y uppercase, nulo permitido, valores reales pendientes de confirmar | | |
| `mast_birads` | TEXT | `BIRADS` enum, nulo permitido, valores B0 a B6, resolución de alias DICOM en `BIRADS_ALIAS` | `MAST_BIRADS_INVALIDO` cuando el valor no corresponde al enum ni a ninguna entrada del alias, evaluado en `fv:before normalizar_birads` | |
| `mast_dicom_blob` | BLOB | contenido binario del archivo DICOM, nulo permitido | | |
| `mast_interpretacion` | TEXT | enlace o referencia a la interpretación del radiólogo, nulo permitido, formato pendiente de confirmar | | |
+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" # incompleto
B1 = "B1" # negativo
B2 = "B2" # hallazgo benigno
B3 = "B3" # probablemente benigno
B4 = "B4" # sospechoso
B5 = "B5" # altamente sospechoso
B6 = "B6" # malignidad confirmada
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",
]
+63
View File
@@ -0,0 +1,63 @@
## 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) |
---
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
|---|---|---|---|---|
| `nm_id` | INTEGER | entero positivo, autoincrement, no nulo | `NM_ID_AUSENTE` si el campo llega nulo | |
| `pac_id` | INTEGER | entero positivo, indexado, nulo permitido | `PAC_ID_AUSENTE`, `PAC_ID_INVALIDO` | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, indexado, no nulo en schema de validación | | |
| `nm_id_hospital` | TEXT | alfanumérico, no nulo en schema de validación; normalizado con strip y uppercase | `NM_ID_HOSPITAL_AUSENTE` cuando llega nulo | |
| `nm_nota_previa_id` | TEXT | alfanumérico, nulo si es nota inaugural; normalizado con strip | | |
| `nm_tipo_nota` | TEXT | `TipoNota` enum: CONSULTA, EGRESO, INGRESO, URG_EGRESO; alias TIPO_NOTA_ALIAS resuelve variantes HIS ("URG. EGRESO"); no nulo | `NM_TIPO_NOTA_AUSENTE` cuando llega nulo, `NM_TIPO_NOTA_INVALIDA` cuando el valor no corresponde al enum tras normalización | |
| `nm_especialidad` | TEXT | `Especialidad` enum: MEDICINA_FAMILIAR, CIRUGIA_ONCOLOGICA, CLINICA_MUJER_COLPOSCOPIA; alias ESPECIALIDAD_ALIAS resuelve variantes HIS; no nulo | `NM_ESPECIALIDAD_AUSENTE` cuando llega nulo, `NM_ESPECIALIDAD_INVALIDA` cuando el valor no corresponde al enum tras normalización | |
| `nm_fecha` | DATE | fecha de la consulta, no nulo en schema de validación | `NM_FECHA_AUSENTE` cuando llega nulo, `NM_FECHA_FUTURA` cuando es posterior a hoy | |
| `nm_medico_tratante` | TEXT | texto libre, máximo 100 caracteres, nulo permitido | `NM_MEDICO_TRATANTE_INVALIDO` cuando supera 100 caracteres | |
| `nm_motivo_consulta` | TEXT | texto libre, no nulo en schema de validación; normalizado con strip | `NM_MOTIVO_CONSULTA_AUSENTE` cuando llega nulo | |
| `nm_interrogatorio` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_diagnostico_texto` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_cie_codigo` | TEXT | formato `[A-Z][0-9]{2}(\.[0-9]{1,2})?`, nulo permitido | `NM_CIE_CODIGO_INVALIDO` cuando no cumple el formato regex | |
| `nm_cie_descripcion` | TEXT | texto libre, máximo 200 caracteres, nulo permitido | `NM_CIE_DESCRIPCION_INVALIDA` cuando supera 200 caracteres | |
| `nm_tratamiento_texto` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_receta` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_plan_estudios` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_pronostico` | TEXT | texto libre normalizado con strip y uppercase, nulo permitido | | |
| `nm_observaciones` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_masa_corporal` | FLOAT | rango [20.0, 300.0] kg, nulo permitido | `NM_MASA_CORPORAL_FUERA_RANGO` cuando cae fuera del rango | |
| `nm_talla` | FLOAT | rango [100, 250] cm, nulo permitido | `NM_TALLA_FUERA_RANGO` cuando cae fuera del rango | |
| `nm_imc_visita` | FLOAT | rango [12.0, 90.0], nulo si peso o talla ausentes | `NM_IMC_FUERA_RANGO` cuando cae fuera del rango, `NM_IMC_INCOHERENTE` cuando no corresponde a peso/talla registrados (tolerancia ±0.5) | |
| `nm_frecuencia_cardiaca` | INTEGER | rango [0, 500] lpm, nulo permitido | `NM_FRECUENCIA_CARDIACA_FUERA_RANGO` cuando cae fuera del rango | |
| `nm_frecuencia_respiratoria` | INTEGER | rango [0, 200] rpm, nulo permitido | `NM_FRECUENCIA_RESPIRATORIA_FUERA_RANGO` cuando cae fuera del rango | |
| `nm_presion_arterial_sistolica` | INTEGER | rango [0, 560] mmHg, nulo permitido | `NM_PRESION_SISTOLICA_FUERA_RANGO` cuando cae fuera del rango, `NM_PRESION_INCOHERENTE` cuando la sistólica no supera a la diastólica | |
| `nm_presion_arterial_diastolica` | INTEGER | rango [0, 360] mmHg, nulo permitido | `NM_PRESION_DIASTOLICA_FUERA_RANGO` cuando cae fuera del rango, `NM_PRESION_INCOHERENTE` cuando la sistólica no supera a la diastólica | |
| `nm_temperatura` | FLOAT | rango [24.0, 45.0] °C, nulo permitido | `NM_TEMPERATURA_FUERA_RANGO` cuando cae fuera del rango | |
+1
View File
@@ -0,0 +1 @@
from core.cama.nota_medica.model import NotaMedica
+41
View File
@@ -0,0 +1,41 @@
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"
# TODO: otros valores pendientes de confirmar con el HIS
PARENTESCO_ALIAS: dict[str, str] = {
"AFILIADO": "Afiliado",
}
class Dependencia(str, Enum):
GOBIERNO = "GOBIERNO"
CALLES_Y_CAMINOS = "CALLES Y CAMINOS"
# TODO: valores tentativos — confirmar con administrador del HIS
DEPENDENCIA_ALIAS: dict[str, str] = {
"CALLES Y CAMINOS": "CALLES Y CAMINOS",
}
# TODO: EstatusOrden -- valores pendientes de confirmar con administrador del HIS
+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),
)
+40
View File
@@ -0,0 +1,40 @@
## 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 |
Validadores:
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| --------------------- | ------- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ----------------------------- |
| `ord_id` | INTEGER | entero positivo, autoincrement, no nulo | | |
| `pac_id` | INTEGER | entero positivo, FK hacia paciente, nulo si el lookup falla al momento de ingesta | | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo | | |
| `ord_numero_hospital` | INTEGER | entero de 5 dígitos, identificador de la orden en el HIS, índice único, no nulo | `ORD_NUMERO_AUSENTE` cuando la clave llega ausente del dict, `ORD_NUMERO_INVALIDO` cuando el valor no es convertible a entero | |
| `ord_tipo_estudio` | TEXT | valores pendientes de confirmar con administrador, nulo permitido. Candidatos: CITOLOGIA_CERVICAL, TAMIZAJE_VPH, BIOPSIA_CERVICAL | sin validador implementado | |
| `ord_fecha` | DATE | fecha de emisión de la orden por el médico, nulo permitido | sin validador implementado | |
| `ord_fecha_solicitud` | DATE | fecha sugerida por el médico para realizar el estudio, nulo permitido | sin validador implementado | |
| `ord_fecha_resultado` | DATE | fecha en que el resultado estuvo disponible, nulo permitido porque la orden puede existir sin resultado | sin validador implementado | |
| `ord_estatus` | TEXT | valores pendientes de confirmar con administrador, nulo permitido. Candidatos: SOLICITADO, EN_PROCESO, RESULTADO_DISPONIBLE, CANCELADO | sin validador implementado | |
| `ord_diagnostico` | TEXT | diagnóstico presuntivo del médico, pantalla Asignar diagnóstico, texto libre, nulo permitido | sin validador implementado | |
| `ord_observaciones` | TEXT | texto libre, nulo permitido | sin validador implementado | |
| `ord_especialidad` | TEXT | valores pendientes de confirmar con administrador, nulo permitido. Candidatos: GINECOLOGIA, ONCOLOGIA, MEDICINA_FAMILIAR, COLPOSCOPIA, OTRO | sin validador implementado | |
| `ord_medico_solicitante` | TEXT | nombre o clave del médico tratante, texto libre, nulo permitido | sin validador implementado | |
@@ -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),
)
# Desnormalizado para joins directos sin pasar por 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",
)
+27
View File
@@ -0,0 +1,27 @@
## 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 |
Validadores:
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| ---------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pac_id` | INTEGER | entero positivo, no nulo | `PAC_ID_AUSENTE` si el campo llega nulo, detectado por `fv:before` al requerir tipo `int` | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo | | |
| `pac_sexo` | TEXT | `SexoBiologico` enum, nulo permitido | `SEXO_INVALIDO` cuando el valor no corresponde a ninguna entrada del enum, normalizado en `fv:before` con strip y uppercase antes de la coerción | |
| `pac_fecha_nacimiento` | DATE | fecha, nulo permitido | `FECHA_NACIMIENTO_FUTURA` cuando la fecha es posterior a hoy, verificado en `fv:before fecha_nacimiento_no_futura` | `EDAD_FUERA_DE_RANGO` cuando la edad implícita cae fuera del rango de 1 a 110 años, evaluado en `mv:after edad_plausible_para_registro` una vez que la fecha fue validada |
| `pac_codigo_postal` | CHAR(5) | CP de 5 dígitos, nulo permitido. El ORM tiene una `CheckConstraint` REGEXP para el formato pero no está disponible en SQLite | sin validador implementado en schema | |
| `pac_dependencia` | TEXT | valores pendientes de confirmar con administrador, nulo permitido | sin validador implementado | |
| `pac_parentesco` | TEXT | texto libre, nulo permitido, sin fuente documentada | sin validador implementado | |
+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",
}
+50
View File
@@ -0,0 +1,50 @@
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),
)
# Identificador original del paciente en el HIS (DG1), con indice unico para busquedas
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: obligatoria; el sistema calcula la edad en cada evento de
# interés (episodio clínico) a partir de esta fecha.
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),
# sa.CheckConstraint("pac_codigo_postal REGEXP '^[0-9]{5}$'"), # CheckConstraint con REGEXP no aplica en SQLite; la regla de 5 dígitos se valida en la capa de importación
),
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",
)
-187
View File
@@ -1,187 +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 = {
name: (_annotation(f), ... if f.required else None) 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
-119
View File
@@ -1,119 +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}
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
-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}
-49
View File
@@ -1,49 +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
-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 (`../../../_docs/esquema_generico_catalogos.md` §3 y §5).
La arista `catalogos` de 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 {}
-470
View File
@@ -1,470 +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
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",
}),
"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()
# 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
# 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", ["MeasureReport.group.measureScore"]),
"q3": ("decimal", ["MeasureReport.group.measureScore"]),
"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"]),
"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"]),
} # 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))
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 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."""
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"]}]
found: dict = {
"resourceType": "Condition",
"id": _id("condition", person, day, row.get("specialty")),
"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) -> Procedure:
"""A procedure the timeline inferred (`gold.cacu_events`: colposcopy, treatment)."""
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("cacu-procedure", row["type"]),
"subject": subject(person),
"performedDateTime": day,
}) # fmt: skip
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."""
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}],
"text": f"{model} v{row['version']}"},
"subject": subject(row["person_id"]),
"occurrenceDateTime": _day(row["index_date"]),
"prediction": predictions,
}) # 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", "Cutoff for sample-linked stages"),
"follow-up-age-min": ("Patient", "number", "Minimum completed age at the cutoff"),
"follow-up-age-max": ("Patient", "number", "Maximum completed age at the cutoff"),
"follow-up-search": ("Patient", "string", "Partial name or identifier"),
"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
+14
View File
@@ -0,0 +1,14 @@
import sqlalchemy.orm as orm
from sqlmodel import SQLModel
registry = orm.registry()
class GovernanceModel(SQLModel, registry=registry):
"""Base class for the governance domain: cohort and model versioning,
training artifacts and persisted predictions (EL, ML and MLD requirements).
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.
"""
@@ -0,0 +1,44 @@
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 CohortExclusion(GovernanceModel, table=True):
"""EL-05: one row per excluded episode, with the criterion and reason code.
EL-04a: rows are only written when building the training cohort
(`models.cohort.CohortBuilder.build`). The production applicability check
(EL-04b, `models.cohort.evaluate_applicability`) does not write here.
"""
cohort_exclusion_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
cohort_version_id: int = Field(
sa_column=sa.Column(sa.Integer, sa.ForeignKey("cohortversion.cohort_version_id"), 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),
)
criterion_code: str = Field(
sa_column=sa.Column(sa.String(64), nullable=False, index=True),
description="código del criterio de exclusión evaluado (p.ej. EDAD_FUERA_DE_RANGO)",
)
reason_code: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="EL-05: código de razón específico de por qué este criterio excluyó al episodio",
)
excluded_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_column=sa.Column(sa.DateTime, nullable=False),
)
@@ -0,0 +1,35 @@
from datetime import datetime, timezone
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.governance.base import GovernanceModel
class CohortExclusionCount(GovernanceModel, table=True):
"""EL-07: per-criterion exclusion count for a cohort version (TRIPOD+AI 20a).
Written once by the same `build()` that writes `CohortExclusion`, so the
count is materialized with the cohort instead of derived on demand.
"""
cohort_exclusion_count_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
cohort_version_id: int = Field(
sa_column=sa.Column(sa.Integer, sa.ForeignKey("cohortversion.cohort_version_id"), nullable=False, index=True),
)
criterion_code: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
)
reason_code: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
)
count: int = Field(
sa_column=sa.Column(sa.Integer, nullable=False),
)
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