Compare commits

..

13 Commits

Author SHA1 Message Date
Angel Capetillo Zavala 4ac3026bb1 feat(auth): integrar flujo de autenticacion 2026-09-29 13:51:33 -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
331 changed files with 5076 additions and 373475 deletions
+12 -7
View File
@@ -1,7 +1,12 @@
.venv
data
**/__pycache__
**/target
**/logs
WebApp
.git
# WebApi's docker-compose service builds with context: . (this directory)
# so it can COPY its sibling Core/, Persistance/ and models/ directories —
# this is the .dockerignore Docker actually reads for that build.
.git/
WebApp/
**/__pycache__/
**/*.pyc
**/.venv/
**/*.egg-info/
**/.pytest_cache/
**/*.db
**/uv.lock
-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
+4 -10
View File
@@ -1,10 +1,4 @@
.venv/
__pycache__/
data/
*.db
.dlt/
.pytest_cache/
.ruff_cache/
compose.override.yml
!tests/fixtures/**/*.db
.env
# Local orientation docs, not committed anywhere in this workspace.
CLAUDE.md
.DS_Store
+3 -6
View File
@@ -1,12 +1,9 @@
[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
-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
+4
View File
@@ -0,0 +1,4 @@
from core.auth.base import AuthModel
from core.auth.models import Role, User, UserRole
__all__ = ["AuthModel", "User", "Role", "UserRole"]
+8
View File
@@ -0,0 +1,8 @@
import sqlalchemy.orm as orm
from sqlmodel import SQLModel
registry = orm.registry()
class AuthModel(SQLModel, registry=registry):
"""Base class for Auth tables, isolated from clinical metadata."""
+60
View File
@@ -0,0 +1,60 @@
import sqlalchemy as sa
from sqlmodel import Field
from core.auth.base import AuthModel
class User(AuthModel, table=True):
__tablename__ = "user"
__table_args__ = (
sa.CheckConstraint(
"length(username) BETWEEN 3 AND 64 "
"AND username NOT GLOB '*[^a-z0-9._-]*'",
name="ck_user_username_format",
),
)
id: int | None = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
username: str = Field(
sa_column=sa.Column(sa.String(64), nullable=False, unique=True),
)
password_hash: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
)
activo: bool = Field(
default=True,
sa_column=sa.Column(sa.Boolean, nullable=False, default=True, server_default=sa.true()),
)
class Role(AuthModel, table=True):
__tablename__ = "role"
__table_args__ = (
sa.CheckConstraint("code IN ('ADMIN', 'CACU', 'CAMA', 'TEA')", name="ck_role_code_allowed"),
)
code: str = Field(sa_column=sa.Column(sa.String(8), primary_key=True))
class UserRole(AuthModel, table=True):
__tablename__ = "user_role"
user_id: int = Field(
sa_column=sa.Column(
sa.Integer,
sa.ForeignKey("user.id", ondelete="CASCADE"),
primary_key=True,
nullable=False,
),
)
role_code: str = Field(
sa_column=sa.Column(
sa.String(8),
sa.ForeignKey("role.code"),
primary_key=True,
nullable=False,
),
)
-80
View File
@@ -1,80 +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"],
}
# 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()}
+13
View File
@@ -0,0 +1,13 @@
import sqlalchemy.orm as orm
from sqlmodel import SQLModel
registry = orm.registry()
class CaCuModel(SQLModel, registry=registry):
"""Base class for every CaCu table.
Own SQLAlchemy registry/metadata so table names (e.g. NotaMedica) don't
collide with CaMa's identically-named tables now that both domains live
in the same Python package.
"""
@@ -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,59 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
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.Text, 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
+18
View File
@@ -0,0 +1,18 @@
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",
}
+63
View File
@@ -0,0 +1,63 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
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, es el que permite vincular estudios con pacientes
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.Text, 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(sa.LargeBinary),
)
bx_ocr_confianza: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
@@ -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,36 @@
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",
}
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
+102
View File
@@ -0,0 +1,102 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
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, es el que permite vincular estudios con pacientes
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.Text, 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(sa.LargeBinary),
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(sa.LargeBinary)
)
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)
)
+5
View File
@@ -0,0 +1,5 @@
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
-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)
-122
View File
@@ -1,122 +0,0 @@
"""CaCu's measures (`core.measures` evaluates them) and the follow-up status they stratify by."""
from datetime import date
from core import cacu
from core.measures import (
NO_BIOPSY,
NO_DATA,
Composition,
Duration,
Measure,
Proportion,
RiskBand,
age_group,
as_day,
desc,
)
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
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"])
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))),
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,))),
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_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
+15
View File
@@ -0,0 +1,15 @@
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
__all__ = [
"Paciente",
"OrdenesEstudio",
"CitologiaCervical",
"BiopsiaCervical",
"NotaMedica",
"BiometriaHematica",
]
+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
+121
View File
@@ -0,0 +1,121 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
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.Text, index=True, nullable=False),
description="DG1: identificador hospitalario obligatorio para vincular estudios con pacientes",
)
nm_id_hospital: str = Field(
sa_column=sa.Column(sa.Text, 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",
}
+76
View File
@@ -0,0 +1,76 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
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.Text, 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",
}
+48
View File
@@ -0,0 +1,48 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
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) — indice unico para lookups confiables
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.Text, unique=True, index=True, nullable=False),
)
pac_sexo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_fecha_nacimiento: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
pac_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", # descripción original decía Departamento — corregida
)
-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()}
+13
View File
@@ -0,0 +1,13 @@
import sqlalchemy.orm as orm
from sqlmodel import SQLModel
registry = orm.registry()
class CaMaModel(SQLModel, registry=registry):
"""Base class for every CaMa table.
Own SQLAlchemy registry/metadata so table names (e.g. NotaMedica) don't
collide with CaCu's identically-named tables now that both domains live
in the same Python package.
"""
@@ -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,59 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
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.Text, 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",
}
+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
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.Text, 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(sa.LargeBinary),
)
bx_ocr_confianza: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
+5
View File
@@ -0,0 +1,5 @@
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
-77
View File
@@ -1,77 +0,0 @@
"""CaMa's follow-up list (pure): the patients whose latest mammogram reported by the cut-off
is BI-RADS 4 to 6 and was taken within the window, with where her biopsy stands and how soon
she should be seen.
Status, from the biopsies that mammogram led to, reported by the cut-off:
- cancer: one found cancer (in situ or invasive);
- pending_biopsy: none reported;
- biopsy_no_result: the latest has no grade;
- benign_biopsy: otherwise.
Priority: high for a cancer, or a pending biopsy after a BI-RADS 5 or 6; medium for any other
pending biopsy or one without result; low otherwise."""
from datetime import date
from core import cama
from core.measures import as_day
WINDOWS = cama.FOLLOW_UP_WINDOWS
SORTS = ("-recent",)
DEFAULT_HORIZON = None
STATUS_SYSTEM = "cama-follow-up-status"
PROCEDURES = ("treatment",) # by kind (persistance.fhir: CaMa's procedure read)
REPORT_FACTS = {"mammography": "diagnosis_days"} # days from the mammogram to its diagnosis
URGENT = ["5", "6"] # BI-RADS whose pending biopsy is high priority
def _ranked(row: dict) -> tuple:
return as_day(row["exam_date"]), as_day(row["report_date"]), row["birads_rank"] or 0
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
"""From each reported mammogram and the biopsies it led to (`gold.cama_mammogram_biopsies`),
who is on the list, most recent mammogram first."""
latest: dict[str, dict] = {}
biopsies: dict[str, list[dict]] = {}
for row in rows:
exam, report = as_day(row["exam_date"]), as_day(row["report_date"])
if row["birads"] is None or report is None or not exam <= report <= cutoff:
continue
person = row["person_id"]
if person not in latest or _ranked(row) > _ranked(latest[person]):
latest[person] = row
found = as_day(row["biopsy_report_date"])
if found is not None and exam <= found <= cutoff:
biopsies.setdefault(row["mammogram_id"], []).append(row)
out = []
for person, row in latest.items():
if row["birads"] not in cama.BIRADS_4_TO_6 or not start <= as_day(row["exam_date"]):
continue
mine = biopsies.get(row["mammogram_id"], [])
shown = max(mine, key=lambda b: (as_day(b["biopsy_report_date"]), b["biopsy_id"]),
default=None) # fmt: skip
cancers = [as_day(b["biopsy_report_date"]) for b in mine if b["histology"] in cama.CANCER]
if cancers:
status, priority = "cancer", "high"
elif shown is None:
status = "pending_biopsy"
priority = "high" if row["birads"] in URGENT else "medium"
elif shown["histology"] is None:
status, priority = "biopsy_no_result", "medium"
else:
status, priority = "benign_biopsy", "low"
out.append({
"person_id": person, "birth_date": row["birth_date"], "status": status,
"priority": priority, "recent": as_day(row["exam_date"]),
"first_cancer": min(cancers, default=None),
}) # fmt: skip
return sorted(out, key=lambda r: (-r["recent"].toordinal(), r["person_id"]))
def status(row: dict, cutoff: date) -> None:
"""A patient's status exists only on the list."""
return None
def ordered(rows: list[dict], sort: str, risks: dict, horizon) -> list[dict]:
return rows
+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
+26
View File
@@ -0,0 +1,26 @@
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",
}
class GradoHistologicoMama(str, Enum):
BENIGNO = "BENIGNO"
CARCINOMA_IN_SITU = "CARCINOMA_IN_SITU"
CARCINOMA_INVASOR = "CARCINOMA_INVASOR"
DESCONOCIDO = "DESCONOCIDO"
+61
View File
@@ -0,0 +1,61 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
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.Text, 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(sa.LargeBinary),
)
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
+15
View File
@@ -0,0 +1,15 @@
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
__all__ = [
"Paciente",
"OrdenesEstudio",
"Mastografia",
"BiopsiaMama",
"NotaMedica",
"BiometriaHematica",
]
+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
+121
View File
@@ -0,0 +1,121 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
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.Text, index=True, nullable=False),
description="DG1: identificador hospitalario obligatorio para vincular estudios con pacientes",
)
nm_id_hospital: str = Field(
sa_column=sa.Column(sa.Text, 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
+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",
}
+76
View File
@@ -0,0 +1,76 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
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.Text, 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",
}
+48
View File
@@ -0,0 +1,48 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
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) — indice unico para lookups confiables
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.Text, unique=True, index=True, nullable=False),
)
pac_sexo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_fecha_nacimiento: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
pac_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", # descripción original decía Departamento — corregida
)
-188
View File
@@ -1,188 +0,0 @@
"""The platform's clinical catalog: every study, the events it is made of, its fields, and the
code systems their values come from. It is data (the YAML files beside this module) and
changes only by a reviewed commit; nothing ships that it doesn't name.
Everything that validates, stores or serves a clinical value reads it: the pydantic model of
each study (what a pipeline's target checks rows against), the long silver tables and their
wide views (dbt), and the FHIR conformance resources the API serves.
"""
from datetime import date
from functools import cache
from pathlib import Path
from typing import Annotated, Any, ClassVar, Literal
import yaml
from pydantic import BaseModel, ConfigDict, Field, create_model, model_validator
HERE = Path(__file__).parent
EventClass = Literal["order", "encounter", "sample", "report", "part"]
# `file`: a document or signal kept whole (an EEG); silver holds its content hash, the
# platform keeps the content once (persistance.files).
ValueType = Literal["code", "boolean", "number", "date", "text", "file"]
class System(BaseModel):
model_config = ConfigDict(extra="forbid")
url: str
title: str
external: bool = False # a standard system we name but don't publish
class Event(BaseModel):
model_config = ConfigDict(extra="forbid")
date: str # the field that dates it
parent: EventClass | None = None
class FieldDef(BaseModel):
model_config = ConfigDict(extra="forbid")
type: ValueType
event: EventClass
title: str
system: str | None = None
codes: dict[str, str] = {} # allowed code -> display; empty: any code of `system`
pattern: str | None = None
unit: str | None = None
required: bool = False
@model_validator(mode="after")
def _codes_have_a_system(self):
if self.type == "code" and self.system is None:
raise ValueError("a code field names its system")
if self.type != "code" and (self.codes or self.system):
raise ValueError("only code fields take a system and codes")
return self
class Study(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str
key: list[str] # fields that, with the person, identify one study instance
events: dict[EventClass, Event]
fields: dict[str, FieldDef]
@model_validator(mode="after")
def _consistent(self):
for name in self.key:
if name not in self.fields:
raise ValueError(f"key field {name} is not a field")
for cls, event in self.events.items():
if self.fields.get(event.date, None) is None or self.fields[event.date].type != "date":
raise ValueError(f"{cls}: its date {event.date} is not a date field")
if event.parent and event.parent not in self.events:
raise ValueError(f"{cls}: parent {event.parent} is not an event")
for name, f in self.fields.items():
if f.event not in self.events:
raise ValueError(f"{name}: event {f.event} is not one of the study's")
return self
def _load(name: str) -> dict:
return yaml.safe_load((HERE / f"{name}.yaml").read_text(encoding="utf-8"))
@cache
def systems() -> dict[str, System]:
return {k: System.model_validate(v) for k, v in _load("systems").items()}
@cache
def files() -> dict[str, list[str]]:
"""Each catalog file (a domain, or `common` to all) and the studies it defines."""
return {
path.stem: list(_load(path.stem))
for path in sorted(HERE.glob("*.yaml"))
if path.stem != "systems"
}
def of_domain(domain: str) -> list[str]:
"""The studies a domain serves: its own and the common ones."""
return [*files().get(domain, []), *files().get("common", [])]
@cache
def studies() -> dict[str, Study]:
"""Every study of every catalog file, by name (names are unique across files)."""
found: dict[str, Study] = {}
for path in sorted(HERE.glob("*.yaml")):
if path.stem == "systems":
continue
for name, spec in _load(path.stem).items():
if name in found:
raise ValueError(f"study {name} is defined twice")
study = Study.model_validate(spec)
unknown = {f.system for f in study.fields.values() if f.system} - set(systems())
if unknown:
raise ValueError(f"{name}: unknown systems {sorted(unknown)}")
found[name] = study
return found
class Record(BaseModel):
"""One row of a study, as a pipeline's target receives it."""
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
key: ClassVar[tuple[str, ...]] = ()
study: ClassVar[str] = ""
_TYPES: dict[str, Any] = {
"boolean": bool,
"number": float,
"date": date,
"text": str,
"file": str,
} # fmt: skip (a file field holds its content hash)
def _annotation(f: FieldDef) -> Any:
if f.type == "code" and f.codes:
kind: Any = Literal[tuple(f.codes)] # type: ignore[valid-type]
elif f.type == "code":
kind = Annotated[str, Field(pattern=f.pattern)] if f.pattern else str
else:
kind = _TYPES[f.type]
return kind if f.required else kind | None
@cache
def model(study: str) -> type[Record]:
"""The pydantic model a row of this study is checked against."""
spec = studies()[study]
fields = { # titled as the catalog names them (forms and review show the titles)
name: (_annotation(f), Field(... if f.required else None, title=f.title))
for name, f in spec.fields.items()
}
found = create_model(study, __base__=Record, **fields) # type: ignore[call-overload]
found.key = tuple(spec.key)
found.study = study
return found
def value_column(f: FieldDef) -> str:
"""The typed column of the long observation table a field's value is stored in."""
return {"boolean": "value_bool", "number": "value_num", "date": "value_date"}.get(
f.type, "value_text"
)
def dbt_vars() -> dict:
"""What dbt reads (`var('catalog')`): each study's key, events and typed fields."""
return {
name: {
"key": s.key,
"events": {c: e.model_dump() for c, e in s.events.items()},
"fields": {
f: {
"type": d.type,
"event": d.event,
"column": value_column(d),
"codes": list(d.codes),
}
for f, d in s.fields.items()
},
}
for name, s in studies().items()
}
-53
View File
@@ -1,53 +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}
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}
cervical_biopsy:
title: Biopsia cervical
key: [request_date]
events:
order: {date: request_date}
report: {date: report_date, parent: order}
fields:
request_date: {type: date, event: order, title: Fecha de solicitud, required: true}
cytology_sample_date: {type: date, event: order, title: Toma de la citología que la originó}
report_date: {type: date, event: report, title: Fecha de reporte}
histology:
type: code
event: report
title: Histología
system: who-cervical-histology
codes:
normal: Sin lesión
LSIL: Lesión intraepitelial escamosa de bajo grado (CIN 1)
HSIL: Lesión intraepitelial escamosa de alto grado (CIN 2-3)
CIS: Carcinoma in situ
carcinoma: Carcinoma invasor
-134
View File
@@ -1,134 +0,0 @@
# Breast cancer screening.
mammography:
title: Mastografía
key: [exam_date]
events:
sample: {date: exam_date}
report: {date: report_date, parent: sample}
fields:
exam_date: {type: date, event: sample, title: Fecha del estudio, required: true}
report_date: {type: date, event: report, title: Fecha de reporte}
adequacy:
type: code
event: report
title: Calidad de la imagen
system: adequacy
codes: {satisfactory: Satisfactoria, unsatisfactory: Insatisfactoria}
birads:
type: code
event: report
title: BI-RADS
system: bi-rads
codes:
'0': Incompleta, requiere estudios adicionales
'1': Negativa
'2': Hallazgos benignos
'3': Probablemente benigna
'4': Sospechosa
4A: Sospecha baja de malignidad
4B: Sospecha moderada de malignidad
4C: Sospecha alta de malignidad
'5': Altamente sugestiva de malignidad
'6': Malignidad confirmada por biopsia
breast_biopsy:
title: Biopsia de mama
key: [request_date, mammogram_exam_date]
events:
order: {date: request_date}
report: {date: report_date, parent: order}
fields:
request_date: {type: date, event: order, title: Fecha de solicitud, required: true}
mammogram_exam_date: {type: date, event: order, title: Mastografía que la originó}
report_date: {type: date, event: report, title: Fecha de reporte}
histology:
type: code
event: report
title: Histología
system: breast-histology
codes: {benign: Benigno, in_situ: In situ, invasive: Invasor}
histologic_type:
type: code
event: report
title: Tipo histológico (CIE-O-3)
system: icd-o-3
grade:
type: code
event: report
title: Grado histológico (Nottingham)
system: nottingham-grade
codes: {'1': Grado 1, '2': Grado 2, '3': Grado 3}
er:
type: code
event: report
title: Receptor de estrógeno
system: receptor-status
codes: &receptor {positive: Positivo, negative: Negativo}
pr:
type: code
event: report
title: Receptor de progesterona
system: receptor-status
codes: *receptor
her2:
type: code
event: report
title: HER2
system: receptor-status
codes: *receptor
ki67_pct: {type: number, event: report, title: Ki-67, unit: '%'}
size_mm: {type: number, event: report, title: Tamaño del tumor, unit: mm}
positive_nodes: {type: number, event: report, title: Ganglios linfáticos positivos}
stage:
type: code
event: report
title: Estadio clínico (AJCC)
system: ajcc-stage
codes:
'0': Estadio 0
I: Estadio I (sin subgrupo)
II: Estadio II (sin subgrupo)
III: Estadio III (sin subgrupo)
IA: Estadio IA
IB: Estadio IB
IIA: Estadio IIA
IIB: Estadio IIB
IIIA: Estadio IIIA
IIIB: Estadio IIIB
IIIC: Estadio IIIC
IV: Estadio IV
breast_treatment:
title: Tratamiento de cáncer de mama
key: [start_date, kind]
events:
encounter: {date: start_date}
fields:
start_date: {type: date, event: encounter, title: Fecha de inicio, required: true}
kind:
type: code
event: encounter
title: Tratamiento
system: breast-treatment
required: true
codes:
breast_conserving_surgery: Cirugía conservadora
mastectomy: Mastectomía
chemotherapy: Quimioterapia
radiotherapy: Radioterapia
hormone_therapy: Hormonoterapia
anti_her2: Terapia anti-HER2
breast_recurrence:
title: Recurrencia de cáncer de mama
key: [diagnosis_date]
events:
encounter: {date: diagnosis_date}
fields:
diagnosis_date: {type: date, event: encounter, title: Fecha de diagnóstico, required: true}
site:
type: code
event: encounter
title: Sitio de la recurrencia
system: breast-recurrence-site
codes: {local: Local, regional: Regional, distant: A distancia}
-36
View File
@@ -1,36 +0,0 @@
# Studies every domain shares.
clinical_note:
title: Nota médica
key: [note_date, specialty]
events:
encounter: {date: note_date}
fields:
note_date: {type: date, event: encounter, title: Fecha de la nota}
specialty:
type: code
event: encounter
title: Especialidad
system: specialty
codes:
colposcopy: Clínica de la mujer y colposcopia
oncology_surgery: Cirugía oncológica
medical_oncology: Oncología médica
radiation_oncology: Radio-oncología
family_medicine: Medicina familiar
pediatric_neurology: Neurología pediátrica
icd10:
type: code
event: encounter
title: Diagnóstico (CIE-10)
system: icd-10
pattern: '^[A-Z]\d{2}(\.\d{1,2})?$'
reason: {type: text, event: encounter, title: Motivo de consulta}
diagnosis_text: {type: text, event: encounter, title: Diagnóstico como se escribió}
death:
title: Defunción
key: []
events:
encounter: {date: death_date}
fields:
death_date: {type: date, event: encounter, title: Fecha de defunción, required: true}
-46
View File
@@ -1,46 +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)
bi-rads:
url: https://isssteleon.org/fhir/CodeSystem/bi-rads
title: BI-RADS
icd-10:
url: http://hl7.org/fhir/sid/icd-10
title: CIE-10
external: true
adequacy:
url: https://isssteleon.org/fhir/CodeSystem/adequacy
title: Calidad de la muestra
specialty:
url: https://isssteleon.org/fhir/CodeSystem/specialty
title: Especialidades
breast-histology:
url: https://isssteleon.org/fhir/CodeSystem/breast-histology
title: Histología de mama
ados2-module:
url: https://isssteleon.org/fhir/CodeSystem/ados2-module
title: Módulos del ADOS-2
icd-o-3:
url: http://terminology.hl7.org/CodeSystem/icd-o-3
title: CIE-O-3 (morfología)
external: true
nottingham-grade:
url: https://isssteleon.org/fhir/CodeSystem/nottingham-grade
title: Grado histológico de Nottingham
receptor-status:
url: https://isssteleon.org/fhir/CodeSystem/receptor-status
title: Estado de receptores hormonales y HER2
ajcc-stage:
url: https://isssteleon.org/fhir/CodeSystem/ajcc-stage
title: Estadio clínico AJCC (grupo)
breast-treatment:
url: https://isssteleon.org/fhir/CodeSystem/breast-treatment
title: Tratamientos de cáncer de mama
breast-recurrence-site:
url: https://isssteleon.org/fhir/CodeSystem/breast-recurrence-site
title: Sitio de la recurrencia de cáncer de mama
-60
View File
@@ -1,60 +0,0 @@
# Autism (TEA) screening: M-CHAT, ADOS-2, EEG; the neurology note that confirms the diagnosis
# is the common clinical note (specialty pediatric_neurology).
mchat:
title: M-CHAT-R/F
key: [screening_date]
events:
encounter: {date: screening_date}
fields:
screening_date: {type: date, event: encounter, title: Fecha del M-CHAT, required: true}
score: {type: number, event: encounter, title: Puntaje total (0 a 20)}
ados2:
title: ADOS-2
key: [evaluation_date]
events:
encounter: {date: evaluation_date}
fields:
evaluation_date: {type: date, event: encounter, title: Fecha de evaluación, required: true}
module:
type: code
event: encounter
title: Módulo
system: ados2-module
codes: {toddler: Módulo para niños pequeños, module_1: Módulo 1, module_2: Módulo 2, module_3: Módulo 3}
# The 22 items by what they observe (the same meaning in every module), each 0 to 3.
vocalization_directed: {type: number, event: encounter, title: Frecuencia de la vocalización espontánea dirigida a otros}
pointing: {type: number, event: encounter, title: Señalar}
gestures: {type: number, event: encounter, title: Gestos}
unusual_eye_contact: {type: number, event: encounter, title: Contacto visual inusual}
facial_expressions: {type: number, event: encounter, title: Expresiones faciales dirigidas a otros}
gaze_integration: {type: number, event: encounter, title: Integración de la mirada y otras conductas}
shared_enjoyment: {type: number, event: encounter, title: Disfrute compartido durante la interacción}
response_to_name: {type: number, event: encounter, title: Respuesta al nombre}
ignoring: {type: number, event: encounter, title: Ignorar}
requesting: {type: number, event: encounter, title: Pedir}
showing: {type: number, event: encounter, title: Mostrar}
joint_attention_initiation: {type: number, event: encounter, title: Iniciación espontánea de la atención conjunta}
joint_attention_response: {type: number, event: encounter, title: Respuesta a la atención conjunta}
social_overtures_quality: {type: number, event: encounter, title: Características de las iniciaciones sociales}
social_overtures_caregiver: {type: number, event: encounter, title: Cantidad de acercamientos sociales al cuidador}
reciprocal_communication: {type: number, event: encounter, title: Cantidad de comunicación social recíproca}
rapport_quality: {type: number, event: encounter, title: Calidad general de la relación}
intonation: {type: number, event: encounter, title: Entonación de las vocalizaciones o verbalizaciones}
stereotyped_language: {type: number, event: encounter, title: Uso estereotipado o idiosincrásico de palabras o frases}
unusual_sensory_interest: {type: number, event: encounter, title: Interés sensorial inusual}
hand_finger_mannerisms: {type: number, event: encounter, title: Manierismos de manos y dedos}
repetitive_interests: {type: number, event: encounter, title: Intereses inusualmente repetitivos}
social_affect_total: {type: number, event: encounter, title: Total de afectación social (impreso)}
restricted_repetitive_total: {type: number, event: encounter, title: Total de comportamiento restringido y repetitivo (impreso)}
overall_total: {type: number, event: encounter, title: Puntuación total global (impresa)}
eeg:
title: Electroencefalograma
key: [study_date]
events:
sample: {date: study_date}
fields:
study_date: {type: date, event: sample, title: Fecha del estudio, required: true}
lab_record_id: {type: text, event: sample, title: Registro del laboratorio}
edf: {type: file, event: sample, title: Registro EDF}
-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 {}
-514
View File
@@ -1,514 +0,0 @@
"""Platform rows as FHIR R4B resources (pure, no IO), and the conformance resources that
declare what ours are: the local code systems, our extensions and our search parameters.
Every mapper builds a `fhir.resources.R4B` model, so a resource that breaks FHIR's structure
fails here, before it is served. Clinical resources other than Patient are found by search
only; their ids are stable (a UUID of their natural key), not addresses.
"""
import uuid
from collections.abc import Iterable
from datetime import UTC, date, datetime
from fhir.resources.R4B.codesystem import CodeSystem
from fhir.resources.R4B.condition import Condition
from fhir.resources.R4B.diagnosticreport import DiagnosticReport
from fhir.resources.R4B.encounter import Encounter
from fhir.resources.R4B.measure import Measure
from fhir.resources.R4B.observation import Observation
from fhir.resources.R4B.patient import Patient
from fhir.resources.R4B.procedure import Procedure
from fhir.resources.R4B.resource import Resource
from fhir.resources.R4B.riskassessment import RiskAssessment
from fhir.resources.R4B.searchparameter import SearchParameter
from fhir.resources.R4B.structuredefinition import StructureDefinition
from core import catalog, models
FHIR_VERSION = "4.3.0"
BASE = "https://isssteleon.org/fhir"
EXTENSION = f"{BASE}/StructureDefinition/"
CODES = f"{BASE}/CodeSystem/"
ICD10 = "http://hl7.org/fhir/sid/icd-10"
UCUM = "http://unitsofmeasure.org"
_IDS = uuid.uuid5(uuid.NAMESPACE_URL, BASE)
# Local code systems: code -> display (Spanish, as the screens show them).
CODE_SYSTEMS: dict[str, tuple[str, dict[str, str]]] = {
"cacu-procedure": ("Procedimientos de CaCu", {
"colposcopy": "Colposcopia", "treatment": "Tratamiento",
}),
"cacu-follow-up-status": ("Estatus de seguimiento", {
"case": "Caso (cáncer)", "pre_colposcopy": "Pre colposcopia",
"post_colposcopy": "Post colposcopia", "post_treatment": "Post tratamiento",
}),
"cama-follow-up-status": ("Estatus de seguimiento", {
"cancer": "Diagnóstico confirmado", "pending_biopsy": "Pendiente de biopsia",
"biopsy_no_result": "Biopsia sin resultado", "benign_biopsy": "Biopsia benigna",
}),
"tea-follow-up-status": ("Estatus de seguimiento", {
"mchat_only": "Solo M-CHAT", "psychology": "Hasta evaluación psicológica",
"neuropediatrics": "Hasta evaluación neuropediátrica", "eeg": "Con EEG",
}),
"tea-case": ("Estado del caso", {
"confirmed": "Diagnóstico confirmado", "in_process": "En proceso",
"not_confirmed": "Sin TEA",
}),
"tea-eeg-status": ("Estatus de EEG", {
"normal": "Normal", "abnormal": "Anormal", "no_valid_eeg": "Sin EEG válido",
}),
# an EEG metric outside its age band: `<metric>:above` or `<metric>:below`
"tea-eeg-alteration": ("Alteración del EEG", {}),
"follow-up-priority": ("Prioridad de seguimiento", {
"high": "Alta", "medium": "Media", "low": "Baja",
}),
"measure-stratifier": ("Estratos de indicadores", {
"category": "Categoría", "age_group": "Grupo de edad",
"follow_up_status": "Estatus de seguimiento", "result": "Citología de alto grado",
"birads": "BI-RADS de la mastografía",
}),
"risk-model": ("Modelos de riesgo", {}), # open: a model's name is its code
} # fmt: skip
def _catalog_systems() -> dict[str, tuple[str, dict[str, str]]]:
"""The catalog's own code systems, with every code some field allows."""
found: dict[str, tuple[str, dict[str, str]]] = {}
for name, system in catalog.systems().items():
if not system.external:
codes = {c: d for s in catalog.studies().values() for f in s.fields.values()
if f.system == name for c, d in f.codes.items()} # fmt: skip
found[name] = (system.title, codes)
return found
CODE_SYSTEMS |= _catalog_systems()
CODE_SYSTEMS["cama-procedure"] = ("Procedimientos de CaMa", CODE_SYSTEMS["breast-treatment"][1])
# What the catalog names: its studies, and every field as `<study>.<field>`.
CODE_SYSTEMS["study"] = ("Estudios", {n: s.title for n, s in catalog.studies().items()})
CODE_SYSTEMS["catalog-field"] = ("Campos de los estudios", {
f"{n}.{f}": d.title for n, s in catalog.studies().items() for f, d in s.fields.items()
}) # fmt: skip
# 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"]),
# a clinical scenario of the model's report the person falls in (its curves)
"escenario-clinico": ("string", ["RiskAssessment"]),
# a child on TEA's list: her age group, case, EEG and scores
"tea-age-group": ("string", ["Patient"]),
"tea-case": ("Coding", ["Patient"]),
"tea-eeg-status": ("Coding", ["Patient"]),
"tea-eeg-alteration": ("Coding", ["Patient"]),
"tea-last-eeg": ("date", ["Patient"]),
"mchat-score": ("integer", ["Patient"]),
"ados2-css": ("integer", ["Patient"]),
} # fmt: skip
def _name(code: str) -> str:
"""A conformance resource's computable name (CamelCase)."""
return "".join(part.capitalize() for part in code.replace("_", "-").split("-"))
def _id(*key) -> str:
return str(uuid.uuid5(_IDS, "|".join(str(k) for k in key)))
def _day(value) -> str | None:
if value is None:
return None
return value.isoformat()[:10] if isinstance(value, date) else str(value)[:10]
def _instant(value) -> str | None:
"""A stored moment as an instant; one stored without an offset is UTC."""
if value is None:
return None
found = value if isinstance(value, datetime) else datetime.fromisoformat(str(value))
return (found if found.tzinfo else found.replace(tzinfo=UTC)).isoformat()
def coding(system: str, code: str) -> dict:
display = CODE_SYSTEMS[system][1].get(code) if system in CODE_SYSTEMS else None
return {"system": CODES + system, "code": code, **({"display": display} if display else {})}
def concept(system: str, code: str) -> dict:
found = coding(system, code)
return {"coding": [found], "text": found.get("display", code)}
def ext(name: str, value_type: str, value) -> dict:
return {"url": EXTENSION + name, f"value{value_type[0].upper()}{value_type[1:]}": value}
def subject(person_id: str) -> dict:
return {"reference": f"Patient/{person_id}"}
# --- clinical resources ----------------------------------------------------------------
def patient(row: dict, status_system: str | None = None) -> Patient:
"""A person: what her records agree on, her names and identifiers, the ids she
replaced; on a follow-up list, her status there (`status_system`) and priority."""
found: dict = {"resourceType": "Patient", "id": row["person_id"]}
if row.get("sex"):
found["gender"] = row["sex"]
if row.get("birth_date"):
found["birthDate"] = _day(row["birth_date"])
if row.get("death_date"):
found["deceasedDateTime"] = _day(row["death_date"])
if row.get("status") and status_system:
found["extension"] = [ext("follow-up-status", "Coding",
coding(status_system, row["status"]))] # fmt: skip
if row.get("priority"):
priority = coding("follow-up-priority", row["priority"])
found["extension"].append(ext("follow-up-priority", "Coding", priority))
found.setdefault("extension", []).extend(_tea_listed(row))
if not found["extension"]:
del found["extension"]
if row.get("names"):
found["name"] = [{"text": n} for n in row["names"]]
if row.get("identifiers"):
found["identifier"] = [{"system": s, "value": v} for s, v in row["identifiers"]]
if row.get("replaces"):
found["link"] = [{"other": {"reference": f"Patient/{old}"}, "type": "replaces"}
for old in row["replaces"]] # fmt: skip
return Patient.model_validate(found)
def _tea_listed(row: dict) -> list[dict]:
"""What TEA's list shows of a child, when she is on it (core.tea.follow_up)."""
found = []
if row.get("age_group"):
found.append(ext("tea-age-group", "string", row["age_group"]))
for key, system in (("case", "tea-case"), ("eeg_status", "tea-eeg-status")):
if row.get(key):
found.append(ext(system, "Coding", coding(system, row[key])))
for altered in row.get("alterations") or []:
found.append(ext("tea-eeg-alteration", "Coding", coding("tea-eeg-alteration", altered)))
if row.get("last_eeg"):
found.append(ext("tea-last-eeg", "date", _day(row["last_eeg"])))
for key, name in (("mchat_score", "mchat-score"), ("ados2_css", "ados2-css")):
if row.get(key) is not None:
found.append(ext(name, "integer", int(row[key])))
return found
def replaced_patient(person_id: str, replaced_by: str) -> Patient:
"""A person a review merged into another: no longer active, pointing at who replaced
her, so her id keeps resolving."""
return Patient.model_validate({
"resourceType": "Patient", "id": person_id, "active": False,
"link": [{"other": {"reference": f"Patient/{replaced_by}"}, "type": "replaced-by"}],
}) # fmt: skip
def _value(f: catalog.FieldDef, value) -> dict:
"""A field's value as the Observation value of its type."""
if f.type == "code":
system = catalog.systems()[f.system]
if system.external:
return {"valueCodeableConcept": {"coding": [{"system": system.url, "code": value}],
"text": value}} # fmt: skip
return {"valueCodeableConcept": concept(f.system, value)}
if f.type == "boolean":
return {"valueBoolean": bool(value)}
if f.type == "number":
return {"valueQuantity": {"value": value, **({"unit": f.unit} if f.unit else {})}}
if f.type == "date":
return {"valueDateTime": _day(value)}
return {"valueString": str(value)}
def known(study: str, row: dict, cutoff) -> dict:
"""A study instance as the platform knew it by the end of `cutoff`: the fields of an
event that has no date yet, or a later one, are not known."""
spec = catalog.studies()[study]
out = dict(row)
for cls, event in spec.events.items():
day = _day(row.get(event.date))
if event.parent is not None and (day is None or day > _day(cutoff)):
for name, f in spec.fields.items():
if f.event == cls:
out[name] = None
return out
def instance(study: str, row: dict, report_extensions: Iterable[dict] = ()) -> list[Resource]:
"""One study instance (a row of `silver.<study>`) as FHIR, from the catalog: an
Observation per field that is not an event's date, and, when the study has a report,
the DiagnosticReport that gathers them."""
spec = catalog.studies()[study]
person = row["person_id"]
key = [_day(row[k]) if spec.fields[k].type == "date" else row[k] for k in spec.key]
dates = {e.date for e in spec.events.values()}
root = next(e for e in spec.events.values() if e.parent is None)
effective = _day(row.get(root.date))
container = _id(study, person, *key) # its report, or the encounter its notes are of
visit = "report" not in spec.events
observations = []
for name, f in spec.fields.items():
if name in dates or row.get(name) is None or f.type == "file":
continue
observations.append(Observation.model_validate({
"resourceType": "Observation",
"id": _id(study, name, person, *key),
"status": "final",
"code": concept("catalog-field", f"{study}.{name}"),
"subject": subject(person),
**({"encounter": {"reference": f"Encounter/{container}"}} if visit else {}),
**({"effectiveDateTime": effective} if effective else {}),
**_value(f, row[name]),
})) # fmt: skip
if visit: # a study without a report (a consultation): the encounter its values are of
if not observations:
return []
encounter = Encounter.model_validate({
"resourceType": "Encounter", "id": container, "status": "finished",
"class": {"system": "http://terminology.hl7.org/CodeSystem/v3-ActCode",
"code": "AMB"},
"type": [concept("study", study)],
"subject": subject(person),
**({"period": {"start": effective}} if effective else {}),
}) # fmt: skip
return [encounter, *observations]
reported = _day(row.get(spec.events["report"].date))
extensions = ([ext("report-date", "date", reported)] if reported else []) + list(
report_extensions
)
report = DiagnosticReport.model_validate({
"resourceType": "DiagnosticReport",
"id": container,
"status": "final" if reported else "registered",
"code": concept("study", study),
"subject": subject(person),
**({"effectiveDateTime": effective} if effective else {}),
**({"extension": extensions} if extensions else {}),
"result": [{"reference": f"Observation/{o.id}"} for o in observations] or None,
}) # fmt: skip
return [report, *observations]
def condition(row: dict) -> Condition:
"""What a clinical note diagnosed (`silver.clinical_note`), by ICD-10 or as written; or
a study of the catalog that is a diagnosis (`study`: a breast recurrence), by its name
and its coded field (`code`: where it recurred)."""
person, day = row["person_id"], _day(row["note_date"])
code: dict = {"text": row.get("diagnosis_text") or row.get("icd10")}
if row.get("icd10"):
code["coding"] = [{"system": ICD10, "code": row["icd10"]}]
if study := row.get("study"):
code = concept("study", study)
system = next((f.system for f in catalog.studies()[study].fields.values()
if f.type == "code"), None) # fmt: skip
if system and row.get("code"):
where = coding(system, row["code"])
code["coding"].append(where)
code["text"] += f" ({where.get('display', row['code']).lower()})"
found: dict = {
"resourceType": "Condition",
"id": _id("condition", person, day, row.get("specialty") or study),
"category": [{"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/condition-category",
"code": "encounter-diagnosis"}]}],
"code": code,
"subject": subject(person),
"recordedDate": day,
} # fmt: skip
if row.get("reason"):
found["note"] = [{"text": row["reason"]}]
return Condition.model_validate(found)
def procedure(row: dict, domain: str = "cacu") -> Procedure:
"""A procedure the timeline inferred (`gold.<domain>_events`; CaCu: colposcopy,
treatment; CaMa: each treatment by its kind), coded in `<domain>-procedure`."""
person, day = row["person_id"], _day(row["date"])
return Procedure.model_validate({
"resourceType": "Procedure",
"id": _id("procedure", row["type"], person, day),
"status": "completed",
"code": concept(f"{domain}-procedure", row["type"]),
"subject": subject(person),
"performedDateTime": day,
}) # fmt: skip
SCENARIO_SEPARATOR = " | " # as models.survival joins them
def risk_assessment(row: dict, horizons: Iterable[dict]) -> RiskAssessment:
"""A model's risk for one person at her index date (`gold.cacu_risk`): one prediction
per horizon, in years, with its 95% interval; and the clinical scenarios of the model's
report she falls in (an extension each), for her record to draw their curves."""
predictions = []
for h in sorted(horizons, key=lambda h: h["horizon_years"]):
bounds = (("ic-bajo", "ci_low"), ("ic-alto", "ci_high"))
interval = [ext(name, "decimal", h[key]) for name, key in bounds
if h.get(key) is not None] # fmt: skip
predictions.append({
"probabilityDecimal": h["probability"],
"whenRange": {"high": {"value": h["horizon_years"], "unit": "a", "system": UCUM,
"code": "a"}},
**({"extension": interval} if interval else {}),
}) # fmt: skip
model = row["model"]
return RiskAssessment.model_validate({
"resourceType": "RiskAssessment",
"id": _id("risk", model, row["version"], row["person_id"], _day(row["index_date"])),
"meta": {"lastUpdated": _instant(row["scored_at"])},
"status": "final",
"method": {"coding": [{"system": CODES + "risk-model", "code": model,
"display": models.title(model)}],
"text": f"{models.title(model)} v{row['version']}"},
"subject": subject(row["person_id"]),
"occurrenceDateTime": _day(row["index_date"]),
"prediction": predictions,
**({"extension": [ext("escenario-clinico", "string", name) for name in scenarios]}
if (scenarios := [n for n in (row.get("scenarios") or "").split(SCENARIO_SEPARATOR)
if n]) else {}),
}) # fmt: skip
SCORING = {"proportion": "proportion", "continuous-variable": "continuous-variable",
"composition": "cohort"} # fmt: skip
def measure_id(code: str) -> str:
"""A measure's FHIR id (ids allow no underscore)."""
return code.lower().replace("_", "-")
def measure_url(code: str) -> str:
return f"{BASE}/Measure/{code}"
# The populations each kind of measure counts (core.measures emits exactly these).
POPULATIONS = {"proportion": ["initial-population", "denominator", "numerator"],
"continuous-variable": ["initial-population", "measure-observation"],
"composition": ["initial-population", "measure-observation"]} # fmt: skip
POPULATION = "http://terminology.hl7.org/CodeSystem/measure-population"
def stratifiers(m) -> list[str]:
"""A measure's strata: a composition's categories first, then its declared strata."""
first = ["category"] if m.rule.kind == "composition" else []
return first + [name for name, _ in getattr(m.rule, "strata", ())]
def stratifier_code(name: str) -> dict:
return concept("measure-stratifier", name)
def measure(m, domain: str) -> Measure:
"""A measure definition (`core.measures.Measure`): how it is computed is Core's code,
which `criteria` points to."""
criteria = {"language": "text/x-python",
"expression": f"core.{domain}.measures.MEASURES['{m.id}']"} # fmt: skip
group: dict = {
"id": m.group,
"population": [{"code": {"coding": [{"system": POPULATION, "code": c}]},
"criteria": criteria} for c in POPULATIONS[m.rule.kind]],
} # fmt: skip
if strata := stratifiers(m):
group["stratifier"] = [{"id": s, "code": stratifier_code(s), "criteria": criteria}
for s in strata] # fmt: skip
found: dict = {
"resourceType": "Measure",
"id": measure_id(m.id),
"url": measure_url(m.id),
"version": m.version,
"name": m.id,
"title": m.title,
"status": "active",
"scoring": {"coding": [{"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": SCORING[m.rule.kind]}]},
"extension": [ext("period-type", "code", p) for p in m.periods],
"group": [group],
} # fmt: skip
if m.improvement:
found["improvementNotation"] = {"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": m.improvement}]} # fmt: skip
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]] = {
"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)
-509
View File
@@ -1,509 +0,0 @@
"""The measure engine: what a domain's measure counts, evaluated per period over the rows gold
gives (pure, no IO), and the FHIR R4B MeasureReport each evaluation is served as. Each domain
declares its measures in `core.<domain>.measures` (`MEASURES`).
Three kinds, as FHIR scores them:
- proportion: patients in the denominator and, of them, in the numerator; with a Wilson
95% interval;
- composition: patients split by the category of their latest valid fact in the period;
- continuous variable: days per unit, summarized by the median and inclusive quartiles. A
unit still within its horizon without an end isn't measured yet, so it is left out.
Rows are known from `known_at`; an evaluation `as_of` a moment uses only rows known by then
(all of them by default). Durations count to the event cut-off, `as_of`'s day by default.
"""
import functools
import math
import statistics
from collections import defaultdict
from collections.abc import Callable, Iterable
from dataclasses import dataclass, field
from datetime import UTC, date, datetime
from typing import ClassVar
from fhir.resources.R4B.measurereport import MeasureReport
from core.fhir import EXTENSION, measure_url, stratifier_code
POPULATION = "http://terminology.hl7.org/CodeSystem/measure-population"
IMPROVEMENT = "http://terminology.hl7.org/CodeSystem/measure-improvement-notation"
Z = 1.959963984540054
NO_DATA = "no_data"
NO_BIOPSY = "no_biopsy"
@dataclass(frozen=True)
class Period:
start: date
end: date # exclusive
@classmethod
def parse(cls, text: str) -> "Period":
"""A semester (`2025-S1`) or a month (`2025-03`)."""
year, part = text.split("-")
if part.startswith("S"):
first = 1 if part == "S1" else 7
return cls(
date(int(year), first, 1),
date(int(year), 7, 1) if first == 1 else date(int(year) + 1, 1, 1),
)
month = int(part)
return cls(date(int(year), month, 1),
date(int(year) + month // 12, month % 12 + 1, 1)) # fmt: skip
@functools.cached_property
def _iso(self) -> tuple[str, str]:
return self.start.isoformat(), self.end.isoformat()
def __contains__(self, day) -> bool:
if isinstance(day, str): # ISO days sort as the days they name
start, end = self._iso
return start <= day[:10] < end
return day is not None and self.start <= as_day(day) < self.end
def as_day(value) -> date | None:
"""A day, from a date, a datetime or ISO text."""
if value is None or isinstance(value, date) and not isinstance(value, datetime):
return value
if isinstance(value, datetime):
return value.date()
return _iso_day(str(value)[:10])
@functools.lru_cache(maxsize=65536)
def _iso_day(text: str) -> date:
"""Parsed once per day: every period scans every row."""
return date.fromisoformat(text)
def _moment(value) -> datetime | None:
"""A moment; one stored without an offset is UTC (how the platform stores them)."""
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)
def age_group(birth, at: date, groups: list[tuple[int, int]]) -> str:
"""`low-high` of the group her age at `at` falls in, or below/above them all."""
birth = as_day(birth)
if birth is None:
return NO_DATA
age = at.year - birth.year - ((at.month, at.day) < (birth.month, birth.day))
for low, high in groups:
if low <= age <= high:
return f"{low}-{high}"
lowest, highest = groups[0][0], groups[-1][1]
return f"<{lowest}" if age < lowest else f"{highest + 1}+"
# A stratum: its name and the value a row takes in a period.
Stratum = tuple[str, Callable[[dict, "Period"], str]]
@dataclass(frozen=True)
class Result:
populations: dict[str, int]
score: float | None = None
score_extensions: dict[str, float] = field(default_factory=dict)
unit: str | None = None
strata: dict[str, dict[str, dict[str, int]]] = field(default_factory=dict)
# A stratum crossed with the category: (its name, "category") -> (value, category) ->
# counts (a composition by clinical scenario and result, say).
crossed: dict[tuple[str, str], dict[tuple[str, str], dict[str, int]]] = field(
default_factory=dict
)
def wilson(k: int, n: int) -> tuple[float, float]:
p = k / n
centre, half = p + Z * Z / (2 * n), Z * math.sqrt(p * (1 - p) / n + Z * Z / (4 * n * n))
low, high = (centre - half) / (1 + Z * Z / n), (centre + half) / (1 + Z * Z / n)
return round(max(low, 0.0), 12), round(min(high, 1.0), 12)
@dataclass(frozen=True)
class Proportion:
"""Units with a row dated in the period that meets `denominator` and, of them, those
with such a row that also meets `numerator`; with a Wilson 95% interval."""
numerator: Callable[[dict], bool]
strata: tuple[Stratum, ...] = ()
denominator: Callable[[dict], bool] = lambda row: True
unit: str = "person_id"
date: str = "sample_date"
kind: str = "proportion"
# Reads only the rows dated in the period (evaluate_periods hands it just those).
dated_only: ClassVar[bool] = True
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
mine = [r for r in rows if r[self.date] in period and self.denominator(r)]
den = {r[self.unit]: r for r in mine}
num = {r[self.unit] for r in mine if self.numerator(r)}
found = {"initial-population": len(den), "denominator": len(den), "numerator": len(num)}
strata = {}
for name, stratum in self.strata:
values: dict[str, dict[str, int]] = {}
for unit, row in den.items():
cell = values.setdefault(
stratum(row, period),
{"initial-population": 0, "denominator": 0, "numerator": 0},
)
cell["initial-population"] += 1
cell["denominator"] += 1
cell["numerator"] += unit in num
strata[name] = values
if not den:
return Result(found, strata=strata)
low, high = wilson(len(num), len(den))
return Result(found, len(num) / len(den), {"ic-bajo": low, "ic-alto": high}, strata=strata)
def desc(value) -> tuple:
"""A sort key on which a value ranks above a missing one."""
return (value is not None, value)
@dataclass(frozen=True)
class Composition:
"""Units by the category of one row each: of a unit's rows dated in the period (that meet
`where`), the one `order` ranks highest. Only units whose chosen row is `admit`ted count.
The chosen row's `category` is the first stratifier; `strata` add others."""
order: Callable[[dict], tuple]
category: Callable[[dict], str]
admit: Callable[[dict], bool] = lambda row: True
where: Callable[[dict], bool] = lambda row: True
strata: tuple[Stratum, ...] = ()
unit: str = "person_id"
date: str = "sample_date"
kind: str = "composition"
# Reads only the rows dated in the period (evaluate_periods hands it just those).
dated_only: ClassVar[bool] = True
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
chosen: dict[str, dict] = {}
for row in rows:
if row[self.date] in period and self.where(row):
unit = row[self.unit]
if unit not in chosen or self.order(row) > self.order(chosen[unit]):
chosen[unit] = row
chosen = {u: r for u, r in chosen.items() if self.admit(r)}
strata: dict[str, dict[str, dict[str, int]]] = {}
for name, stratum in (("category", lambda row, p: self.category(row)), *self.strata):
values: dict[str, dict[str, int]] = {}
for row in chosen.values():
value = stratum(row, period)
values.setdefault(value, {"initial-population": 0})["initial-population"] += 1
strata[name] = values
crossed: dict[tuple[str, str], dict[tuple[str, str], dict[str, int]]] = {}
for name, stratum in self.strata: # each also by category
pairs: dict[tuple[str, str], dict[str, int]] = {}
for row in chosen.values():
key = (stratum(row, period), self.category(row))
pairs.setdefault(key, {"initial-population": 0})["initial-population"] += 1
crossed[(name, "category")] = pairs
n = len(chosen)
return Result({"initial-population": n, "measure-observation": n}, strata=strata,
crossed=crossed) # fmt: skip
@dataclass(frozen=True)
class Duration:
"""Days from `start` to `end` per unit (`value`), within `horizon` days. A unit whose
interval `ended` (default: has an `end`) without a value, like a sample reported
unsatisfactory, is in the initial population but not measured."""
value: str
end: str
start: str
horizon: int
units: Callable[[dict], bool] = lambda row: True
ended: str | None = None
unit: str = "sample_id"
date: str = "sample_date"
kind: str = "continuous-variable"
# Keeps each unit's last row, then reads only those dated in the period.
dated_only: ClassVar[bool] = True
one_per_unit: ClassVar[bool] = True
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
measured, initial = [], 0
for row in {r[self.unit]: r for r in rows}.values():
if row[self.date] not in period or not self.units(row):
continue
end = as_day(row.get(self.end))
has = row.get(self.value) is not None and end is not None and end <= cutoff
if has:
measured.append(float(row[self.value]))
stop = as_day(row.get(self.ended)) if self.ended else None
done = has or (stop is not None and stop <= cutoff)
pending = not done and (cutoff - as_day(row[self.start])).days < self.horizon
initial += not pending
found = {"initial-population": initial, "measure-observation": len(measured)}
if not measured:
return Result(found)
if len(measured) == 1:
q1 = median = q3 = measured[0]
else:
q1, median, q3 = statistics.quantiles(measured, n=4, method="inclusive")
return Result(found, median, {"q1": q1, "q3": q3}, unit="d")
@dataclass(frozen=True)
class RiskBand:
"""Patients indexed in the period, by the band their risk falls in (NO_DATA unscored):
`bands` are (name, upper cut), the last one's cut None."""
bands: tuple[tuple[str, float | None], ...]
kind: str = "composition"
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
bands: dict[str, dict[str, int]] = {}
mine = [r for r in rows if r["index_date"] in period]
for row in mine:
band = NO_DATA
if (p := row.get("probability")) is not None:
band = next(name for name, cut in self.bands if cut is None or p < cut)
bands.setdefault(band, {"initial-population": 0})["initial-population"] += 1
n = len(mine)
return Result({"initial-population": n, "measure-observation": n},
strata={"category": bands}) # fmt: skip
@dataclass(frozen=True)
class AtEnd:
"""The units on the books at a period's end: entered (`entry`) before it ended and not
gone (`exit`) before it began. Each is in the latest of `states` (name, date column, in
order) it reached before the end."""
entry: str
exit: str
states: tuple[tuple[str, str], ...]
unit: str = "person_id"
def units(self, rows: list[dict], period: Period) -> dict[str, tuple[dict, str]]:
found = {}
for row in rows:
entry, gone = as_day(row.get(self.entry)), as_day(row.get(self.exit))
if entry is None or entry >= period.end or (gone is not None and gone < period.start):
continue
reached = [n for n, c in self.states
if (d := as_day(row.get(c))) is not None and d < period.end] # fmt: skip
if reached:
found[row[self.unit]] = (row, reached[-1])
return found
def reached(row: dict, column: str, period: Period) -> bool:
"""A date reached by the period's end."""
day = as_day(row.get(column))
return day is not None and day < period.end
@dataclass(frozen=True)
class StatusProportion:
"""Of the units on the books at the end (`population`) that meet `denominator`, those
that meet `numerator`; both see the unit's row, its state and the period. Strata count
every unit on the books, so a stratum with none in the denominator still shows."""
population: AtEnd
denominator: Callable[[dict, str, Period], bool]
numerator: Callable[[dict, str, Period], bool]
strata: tuple[Stratum, ...] = ()
kind: str = "proportion"
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
units = self.population.units(rows, period)
den = {u for u, (r, s) in units.items() if self.denominator(r, s, period)}
num = {u for u in den if self.numerator(*units[u], period)}
found = {"initial-population": len(den), "denominator": len(den), "numerator": len(num)}
strata = {}
for name, stratum in self.strata:
values: dict[str, dict[str, int]] = {}
for unit, (row, _) in units.items():
cell = values.setdefault(stratum(row, period), {
"initial-population": 0, "denominator": 0, "numerator": 0}) # fmt: skip
cell["initial-population"] += unit in den
cell["denominator"] += unit in den
cell["numerator"] += unit in num
strata[name] = values
if not den:
return Result(found, strata=strata)
low, high = wilson(len(num), len(den))
return Result(found, len(num) / len(den), {"ic-bajo": low, "ic-alto": high}, strata=strata)
@dataclass(frozen=True)
class StatusComposition:
"""The units on the books at the end, by their state; only `admit`ted states count."""
population: AtEnd
admit: Callable[[str], bool] = lambda state: True
kind: str = "composition"
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
states = [s for _, s in self.population.units(rows, period).values() if self.admit(s)]
categories: dict[str, dict[str, int]] = {}
for state in states:
categories.setdefault(state, {"initial-population": 0})["initial-population"] += 1
n = len(states)
return Result({"initial-population": n, "measure-observation": n},
strata={"category": categories}) # fmt: skip
@dataclass(frozen=True)
class StatusDuration:
"""Days (`value`) per unit on the books at the end, for those whose interval ended
(`end`) before the period's end and by the cut-off; every unit on the books is in the
initial population."""
population: AtEnd
value: str
end: str
kind: str = "continuous-variable"
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
units = self.population.units(rows, period)
measured = [float(r[self.value]) for r, _ in units.values()
if r.get(self.value) is not None and reached(r, self.end, period)
and as_day(r[self.end]) <= cutoff] # fmt: skip
found = {"initial-population": len(units), "measure-observation": len(measured)}
if not measured:
return Result(found)
if len(measured) == 1:
q1 = median = q3 = measured[0]
else:
q1, median, q3 = statistics.quantiles(measured, n=4, method="inclusive")
return Result(found, median, {"q1": q1, "q3": q3}, unit="d")
Rule = (Proportion | Composition | Duration | RiskBand | StatusProportion | StatusComposition
| StatusDuration) # fmt: skip
@dataclass(frozen=True)
class Measure:
id: str
title: str
rows: str # which gold rows it reads (see persistance.measures)
rule: Rule
improvement: str | None = None
version: str = "1.0.0"
periods: tuple[str, ...] = ("semester", "month")
group: str = "TOTAL"
params: dict = field(default_factory=dict) # bound into the read of its rows
known: str = "known_at" # when a row's unit became known: before then it isn't counted
# Facts a row carries that became known apart from the row itself: their `known_at`
# column -> the columns they fill. Asked `as_of` before then, the row has them empty.
facts: dict[str, tuple[str, ...]] = field(default_factory=dict)
def evaluate(
measure: Measure,
rows: Iterable[dict],
period: Period,
as_of: datetime | None = None,
event_cutoff: date | None = None,
) -> Result:
"""The measure over the rows known `as_of` (all by default) for one period; durations
count to `event_cutoff` (default: `as_of`'s day, or today)."""
as_of = _moment(as_of)
cutoff = event_cutoff or (as_of or datetime.now(UTC)).date()
if as_of is None: # every row and fact is known
return measure.rule.evaluate(rows if isinstance(rows, list) else list(rows), period, cutoff)
def known(column: str, row: dict) -> bool:
return as_of is None or (_moment(row.get(column)) or as_of) <= as_of
found = []
for row in rows:
if known(measure.known, row):
unknown = [c for k, cols in measure.facts.items() if not known(k, row) for c in cols]
found.append({**row, **dict.fromkeys(unknown)} if unknown else row)
return measure.rule.evaluate(found, period, cutoff)
def evaluate_periods(
measure: Measure,
rows: Iterable[dict],
periods: list[Period],
as_of: datetime | None = None,
event_cutoff: date | None = None,
) -> list[Result]:
"""`evaluate` for each period. A rule that reads only the rows dated in the period gets
just those, in their order: the rows are indexed by month once (periods are whole
months), not scanned once per period. One that keeps a row per unit first gets them
already kept."""
rule = measure.rule
rows = rows if isinstance(rows, list) else list(rows)
if as_of is not None or not getattr(rule, "dated_only", False):
return [evaluate(measure, rows, p, as_of, event_cutoff) for p in periods]
if getattr(rule, "one_per_unit", False): # the same for every period: done once
rows = list({row[rule.unit]: row for row in rows}.values())
months: dict[tuple[int, int], list[int]] = defaultdict(list)
for i, row in enumerate(rows):
if (day := as_day(row[rule.date])) is not None:
months[day.year, day.month].append(i)
found = []
for period in periods:
mine = sorted(i for (y, m), ids in months.items() if date(y, m, 1) in period for i in ids)
found.append(evaluate(measure, [rows[i] for i in mine], period, None, event_cutoff))
return found
def _population(code: str, count: int) -> dict:
return {"code": {"coding": [{"system": POPULATION, "code": code}]}, "count": count}
def report(
measure: Measure, period: Period, result: Result, as_of: datetime | None
) -> MeasureReport:
"""The evaluation as a FHIR R4B MeasureReport (validated when built)."""
group: dict = {
"id": measure.group,
"population": [_population(c, n) for c, n in result.populations.items()],
}
if result.score is not None:
group["measureScore"] = {
"value": result.score,
**({"unit": result.unit} if result.unit else {}),
"extension": [{"url": EXTENSION + k, "valueDecimal": v}
for k, v in result.score_extensions.items()],
} # fmt: skip
elif measure.rule.kind == "composition": # a cohort scores its count
group["measureScore"] = {"value": result.populations["initial-population"]}
if result.strata:
group["stratifier"] = [
{"id": name, "code": [stratifier_code(name)],
"stratum": [{"value": {"text": value},
"population": [_population(c, n) for c, n in cells.items()]}
for value, cells in sorted(values.items())]}
for name, values in result.strata.items()
] + [
{"id": f"{a}-{b}", "code": [stratifier_code(a), stratifier_code(b)],
"stratum": [{"component": [{"code": stratifier_code(a), "value": {"text": va}},
{"code": stratifier_code(b), "value": {"text": vb}}],
"population": [_population(c, n) for c, n in cells.items()]}
for (va, vb), cells in sorted(values.items())]}
for (a, b), values in result.crossed.items()
] # fmt: skip
found = {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary", # with no score when nothing in the period could be measured
"measure": f"{measure_url(measure.id)}|{measure.version}",
"period": {"start": period.start.isoformat(),
"end": date.fromordinal(period.end.toordinal() - 1).isoformat()},
"date": datetime.now().astimezone().isoformat(),
"group": [group],
} # fmt: skip
if as_of is not None:
found["extension"] = [{"url": EXTENSION + "corte-conocimiento",
"valueDateTime": as_of.isoformat()}] # fmt: skip
if measure.improvement:
found["improvementNotation"] = {"coding": [{"system": IMPROVEMENT,
"code": measure.improvement}]} # fmt: skip
return MeasureReport.model_validate(found)
-26
View File
@@ -1,26 +0,0 @@
"""The models' names as the pages and FHIR resources show them (`<domain>.<model>`). A model
without one is shown by its code."""
TITLES: dict[str, str] = {
"cacu.cin2_logistic": "Riesgo de LIEAG+ (regresión logística)",
"cacu.cin2_pim": "Riesgo de LIEAG+ en vigilancia",
"cacu.cancer_pim": "Riesgo de cáncer en vigilancia",
"cacu.cin2_pim_post_colposcopy": "Riesgo de LIEAG+ tras colposcopía",
"cacu.cin2_pim_post_treatment": "Riesgo de LIEAG+ tras tratamiento",
"cacu.survival": "Supervivencia",
"cama.survival": "Supervivencia",
"cama.recurrence": "Recurrencia",
"tea.eeg-gradient": "Curva por edad: gradiente anteroposterior",
"tea.eeg-posterior-rhythm": "Curva por edad: ritmo posterior",
"tea.eeg-spikes": "Curva por edad: picos paroxísticos",
"tea.eeg-spindles-n2": "Curva por edad: husos de sueño N2",
"tea.eeg-spindles-n3": "Curva por edad: husos de sueño N3",
"tea.eeg-spindle-topography-n2": "Curva por edad: topografía de husos N2",
"tea.eeg-spindle-topography-n3": "Curva por edad: topografía de husos N3",
"tea.eeg-ados2": "Relación del EEG con el ADOS-2",
}
def title(model: str) -> str:
"""`model` (`<domain>.<name>`) as the pages name it."""
return TITLES.get(model, model.split(".", 1)[-1])
-564
View File
@@ -1,564 +0,0 @@
"""The ingestion DSL: a graph an operator draws, and the pure steps it needs. No IO here.
A pipeline is one versioned JSON document of nodes; each node names its inputs (the edges).
Every node kind wraps one library operation and outputs one table, so any node's output can
be previewed and a run can restart from the node that changed. Each kind's JSON Schema is
the form the canvas shows for it. Nothing in a graph is specific to one hospital in code.
"""
import re
from datetime import datetime
from graphlib import CycleError, TopologicalSorter
from typing import Annotated, Any, ClassVar, Literal
from urllib.parse import urlsplit, urlunsplit
import dateparser
from pydantic import (
BaseModel,
ConfigDict,
Field,
ValidationError,
create_model,
field_validator,
model_validator,
)
from core import catalog, sources
from core.schema import ENTITIES
ID_PATTERN = r"^[a-z][a-z0-9_]*$" # pipeline and node ids: also table-name safe
Id = Annotated[str, Field(pattern=ID_PATTERN, max_length=40)]
ImportPath = Annotated[str, Field(pattern=r"^[A-Za-z_][\w.]*:[A-Za-z_]\w*$")]
EntityName = Literal[tuple(ENTITIES)] # type: ignore[valid-type]
# How the forms name each entity: identity, and each study by its catalog title.
ENTITY_TITLES = {"identity": "Identidad de la persona",
**{name: spec.title for name, spec in catalog.studies().items()}} # fmt: skip
def _says(title: str, description: str = "", options: dict[str, str] | None = None,
advanced: bool = False, keys: Literal["field"] | None = None) -> Any: # fmt: skip
"""A field as the canvas form shows it: its title and help in the operator's words,
for a fixed set of values how each one reads, and whether only the "Avanzado" tab
shows it (what a guided dialog fills instead); a map keyed by platform fields says so
(`keys="field"`), so its keys are picked by their titles."""
extra: dict[str, Any] = {}
if options:
listed = [{"value": k, "label": v} for k, v in options.items()]
extra["widget"] = {"formlyConfig": {"props": {"options": listed}}}
if advanced:
extra["advanced"] = True
if keys:
extra["keys"] = keys
return Field(title=title, description=description or None, json_schema_extra=extra or None)
class Position(BaseModel):
x: float
y: float
class Node(BaseModel):
model_config = ConfigDict(extra="forbid")
inputs_allowed: ClassVar[tuple[int, int | None]] = (1, 1) # (min, max); None: no max
id: Id
inputs: list[Id] = []
label: Annotated[str, _says("Nombre", "Cómo se ve en el diagrama.")] = ""
position: Position | None = None # where the canvas drew it
class Guided(BaseModel):
"""How the Conectar dialog drew a source: its type (core.sources) and the answers given.
The node's dlt fields are made from them; drawn by hand ("Avanzado"), a node has none."""
model_config = ConfigDict(extra="forbid")
type: str
answers: dict[str, Any] = {}
class Source(Node):
"""One table, file set or API resource, copied as it is (dlt). Merged on the source's
own primary key or `primary_key`; replaced whole when it has none."""
inputs_allowed = (0, 0)
kind: Literal["source"] = "source"
# any dlt source or resource, e.g. dlt.sources.sql_database:sql_table
source: Annotated[
ImportPath, _says("Fuente dlt", "Módulo:función de la fuente dlt.", advanced=True)
]
args: Annotated[
dict[str, Any], _says("Argumentos", "Los de la fuente dlt.", advanced=True)
] = {}
resource: Annotated[ # which resource, when the source has several
str | None,
_says("Recurso", "Cuál, si la fuente ofrece varios (una tabla).", advanced=True),
] = None
then: Annotated[ # a dlt transformer piped after (file contents, Excel)
ImportPath | None, _says("Lector", "Transformador dlt para los archivos.", advanced=True)
] = None
primary_key: Annotated[
list[str], _says("Llave", "Columnas que identifican una fila.", advanced=True)
] = []
guided: Annotated[Guided | None, _says("Asistente", advanced=True)] = None
@model_validator(mode="before")
@classmethod
def _made_from_answers(cls, data: Any) -> Any:
"""A guided source's dlt fields always follow its answers. A source drawn by hand
that a catalog type makes exactly is read as that type, so the dialog edits it."""
if isinstance(data, dict) and not data.get("guided") and data.get("source"):
if found := sources.recognise(data):
data = {**data, "guided": {"type": found[0], "answers": found[1]}}
if isinstance(data, dict) and data.get("guided"):
guided = data["guided"]
guided = guided.model_dump() if isinstance(guided, BaseModel) else guided
if MASK not in repr(guided.get("answers", {})): # masked: shown, not run
data = {**data, **sources.render(guided["type"], guided.get("answers", {}))}
return data
class Read(Node):
"""Files in a column (PDF, Word, Excel, scans...) to text (MarkItDown, OCRmyPDF)."""
kind: Literal["read"] = "read"
column: Annotated[
str, _says("Columna con los archivos", "Donde la entrada trae cada documento.")
]
class Condition(BaseModel):
column: Annotated[str, _says("Columna", "Por ejemplo «text», el texto leído del documento.")]
op: Annotated[
Literal["equals", "contains", "matches", "present"],
_says(
"Condición",
options={
"equals": "es igual a",
"contains": "contiene",
"matches": "coincide con la expresión",
"present": "tiene algún valor",
},
), # fmt: skip
]
value: Annotated[str, _says("Valor", "Lo que se busca; por ejemplo «citología».")] = ""
class Route(Node):
"""Only the rows where every condition holds (e.g. reports titled "Citología"). An
`otherwise` route takes the rows of its input that none of the other routes on that
input take (documents nobody recognises, for a reviewer), then its own conditions."""
kind: Literal["route"] = "route"
when: Annotated[list[Condition], _says("Pasan las filas donde")] = []
otherwise: Annotated[
bool, _says("Lo que ningún otro tome", "Recoge lo que nadie reconoce, para revisarlo.")
] = False
class Map(Node):
"""Columns to platform fields, the site's codes translated by its ConceptMap
(core.concept_map), and its date formats."""
kind: Literal["map"] = "map"
fields: Annotated[ # platform field -> column
dict[str, str], _says("Campos", "Dato de la plataforma → columna del sitio.", keys="field")
]
concept_map: Annotated[ # the site's codes in platform terms
Id | None, _says("Equivalencias de códigos", "La tabla de códigos del sitio.")
] = None
formats: Annotated[ # platform field -> strptime format
dict[str, str], _says("Formatos de fecha", "Por ejemplo %d/%m/%Y.", keys="field")
] = {}
# platform field -> a value in platform terms that every row has, though no column says
# it (a table of neurology notes: their specialty)
values: Annotated[
dict[str, str], _says("Valores fijos", "Un dato igual para todas las filas.", keys="field")
] = {}
class Extract(Node):
"""Platform fields read from text, each kept with the text it was read from.
`auto` asks the LLM when one is configured and answering, else applies `patterns`;
with neither, the row is held. Patterns are regexes with one group, per field (the
LLM can propose them from sample documents); their values go through the ConceptMap
and `formats` as in `map`."""
kind: Literal["extract"] = "extract"
# the text to read; several columns are read as one document, in their order (an
# outsourced result joined to the order it answers)
column: Annotated[str | list[str], _says("Columna con el texto")]
entity: Annotated[
EntityName, _says("Estudio", "Qué estudio se saca del documento.", ENTITY_TITLES)
]
method: Annotated[
Literal["auto", "llm", "patterns"],
_says(
"Cómo leer",
options={
"auto": "Automático",
"llm": "Con el modelo de lenguaje",
"patterns": "Con patrones",
},
), # fmt: skip
] = "auto"
hints: Annotated[str, _says("Indicaciones", "Para el modelo de lenguaje.")] = ""
patterns: Annotated[ # platform field -> regex with one group
dict[str, str], _says("Patrones", "Dato → expresión con un grupo ( ).", keys="field")
] = {}
# platform field -> a column of the row taken as it is, not read from the text (an EEG
# report joined to its recording: the date from the report, the file from the column)
columns: Annotated[
dict[str, str],
_says("Datos tomados de columnas", "Dato → columna, sin leer el texto.", keys="field"),
] = {}
concept_map: Annotated[Id | None, _says("Equivalencias de códigos")] = None
formats: Annotated[dict[str, str], _says("Formatos de fecha", keys="field")] = {}
@field_validator("patterns")
@classmethod
def _one_group_each(cls, v: dict[str, str]) -> dict[str, str]:
for field, pattern in v.items():
if re.compile(pattern, re.IGNORECASE).groups != 1:
raise ValueError(f"{field}: a pattern needs exactly one (group)")
return v
def text(self, row: dict[str, Any]) -> str:
"""The row's text this node reads."""
columns = [self.column] if isinstance(self.column, str) else self.column
return "\n".join(str(row[c]) for c in columns if row.get(c))
class Fhir(Node):
"""FHIR R4 Bundles a standard hospital sent (a column of their JSON) as rows of one
entity: identity, death or a study (core.fhir_in). The sender's own codes go through
its ConceptMap."""
kind: Literal["fhir"] = "fhir"
column: Annotated[str, _says("Columna con el FHIR")] = "doc"
entity: Annotated[EntityName, _says("Estudio", options=ENTITY_TITLES)]
concept_map: Annotated[Id | None, _says("Equivalencias de códigos")] = None
class Join(Node):
"""Two inputs side by side where their columns match."""
inputs_allowed = (2, 2)
kind: Literal["join"] = "join"
on: Annotated[ # (left column, right column)
list[tuple[str, str]],
_says("Columnas iguales", "Columna de la primera entrada = columna de la segunda."),
]
how: Annotated[
Literal["inner", "left"],
_says(
"Cuáles quedan",
options={"inner": "Solo las que tienen pareja", "left": "Todas las de la izquierda"},
), # fmt: skip
] = "inner"
IDENTIFIERS = ("record_number", "curp", "nss")
class Link(Node):
"""Identity rows from every input, grouped into persons (Splink).
Two records are the same person when any rule holds (Splink's SQL rule syntax, `l.`
and `r.` for the two records); persons are the connected groups. A person whose
records disagree on birth date or sex is held for review as a whole. Pairs Splink
scores above `review` that ended up apart are queued as possible matches."""
inputs_allowed = (1, None)
kind: Literal["link"] = "link"
fields: Annotated[list[str], _says("Datos que comparar")] = [
"record_number", "full_name", "curp", "nss", "birth_date", "sex"] # fmt: skip
rules: Annotated[ # empty: the defaults for `fields` (see default_rules)
list[str],
_says(
"Reglas",
"Vacío: las de siempre (mismo identificador, o misma fecha de nacimiento y nombre).",
), # fmt: skip
] = []
review: Annotated[
float,
Field(gt=0, le=1),
_says("Umbral para revisar", "Parecidos por encima de esto los ve un revisor."),
] = 0.5
def default_rules(self) -> list[str]:
"""The same identifier, unless the birth dates differ; or the same birth date and
the same name (as compared: upper case, no accents, single spaces)."""
dob = "birth_date" in self.fields
same_dob = (
" and (l.birth_date is null or r.birth_date is null"
" or l.birth_date = r.birth_date)" if dob else ""
) # fmt: skip
rules = [f"l.{f} = r.{f}{same_dob}" for f in IDENTIFIERS if f in self.fields]
if dob and "full_name" in self.fields:
rules.append("l.birth_date = r.birth_date and l.full_name = r.full_name")
return rules
class Target(Node):
"""Rows of platform fields into one platform entity, each row given its person by the
one `link` node among the inputs. Rule breaks are held for review."""
inputs_allowed = (2, None)
kind: Literal["target"] = "target"
entity: Annotated[
EntityName,
_says("Estudio", "En qué estudio de la plataforma se guarda.", ENTITY_TITLES),
]
@field_validator("entity")
@classmethod
def _not_identity(cls, v: str) -> str:
if v == "identity":
raise ValueError("identity rows go into a link node, not a target")
return v
AnyNode = Annotated[
Source | Read | Route | Map | Extract | Fhir | Join | Link | Target, Field(discriminator="kind")
]
class Pipeline(BaseModel):
nodes: list[AnyNode]
@model_validator(mode="after")
def _a_valid_graph(self):
ids = [n.id for n in self.nodes]
if len(ids) != len(set(ids)):
raise ValueError("node ids must be unique")
for n in self.nodes:
lo, hi = n.inputs_allowed
if not lo <= len(n.inputs) <= (hi if hi is not None else len(n.inputs)):
raise ValueError(f"{n.id}: {n.kind} takes {lo}..{hi} inputs")
if missing := set(n.inputs) - set(ids):
raise ValueError(f"{n.id}: no node {sorted(missing)}")
kinds = {n.id: n.kind for n in self.nodes}
for n in self.nodes:
if n.kind == "target" and [kinds[i] for i in n.inputs].count("link") != 1:
raise ValueError(f"{n.id}: a target takes exactly one link node among its inputs")
try:
self.order()
except CycleError as e:
raise ValueError(f"cycle: {e.args[1]}") from None
return self
def order(self) -> list[AnyNode]:
"""Nodes in an order where every input runs before the nodes that read it."""
by_id = {n.id: n for n in self.nodes}
graph = TopologicalSorter({n.id: n.inputs for n in self.nodes})
return [by_id[i] for i in graph.static_order()]
RECORD = "_record" # the source row every row comes from (hash of that row)
HELD = "_held" # why a row may not reach silver (list of reasons) or None
QUOTES = "_quotes" # what text each LLM value was read from
def matches(node: Route, row: dict[str, Any]) -> bool:
for c in node.when:
value = row.get(c.column)
text = "" if value is None else str(value)
ok = {
"equals": text == c.value,
"contains": c.value.casefold() in text.casefold(),
"matches": re.search(c.value, text) is not None,
"present": value not in (None, ""),
}[c.op]
if not ok:
return False
return True
def join(node: Join, left: list[dict], right: list[dict], right_id: str) -> list[dict]:
"""Left rows with the matching right rows' columns (a clashing name gets `__<right>`)."""
index: dict[tuple, list[dict]] = {}
for r in right:
index.setdefault(tuple(r.get(b) for _, b in node.on), []).append(r)
out = []
for row in left:
found = index.get(tuple(row.get(a) for a, _ in node.on), [])
for r in found or ([{}] if node.how == "left" else []):
extra = {(k if k not in row else f"{k}__{right_id}"): v for k, v in r.items()}
out.append({**row, **extra, RECORD: row[RECORD]})
return out
Codes = dict[str, dict[str, str]] # field -> site code (casefolded) -> platform code
def convert(node: Map | Extract, field: str, raw: Any, codes: Codes) -> Any:
"""A raw value as the platform field expects it: the site's code translated (its
ConceptMap, case ignored), then its date format: a strptime format (spaces inside the
value ignored when the format has none), or `dateparser:<language>` for dates written
out ("9 de diciembre de 2025"). A value that doesn't parse is kept as written, so the
target holds it with the reason."""
if not isinstance(raw, str):
return raw
raw = raw.strip()
raw = codes.get(field, {}).get(raw.casefold(), raw)
fmt = node.formats.get(field)
if fmt and fmt.startswith("dateparser:"):
found = dateparser.parse(raw, languages=[fmt.split(":")[1]])
return found.date() if found else raw
if fmt:
if " " not in fmt: # OCR may split a number ("25/01/1 967")
raw = "".join(raw.split())
try:
return datetime.strptime(raw, fmt).date()
except ValueError:
return raw
return raw
def map_row(node: Map, row: dict[str, Any], codes: Codes) -> dict[str, Any]:
mapped = {
field: convert(node, field, row.get(col), codes) for field, col in node.fields.items()
}
return {**mapped, **node.values, RECORD: row[RECORD]}
def validate(entity: str, values: dict[str, Any]) -> list[str]:
"""Why these values break the platform schema; empty if they don't."""
try:
ENTITIES[entity].model_validate(values)
except ValidationError as e:
return [f"{'.'.join(map(str, err['loc']))}: {err['msg']}" for err in e.errors()]
return []
_SPACE = re.compile(r"\s+")
def grounded(quote: str | None, text: str) -> bool:
"""An LLM value counts only if the text it says it read is really in the document."""
if not quote:
return False
norm = lambda s: _SPACE.sub(" ", s).strip().casefold() # noqa: E731
return norm(quote) in norm(text)
def ground(answer: dict, text: str) -> list[tuple[dict, dict, list[str]]]:
"""Each record of an LLM answer as (values, quotes, reasons to hold it). A value whose
quote is not in the text is dropped, and the record is held saying so."""
out = []
for record in answer.get("records", []):
values, quotes, held = {}, {}, []
for field, got in record.items():
if not got or got.get("value") is None:
continue
if grounded(got.get("quote"), text):
values[field], quotes[field] = got["value"], got["quote"]
else:
held.append(f"{field}: not found in the document as quoted")
out.append((values, quotes, held))
return out
def apply_patterns(node: Extract, text: str, codes: Codes) -> list[tuple[dict, dict, list[str]]]:
"""One record from the node's patterns: (values, quotes, reasons to hold it). A value
found this way is grounded by construction: the quote is the matched text."""
values, quotes = {}, {}
for field, pattern in node.patterns.items():
if found := re.search(pattern, text, re.IGNORECASE):
values[field] = convert(node, field, found.group(1), codes)
quotes[field] = found.group(0)
if not values:
return []
return [(values, quotes, [])]
def answer_schema(entity: str) -> dict:
"""JSON Schema for an LLM answer: every record of `entity` found, each field with the
quote it was read from."""
fields = {
f: (create_model(f"{entity}_{f}", value=(info.annotation, None), quote=(str, "")), None)
for f, info in ENTITIES[entity].model_fields.items()
}
record = create_model(entity, **fields)
return create_model("Answer", records=(list[record], [])).model_json_schema()
MASK = "********"
_SECRET_KEY = re.compile(r"pass|secret|token|key", re.IGNORECASE)
def _mask(key: str, value: Any) -> Any:
if isinstance(value, dict):
return {k: _mask(k, v) for k, v in value.items()}
if not isinstance(value, str):
return value
if _SECRET_KEY.search(key):
return MASK
url = urlsplit(value)
if url.password:
netloc = url.netloc.replace(f":{url.password}@", f":{MASK}@", 1)
return urlunsplit(url._replace(netloc=netloc))
return value
def _secret_answers(guided: "Guided") -> set[str]:
"""Answers masked whole (a password); a sign-in's account keeps who it is and masks
its tokens and client secret, like any argument."""
fields = sources.catalog().types[guided.type].fields
return {k for k, f in fields.items() if f.type == "password"}
def _masked_source(n: "Source") -> "Source":
update: dict[str, Any] = {"args": _mask("", n.args)}
if n.guided:
secret = _secret_answers(n.guided)
answers = {k: MASK if k in secret and v not in (None, "") else _mask(k, v)
for k, v in n.guided.answers.items()} # fmt: skip
update["guided"] = n.guided.model_copy(update={"answers": answers})
return n.model_copy(update=update)
def redacted(pipeline: Pipeline) -> Pipeline:
"""The pipeline with every secret in its sources masked (arguments and the dialog's
answers), as the API shows it."""
nodes = [_masked_source(n) if n.kind == "source" else n for n in pipeline.nodes]
return pipeline.model_copy(update={"nodes": nodes})
def _restore(new: Any, old: Any, where: str) -> Any:
if isinstance(new, dict):
old = old if isinstance(old, dict) else {}
return {k: _restore(v, old.get(k), f"{where}.{k}") for k, v in new.items()}
if isinstance(new, str) and MASK in new:
if not isinstance(old, str) or _mask(where.rsplit(".", 1)[-1], old) != new:
raise ValueError(f"{where}: masked, but no saved secret to keep there")
return old
return new
def restored(new: Pipeline, old: Pipeline | None) -> Pipeline:
"""A pipeline sent back by the UI with masks where secrets were: the saved secrets are
kept. A mask with nothing saved behind it is refused."""
saved = {n.id: n for n in old.nodes if n.kind == "source"} if old else {}
nodes = [_restored_source(n, saved.get(n.id)) if n.kind == "source" else n
for n in new.nodes] # fmt: skip
return new.model_copy(update={"nodes": nodes})
def _restored_source(new: "Source", old: "Source | None") -> "Source":
if not new.guided:
return new.model_copy(update={"args": _restore(new.args, old and old.args, new.id)})
kept = old.guided.answers if old and old.guided and old.guided.type == new.guided.type else {}
secret = _secret_answers(new.guided)
answers = {}
for k, v in new.guided.answers.items():
if k in secret and v == MASK:
if kept.get(k) in (None, ""):
raise ValueError(f"{new.id}.{k}: masked, but no saved secret to keep there")
answers[k] = kept[k]
else:
answers[k] = _restore(v, kept.get(k), f"{new.id}.{k}")
guided = new.guided.model_copy(update={"answers": answers})
drawn = new.model_dump(exclude={"guided"})
return Source.model_validate({**drawn, "guided": guided.model_dump()})
-64
View File
@@ -1,64 +0,0 @@
"""The platform schema: the only fixed shape in ingestion. Every source is mapped onto it.
`identity` is what a record says about whom it belongs to; every other entity is a study of
the clinical catalog (core.catalog), whose natural key and fields the catalog declares. Two
values for one key that disagree are a conflict. `person` is never a field: record linkage
over `identity` values assigns it.
"""
import re
from datetime import date
from enum import StrEnum
from typing import ClassVar
from pydantic import BaseModel, ConfigDict, Field, field_validator
from core import catalog
class Sex(StrEnum):
FEMALE = "female"
MALE = "male"
# Systems of the identifiers a person carries. A record number's system is where it came
# from (`urn:isssteleon:<pipeline>:<node>`): a hospital has as many as it has sources.
IDENTIFIER_SYSTEMS = {
"curp": "https://isssteleon.org/fhir/sid/curp",
"nss": "https://isssteleon.org/fhir/sid/nss",
}
RECORD_NUMBER_SYSTEM = "urn:isssteleon:"
_DATE = re.compile(r"\d{1,4}[/.-]\d{1,2}[/.-]\d{1,4}")
class Entity(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
key: ClassVar[tuple[str, ...]] = ()
class Identity(Entity):
"""What a record says about whom it belongs to. Input to linkage, never trusted alone."""
record_number: str | None = Field(None, title="Número de expediente")
full_name: str | None = Field(None, title="Nombre completo")
curp: str | None = Field(None, title="CURP")
nss: str | None = Field(None, title="NSS")
birth_date: date | None = Field(None, title="Fecha de nacimiento")
sex: Sex | None = Field(None, title="Sexo")
@field_validator("record_number")
@classmethod
def _not_a_date(cls, v: str | None) -> str | None:
"""A date read where a record number should be (a report's date beside "No.
Registro:", say) would join strangers: the record waits for a reviewer instead."""
if v is not None and _DATE.fullmatch(v.strip()):
raise ValueError("a date is not a record number")
return v
ENTITIES: dict[str, type[BaseModel]] = {
"identity": Identity,
**{name: catalog.model(name) for name in catalog.studies()},
}
-338
View File
@@ -1,338 +0,0 @@
"""The kinds of source an operator can connect, as the Conectar dialog walks them through.
It is data (`types.yaml` beside this module): each type says what to ask (its fields, in
plain words), how the answers become a pipeline's `Source` node (a dlt source and its
arguments), and what "Probar conexión" can list from it. A new kind of source is a new entry,
never code; a site's own source is configuration (the answers saved in its pipeline).
Templates: a string that is exactly "{field}" takes the answer as given (a number stays a
number, a "{field[part]}" one part of a structured answer such as a sign-in's; an empty
optional answer drops the key, and a block whose every answer is empty
goes with it); inside a longer string, `{field:url}` quotes
the answer for a URL's user or password, `{field:path}` for a URL's path, and `{field:last}`
takes the last part of a link (a folder's id in a shared link).
"""
import re
import string
from functools import cache
from pathlib import Path
from typing import Any, Literal
from urllib.parse import quote, unquote
import yaml
from pydantic import BaseModel, ConfigDict, model_validator
HERE = Path(__file__).parent
FieldType = Literal[
"text", # a line of text
"number",
"password", # never shown back; masked like any secret
"select", # one of `options`
"folder", # a folder on the server, browsed under the roots the operator mounted
"server_file", # a file on the server, browsed the same way
"upload", # files sent from the user's computer; holds the folder they landed in
"url", # a web address, or a path typed in
"oauth", # "Iniciar sesión con …": holds the provider's refresh token
"table", # picked from what "Probar conexión" listed
"format", # how to read the files: one of the catalog's `formats`
"columns", # some of the table's columns (a list), picked from its first rows
]
class Option(BaseModel):
model_config = ConfigDict(extra="forbid")
value: Any
label: str
class FieldSpec(BaseModel):
model_config = ConfigDict(extra="forbid")
label: str
type: FieldType = "text"
help: str = ""
placeholder: str = ""
required: bool = True
default: Any = None
options: list[Option] = [] # select
provider: str | None = None # oauth: microsoft, google
advanced: bool = False # shown under "Más opciones"
@model_validator(mode="after")
def _complete(self):
if self.type == "select" and not self.options:
raise ValueError("a select field lists its options")
if self.type == "oauth" and not self.provider:
raise ValueError("an oauth field names its provider")
return self
class Listing(BaseModel):
"""What "Probar conexión" shows: a database's tables (the resources of `source`, built
from `args`), or the first rows the type's own node reads (files, records)."""
model_config = ConfigDict(extra="forbid")
kind: Literal["tables", "rows"]
source: str | None = None
args: dict[str, Any] = {}
class SourceType(BaseModel):
model_config = ConfigDict(extra="forbid")
group: str
title: str
description: str
icon: str
fields: dict[str, FieldSpec]
source: str # the dlt source or resource the node runs
args: dict[str, Any] = {}
resource: str | None = None
then: str | None = None
primary_key: list[str] = []
listing: Listing | None = None
@model_validator(mode="after")
def _templates_name_fields(self):
named = _placeholders([self.source, self.args, self.resource, self.then])
if self.listing:
named |= _placeholders([self.listing.source, self.listing.args])
if unknown := named - set(self.fields):
raise ValueError(f"templates name unknown fields {sorted(unknown)}")
return self
class Provider(BaseModel):
"""A sign-in button's OAuth 2.0 provider (authorization code flow)."""
model_config = ConfigDict(extra="forbid")
title: str
env: str # prefix of the server's settings for its app registration
authorize_url: str
token_url: str
scope: str
authorize_params: dict[str, str] = {}
class Group(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str
description: str
class Catalog(BaseModel):
model_config = ConfigDict(extra="forbid")
groups: dict[str, Group]
providers: dict[str, Provider]
formats: list[Option] # how a file is read: the `then` of a filesystem source
types: dict[str, SourceType]
@model_validator(mode="after")
def _groups_exist(self):
for name, t in self.types.items():
if t.group not in self.groups:
raise ValueError(f"{name}: no group {t.group}")
for field in t.fields.values():
if field.type == "oauth" and field.provider not in self.providers:
raise ValueError(f"{name}: no provider {field.provider}")
return self
class MissingAnswer(ValueError):
"""An answer the type needs was left empty; its message names it in plain words."""
@cache
def catalog() -> Catalog:
return Catalog.model_validate(yaml.safe_load((HERE / "types.yaml").read_text("utf-8")))
class _Formatter(string.Formatter):
def format_field(self, value: Any, format_spec: str) -> str:
if format_spec == "url":
return quote(str(value), safe="")
if format_spec == "path":
return quote(str(value), safe="/")
if format_spec == "last":
return str(value).split("?")[0].rstrip("/").rsplit("/", 1)[-1]
return super().format_field(value, format_spec)
_FORMAT = _Formatter()
def _base(name: str) -> str:
return name.split("[", 1)[0].split(".", 1)[0]
def _placeholders(template: Any) -> set[str]:
if isinstance(template, str):
return {_base(name) for _, name, _, _ in _FORMAT.parse(template) if name}
if isinstance(template, dict):
return set().union(*(_placeholders(v) for v in template.values()))
if isinstance(template, list):
return set().union(*(_placeholders(v) for v in template))
return set()
_DROP = object()
def _fill(template: Any, values: dict[str, Any]) -> Any:
named = _placeholders(template)
if isinstance(template, dict) and named and all(values.get(n) in (None, "") for n in named):
return _DROP # a block whose every answer is empty (an optional token's auth)
if isinstance(template, dict):
filled = {k: _fill(v, values) for k, v in template.items()}
return {k: v for k, v in filled.items() if v is not _DROP}
if isinstance(template, list):
return [v for v in (_fill(t, values) for t in template) if v is not _DROP]
if not isinstance(template, str):
return template
parts = list(_FORMAT.parse(template))
if len(parts) == 1 and parts[0][0] == "" and parts[0][1] and not parts[0][2]:
name = parts[0][1] # "{account}", or a part of it: "{account[drive_id]}"
if values.get(_base(name)) in (None, ""):
return _DROP
value = _FORMAT.get_field(name, (), values)[0]
return _DROP if value in (None, "") else value
return _FORMAT.vformat(template, (), {k: "" if v is None else v for k, v in values.items()})
def answers(type_id: str, given: dict[str, Any]) -> dict[str, Any]:
"""The answers with defaults filled in; a required answer missing is refused."""
spec = catalog().types[type_id]
if unknown := set(given) - set(spec.fields):
raise ValueError(f"{type_id}: no fields {sorted(unknown)}")
out = {}
for name, field in spec.fields.items():
value = given.get(name)
if value in (None, ""):
value = field.default
if value in (None, "") and field.required:
raise MissingAnswer(f"falta «{field.label}»")
out[name] = value
return out
def render(type_id: str, given: dict[str, Any]) -> dict[str, Any]:
"""The `Source` node fields (source, args, resource, then, primary_key) the answers
make."""
spec = catalog().types[type_id]
values = answers(type_id, given)
made = {
"source": _fill(spec.source, values),
"args": _fill(spec.args, values),
"resource": _fill(spec.resource, values),
"then": _fill(spec.then, values),
"primary_key": spec.primary_key,
}
return {k: None if v is _DROP else v for k, v in made.items()}
def listing(type_id: str, given: dict[str, Any]) -> tuple[str, dict[str, Any]] | None:
"""For a type that lists tables: the dlt source and arguments that list them. The
table field may still be empty (it is what the listing helps pick)."""
spec = catalog().types[type_id]
if not spec.listing or spec.listing.kind != "tables" or not spec.listing.source:
return None
relaxed = {n: (given.get(n) or f.default) for n, f in spec.fields.items()}
missing = [f.label for n, f in spec.fields.items()
if f.required and f.type != "table" and relaxed[n] in (None, "")] # fmt: skip
if missing:
raise MissingAnswer("falta " + ", ".join(f"«{m}»" for m in missing))
return _fill(spec.listing.source, relaxed), _fill(spec.listing.args, relaxed)
class _NoMatch(Exception):
pass
def _take(template: Any, value: Any, found: dict[str, Any]) -> None:
"""The answers that make `template` give `value`, into `found` (_NoMatch when none)."""
if isinstance(template, dict):
if not isinstance(value, dict) or set(value) - set(template):
raise _NoMatch
for key, part in template.items():
if key in value:
_take(part, value[key], found)
elif not _placeholders(part): # a fixed key the node lacks
raise _NoMatch
return
if isinstance(template, list):
if not isinstance(value, list) or len(value) != len(template):
raise _NoMatch
for part, item in zip(template, value, strict=True):
_take(part, item, found)
return
if not isinstance(template, str):
if template != value:
raise _NoMatch
return
parts = list(_FORMAT.parse(template))
if any(name and ("[" in name or "." in name) for _, name, _, _ in parts):
raise _NoMatch # an answer's part (an account's drive): not read back
if len(parts) == 1 and parts[0][0] == "" and parts[0][1] and not parts[0][2]:
_answer(found, parts[0][1], value) # the whole value, whatever its type
return
if not isinstance(value, str):
raise _NoMatch
pattern, names = "", []
for literal, name, spec, _ in parts:
pattern += re.escape(literal)
if name:
pattern += f"(?P<g{len(names)}>.*?)"
names.append((name, spec))
matched = re.fullmatch(pattern, value, re.DOTALL)
if not matched:
raise _NoMatch
for i, (name, spec) in enumerate(names):
text = matched.group(f"g{i}")
_answer(found, name, unquote(text) if spec in ("url", "path") else text)
def _answer(found: dict[str, Any], name: str, value: Any) -> None:
if name in found and found[name] != value:
raise _NoMatch
found[name] = value
def recognise(node: dict[str, Any]) -> tuple[str, dict[str, Any]] | None:
"""The catalog type and answers that make a source node drawn by hand, when one makes
exactly it (its source, args, resource and reader): what lets the dialog edit it."""
made = {k: node.get(k) for k in ("source", "args", "resource", "then")}
made["args"] = made["args"] or {}
for type_id, spec in catalog().types.items():
found: dict[str, Any] = {}
try:
for key in made:
template = getattr(spec, key)
if template is None:
if made[key] not in (None, {}):
raise _NoMatch
continue
_take(template, made[key], found)
numbers = {n for n, f in spec.fields.items() if f.type == "number"}
given = {n: (int(v) if n in numbers and isinstance(v, str) and v.isdigit() else v)
for n, v in found.items() if n in spec.fields} # fmt: skip
rendered = render(type_id, given)
except (_NoMatch, ValueError):
continue
if all(rendered[k] == made[k] for k in ("source", "resource", "then")) and _same_args(
rendered["args"] or {}, made["args"], spec
):
return type_id, given
return None
def _same_args(rendered: dict, drawn: dict, spec: "SourceType") -> bool:
"""The same arguments, but for those the type fills from its fields' defaults (rows per
batch, say) where the drawn node left them to the source: how much it reads at a time,
not what."""
defaults = {f"{{{n}}}": f.default for n, f in spec.fields.items() if f.default is not None}
for key, value in rendered.items():
if key in drawn:
if drawn[key] != value:
return False
elif defaults.get(spec.args.get(key)) != value:
return False
return set(drawn) <= set(rendered)
-384
View File
@@ -1,384 +0,0 @@
# The kinds of source the Conectar dialog offers (core.sources). Words are what the operator
# reads: plain Spanish, no jargon. Each type becomes one pipeline `Source` node.
groups:
database:
title: Base de datos
description: Tablas de un sistema del hospital (expediente, laboratorio, archivo de PDFs).
files:
title: Archivos
description: PDFs, escaneos, EEGs, hojas de cálculo o textos, en su computadora o en el servidor.
cloud:
title: Nube
description: Carpetas en OneDrive, SharePoint, Google Drive u otro almacenamiento en línea.
web:
title: Web
description: Un sistema que entrega sus datos por internet (una API) o envía FHIR.
# The sign-in buttons. The app registration (client id and secret) is the site's IT's, set
# on the server as <ENV>_CLIENT_ID and <ENV>_CLIENT_SECRET (Microsoft also <ENV>_TENANT_ID,
# default "organizations"); `{tenant}` in an endpoint takes it.
providers:
microsoft:
title: Microsoft
env: MICROSOFT
authorize_url: "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize"
token_url: "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token"
scope: "offline_access User.Read Files.Read.All Sites.Read.All"
google:
title: Google
env: GOOGLE
authorize_url: "https://accounts.google.com/o/oauth2/v2/auth"
token_url: "https://oauth2.googleapis.com/token"
scope: "https://www.googleapis.com/auth/drive.readonly"
authorize_params: {access_type: offline, prompt: consent}
formats:
- {value: "persistance.readers:read_bytes", label: "Documentos (PDF, Word, escaneos, EEG): cada archivo completo"}
- {value: "persistance.readers:read_excel", label: "Hojas de Excel: cada fila de cada hoja"}
- {value: "dlt.sources.filesystem:read_csv", label: "CSV (separado por comas): cada fila"}
- {value: "persistance.readers:read_tsv", label: "Texto separado por tabuladores: cada fila"}
- {value: "dlt.sources.filesystem:read_jsonl", label: "JSON por líneas: cada línea"}
- {value: "dlt.sources.filesystem:read_parquet", label: "Parquet: cada fila"}
types:
sqlserver:
group: database
title: SQL Server
description: Una tabla de Microsoft SQL Server.
icon: database
fields: &sql_fields
host: {label: Servidor, placeholder: "10.0.0.5 o servidor.hospital.local", help: "Nombre o dirección del equipo donde está la base de datos."}
port: {label: Puerto, type: number, default: 1433, advanced: true, help: "Valor habitual; cámbielo solo si TI lo indica."}
database: {label: Base de datos, placeholder: "Pruebas"}
user: {label: Usuario}
password: {label: Contraseña, type: password}
schema: {label: Esquema, default: dbo, advanced: true, help: "El grupo de tablas; valor habitual."}
table: {label: Tabla, type: table, help: "Pulse «Probar conexión» para ver las tablas."}
chunk_size: {label: Filas por lote, type: number, default: 100, advanced: true, help: "Menos filas por lote usan menos memoria cuando cada fila guarda un archivo."}
columns: {label: Columnas, type: columns, required: false, advanced: true, help: "Solo estas columnas; vacío: todas."}
source: "dlt.sources.sql_database:sql_table"
args: &sql_args
credentials: "mssql+pymssql://{user:url}:{password:url}@{host}:{port}/{database:path}"
schema: "{schema}"
table: "{table}"
chunk_size: "{chunk_size}"
included_columns: "{columns}"
listing: &sql_listing
kind: tables
source: "dlt.sources.sql_database:sql_database"
args:
credentials: "mssql+pymssql://{user:url}:{password:url}@{host}:{port}/{database:path}"
schema: "{schema}"
reflection_level: minimal
postgresql:
group: database
title: PostgreSQL
description: Una tabla de PostgreSQL.
icon: database
fields:
<<: *sql_fields
port: {label: Puerto, type: number, default: 5432, advanced: true, help: "Valor habitual; cámbielo solo si TI lo indica."}
schema: {label: Esquema, default: public, advanced: true, help: "El grupo de tablas; valor habitual."}
source: "dlt.sources.sql_database:sql_table"
args:
<<: *sql_args
credentials: "postgresql+psycopg2://{user:url}:{password:url}@{host}:{port}/{database:path}"
listing:
<<: *sql_listing
args:
credentials: "postgresql+psycopg2://{user:url}:{password:url}@{host}:{port}/{database:path}"
schema: "{schema}"
reflection_level: minimal
mysql:
group: database
title: MySQL o MariaDB
description: Una tabla de MySQL o MariaDB.
icon: database
fields:
<<: *sql_fields
port: {label: Puerto, type: number, default: 3306, advanced: true, help: "Valor habitual; cámbielo solo si TI lo indica."}
schema: {label: Esquema, required: false, advanced: true, help: "En MySQL suele quedar vacío."}
source: "dlt.sources.sql_database:sql_table"
args:
<<: *sql_args
credentials: "mysql+pymysql://{user:url}:{password:url}@{host}:{port}/{database:path}"
listing:
<<: *sql_listing
args:
credentials: "mysql+pymysql://{user:url}:{password:url}@{host}:{port}/{database:path}"
schema: "{schema}"
reflection_level: minimal
oracle:
group: database
title: Oracle
description: Una tabla de Oracle.
icon: database
fields:
<<: *sql_fields
port: {label: Puerto, type: number, default: 1521, advanced: true, help: "Valor habitual; cámbielo solo si TI lo indica."}
database: {label: Servicio, placeholder: "ORCLPDB1", help: "El nombre de servicio de la base de datos."}
schema: {label: Esquema, required: false, advanced: true, help: "El dueño de las tablas; vacío: el del usuario."}
source: "dlt.sources.sql_database:sql_table"
args:
<<: *sql_args
credentials: "oracle+oracledb://{user:url}:{password:url}@{host}:{port}/?service_name={database:url}"
listing:
<<: *sql_listing
args:
credentials: "oracle+oracledb://{user:url}:{password:url}@{host}:{port}/?service_name={database:url}"
schema: "{schema}"
reflection_level: minimal
sqlite:
group: database
title: Archivo SQLite
description: Una tabla de un archivo .db o .sqlite en el servidor.
icon: database
fields:
path: {label: Archivo, type: server_file, placeholder: "/datos/hospital.db", help: "Pulse «Examinar…» o escriba la ruta del archivo en el servidor."}
table: {label: Tabla, type: table, help: "Pulse «Probar conexión» para ver las tablas."}
chunk_size: {label: Filas por lote, type: number, default: 100, advanced: true}
columns: {label: Columnas, type: columns, required: false, advanced: true, help: "Solo estas columnas; vacío: todas."}
source: "dlt.sources.sql_database:sql_table"
args:
credentials: "sqlite:///{path:path}"
table: "{table}"
chunk_size: "{chunk_size}"
included_columns: "{columns}"
listing:
kind: tables
source: "dlt.sources.sql_database:sql_database"
args: {credentials: "sqlite:///{path:path}", reflection_level: minimal}
upload:
group: files
title: Desde mi computadora
description: Suba archivos o una carpeta completa; quedan guardados en el servidor.
icon: upload
fields: &file_fields
folder: {label: Archivos, type: upload, help: "Arrastre aquí los archivos o elija una carpeta."}
read_as: {label: Qué contienen, type: format, default: "persistance.readers:read_bytes"}
pattern: {label: Qué archivos tomar, default: "**/*", advanced: true, help: "Por ejemplo *.pdf para solo los PDF; **/* toma todos, también en subcarpetas."}
source: "dlt.sources.filesystem:filesystem"
args: &file_args
bucket_url: "{folder}"
file_glob: "{pattern}"
then: "{read_as}"
listing: {kind: rows}
server_folder:
group: files
title: Carpeta del servidor
description: Una carpeta que el servidor ya tiene (una unidad compartida montada).
icon: folder
fields:
<<: *file_fields
folder: {label: Carpeta, type: folder, help: "Elija la carpeta; solo se muestran las que el administrador habilitó."}
source: "dlt.sources.filesystem:filesystem"
args: *file_args
then: "{read_as}"
listing: {kind: rows}
path_or_url:
group: files
title: Ruta o enlace
description: Escriba la ruta de una carpeta o el enlace a un archivo en internet.
icon: link
fields:
<<: *file_fields
folder: {label: Ruta o enlace, type: url, placeholder: "/datos/reportes o https://sitio/archivo.csv", help: "Una carpeta del servidor, o la dirección de un archivo."}
source: "dlt.sources.filesystem:filesystem"
args: *file_args
then: "{read_as}"
listing: {kind: rows}
network_share:
group: files
title: Carpeta compartida de la red
description: Una carpeta de Windows compartida en la red del hospital (\\servidor\carpeta).
icon: folder-network
fields:
host: {label: Servidor, placeholder: "archivo.hospital.local"}
share: {label: Carpeta compartida, placeholder: "Reportes", help: "Lo que va después del nombre del servidor: \\\\servidor\\Reportes."}
path: {label: Subcarpeta, required: false, placeholder: "2026/citologias"}
user: {label: Usuario, help: "Con dominio si lo pide: HOSPITAL\\usuario."}
password: {label: Contraseña, type: password}
read_as: {label: Qué contienen, type: format, default: "persistance.readers:read_bytes"}
pattern: {label: Qué archivos tomar, default: "**/*", advanced: true}
source: "persistance.readers:fsspec_files"
args:
url: "smb://{host}/{share:path}/{path:path}"
file_glob: "{pattern}"
storage_options: {username: "{user}", password: "{password}"}
then: "{read_as}"
listing: {kind: rows}
sftp:
group: files
title: Servidor SFTP
description: Archivos en otro equipo por SFTP (SSH).
icon: server
fields:
host: {label: Servidor}
port: {label: Puerto, type: number, default: 22, advanced: true}
path: {label: Carpeta, placeholder: "/reportes"}
user: {label: Usuario}
password: {label: Contraseña, type: password}
read_as: {label: Qué contienen, type: format, default: "persistance.readers:read_bytes"}
pattern: {label: Qué archivos tomar, default: "**/*", advanced: true}
source: "dlt.sources.filesystem:filesystem"
args:
bucket_url: "sftp://{host}/{path:path}"
file_glob: "{pattern}"
credentials: {sftp_port: "{port}", sftp_username: "{user}", sftp_password: "{password}"}
then: "{read_as}"
listing: {kind: rows}
onedrive:
group: cloud
title: OneDrive
description: Una carpeta de su OneDrive (Microsoft 365).
icon: onedrive
fields:
account: {label: Cuenta de Microsoft, type: oauth, provider: microsoft, help: "Inicie sesión con la cuenta que tiene la carpeta."}
folder: {label: Carpeta, required: false, placeholder: "Reportes/2026", help: "La ruta dentro de su OneDrive; vacío: todo."}
read_as: {label: Qué contienen, type: format, default: "persistance.readers:read_bytes"}
pattern: {label: Qué archivos tomar, default: "**/*", advanced: true}
source: "persistance.readers:fsspec_files"
args: # the signed-in user's own drive, by its id (msgraphfs single-drive mode)
url: "msgd://{folder:path}"
file_glob: "{pattern}"
storage_options:
drive_id: "{account[drive_id]}"
oauth2_client_params: "{account[oauth2_client_params]}"
then: "{read_as}"
listing: {kind: rows}
sharepoint:
group: cloud
title: SharePoint
description: Una biblioteca de documentos de un sitio de SharePoint.
icon: sharepoint
fields:
account: {label: Cuenta de Microsoft, type: oauth, provider: microsoft}
site: {label: Sitio, placeholder: "Laboratorio", help: "El nombre del sitio, como aparece en su dirección."}
library: {label: Biblioteca, default: Documentos compartidos, help: "Por lo general, «Documentos compartidos»."}
folder: {label: Carpeta, required: false, placeholder: "Reportes/2026"}
read_as: {label: Qué contienen, type: format, default: "persistance.readers:read_bytes"}
pattern: {label: Qué archivos tomar, default: "**/*", advanced: true}
source: "persistance.readers:fsspec_files"
args:
url: "msgd://{site:url}/{library:url}/{folder:path}"
file_glob: "{pattern}"
storage_options: {oauth2_client_params: "{account[oauth2_client_params]}"}
then: "{read_as}"
listing: {kind: rows}
google_drive:
group: cloud
title: Google Drive
description: Una carpeta de Google Drive.
icon: google-drive
fields:
account: {label: Cuenta de Google, type: oauth, provider: google, help: "Inicie sesión con la cuenta que tiene la carpeta."}
folder: {label: Enlace a la carpeta, type: url, default: root, placeholder: "https://drive.google.com/drive/folders/…", help: "Abra la carpeta en Drive y copie la dirección; vacío: Mi unidad."}
read_as: {label: Qué contienen, type: format, default: "persistance.readers:read_bytes"}
pattern: {label: Qué archivos tomar, default: "**/*", advanced: true}
source: "dlt.sources.filesystem:filesystem"
args:
bucket_url: "gdrive://{folder:last}"
file_glob: "{pattern}"
credentials: "{account[credentials]}"
then: "{read_as}"
listing: {kind: rows}
s3:
group: cloud
title: Amazon S3 o compatible
description: Un bucket de S3, MinIO u otro almacenamiento compatible con S3.
icon: cloud
fields:
bucket: {label: Bucket y carpeta, placeholder: "mi-bucket/reportes"}
access_key: {label: Clave de acceso (Access key ID)}
secret_key: {label: Clave secreta, type: password}
endpoint: {label: Dirección del servicio, required: false, advanced: true, placeholder: "https://minio.hospital.local", help: "Solo si no es Amazon (MinIO y similares)."}
read_as: {label: Qué contienen, type: format, default: "persistance.readers:read_bytes"}
pattern: {label: Qué archivos tomar, default: "**/*", advanced: true}
source: "dlt.sources.filesystem:filesystem"
args:
bucket_url: "s3://{bucket:path}"
file_glob: "{pattern}"
credentials: {aws_access_key_id: "{access_key}", aws_secret_access_key: "{secret_key}", endpoint_url: "{endpoint}"}
then: "{read_as}"
listing: {kind: rows}
azure_blob:
group: cloud
title: Azure Blob Storage
description: Un contenedor de Azure Storage.
icon: cloud
fields:
account: {label: Cuenta de almacenamiento}
key: {label: Clave de la cuenta, type: password}
container: {label: Contenedor y carpeta, placeholder: "reportes/2026"}
read_as: {label: Qué contienen, type: format, default: "persistance.readers:read_bytes"}
pattern: {label: Qué archivos tomar, default: "**/*", advanced: true}
source: "dlt.sources.filesystem:filesystem"
args:
bucket_url: "az://{container:path}"
file_glob: "{pattern}"
credentials: {azure_storage_account_name: "{account}", azure_storage_account_key: "{key}"}
then: "{read_as}"
listing: {kind: rows}
gcs:
group: cloud
title: Google Cloud Storage
description: Un bucket de Google Cloud Storage, con una cuenta de servicio.
icon: cloud
fields:
bucket: {label: Bucket y carpeta, placeholder: "mi-bucket/reportes"}
service_account: {label: Cuenta de servicio (JSON), type: password, help: "Pegue el contenido del archivo JSON de la cuenta de servicio."}
read_as: {label: Qué contienen, type: format, default: "persistance.readers:read_bytes"}
pattern: {label: Qué archivos tomar, default: "**/*", advanced: true}
source: "dlt.sources.filesystem:filesystem"
args:
bucket_url: "gs://{bucket:path}"
file_glob: "{pattern}"
credentials: "{service_account}"
then: "{read_as}"
listing: {kind: rows}
rest_api:
group: web
title: API web
description: Un sistema que entrega sus datos en JSON por internet.
icon: web
fields:
base_url: {label: Dirección base, type: url, placeholder: "https://laboratorio.example/api/"}
path: {label: Recurso, placeholder: "resultados", help: "La parte de la dirección que entrega los datos."}
token: {label: Token de acceso, type: password, required: false, help: "Si el sistema pide un token (Bearer)."}
source: "dlt.sources.rest_api:rest_api_source"
args:
config:
client:
base_url: "{base_url}"
auth: {type: bearer, token: "{token}"}
resources: ["{path}"]
listing: {kind: rows}
fhir_door:
group: web
title: Envío FHIR
description: Un sistema que envía paquetes FHIR a la plataforma (POST /{dominio}/fhir).
icon: fhir
fields:
sender: {label: Quién envía, placeholder: "synthea", help: "El nombre con que el sistema se identifica al enviar."}
source: "persistance.readers:fhir_inbox"
args: {sender: "{sender}"}
primary_key: [id]
listing: {kind: rows}
-42
View File
@@ -1,42 +0,0 @@
"""TEA clinical parameters: the one place they are set. dbt reads them as vars, the measures
import them. Codes are the platform's (core.catalog)."""
# The screening cohort: children whose first M-CHAT is at this age (completed months, from
# the age in months rounded to one decimal), in these windows.
AGE_GROUPS = [(16, 23), (24, 29), (30, 36)]
DAYS_PER_MONTH = 30.4375
FOLLOW_UP_WINDOWS = [1, 3, 6, 12] # months: the list's windows, as CaCu's and CaMa's
# A neurology note with one of these confirms the diagnosis (ICD-10, with the dot).
CONFIRMING_ICD10 = ["F84.0"]
NEUROLOGY = "pediatric_neurology" # the specialty of the notes the screening counts
# ADOS-2 calibrated severity (CSS): the lowest total reaching CSS 2..10, by module and
# algorithm (Module 1) and whether the child is under five. Items score 0 to 3; a 3 counts
# as 2. The values are approximate published ones, kept as data.
ADOS2_CSS = {
("module_1", "few_to_no_words", True): [4, 7, 11, 14, 16, 18, 20, 22, 24],
("module_1", "few_to_no_words", False): [6, 9, 12, 15, 17, 19, 21, 23, 25],
("module_1", "some_words", True): [3, 5, 8, 10, 12, 14, 16, 18, 20],
("module_1", "some_words", False): [4, 6, 9, 11, 13, 15, 17, 19, 21],
("module_2", None, True): [3, 5, 7, 9, 10, 12, 14, 16, 18],
("module_2", None, False): [3, 6, 8, 10, 11, 13, 15, 17, 19],
("module_3", None, None): [2, 4, 7, 8, 9, 11, 13, 15, 17],
}
# Classification by CSS: below 3 no spectrum, 3-4 autism spectrum, 5 or more autism.
ADOS2_CLASSIFICATION = [("non_spectrum", 3), ("autism_spectrum", 5), ("autism", None)]
# The Module 1 items that only the "few to no words" algorithm prints.
FEW_TO_NO_WORDS_ITEMS = ["joint_attention_response", "intonation"]
SOCIAL_AFFECT_ITEMS = [
"vocalization_directed", "pointing", "gestures", "unusual_eye_contact", "facial_expressions",
"gaze_integration", "shared_enjoyment", "response_to_name", "ignoring", "requesting",
"showing", "joint_attention_initiation", "joint_attention_response",
"social_overtures_quality", "social_overtures_caregiver", "reciprocal_communication",
"rapport_quality",
] # fmt: skip
RESTRICTED_REPETITIVE_ITEMS = ["intonation", "stereotyped_language", "unusual_sensory_interest",
"hand_finger_mannerisms", "repetitive_interests"] # fmt: skip
def dbt_vars() -> dict:
"""What dbt reads (`var('tea')`)."""
return {k.lower(): v for k, v in globals().items() if k.isupper() and k != "ADOS2_CSS"}
-48
View File
@@ -1,48 +0,0 @@
"""ADOS-2 scoring (pure): the calibrated severity score (CSS) and classification of one
evaluation from its items (core.tea). The total is the sum of the items given, a 3 counting
as 2; an evaluation without items in either domain is not scored."""
from datetime import date
from core import tea
TODDLER_BANDS = {True: (10, 16), False: (8, 14)} # 20 months or younger: (mild, severe) totals
def algorithm(row: dict) -> str | None:
"""Module 1's algorithm, from the items its report prints."""
if row.get("module") != "module_1":
return None
printed = any(row.get(i) is not None for i in tea.FEW_TO_NO_WORDS_ITEMS)
return "few_to_no_words" if printed else "some_words"
def total(row: dict) -> int | None:
def domain(items: list[str]) -> list[int]:
return [min(int(row[i]), 2) for i in items if row.get(i) is not None]
social = domain(tea.SOCIAL_AFFECT_ITEMS)
restricted = domain(tea.RESTRICTED_REPETITIVE_ITEMS)
return sum(social) + sum(restricted) if social and restricted else None
def score(row: dict, birth: date | None) -> tuple[int | None, str | None]:
"""(CSS, classification); (None, None) when it can't be scored."""
found, module = total(row), row.get("module")
if found is None or module is None:
return None, None
months = (row["evaluation_date"] - birth).days / tea.DAYS_PER_MONTH if birth else None
if module == "toddler":
mild, severe = TODDLER_BANDS[months is not None and months <= 20]
band = "severe_concern" if found >= severe else (
"mild_to_moderate_concern" if found >= mild else "non_spectrum") # fmt: skip
return None, band
under_five = months is not None and months < 60
keys = [(module, algorithm(row), under_five), (module, algorithm(row), None),
(module, None, under_five), (module, None, None)] # fmt: skip
cuts = next((tea.ADOS2_CSS[k] for k in keys if k in tea.ADOS2_CSS), None)
if cuts is None:
return None, None
css = 1 + sum(c <= found for c in cuts)
label = next(n for n, below in tea.ADOS2_CLASSIFICATION if below is None or css < below)
return css, label
-120
View File
@@ -1,120 +0,0 @@
"""What the EEG–ADOS-2 association relates (pure configuration, models.tea.association):
each EEG biomarker's deviation from its age curve (z) in a zone, against the ADOS-2 items
that zone is linked to, or against the calibrated severity (CSS).
An item counts as altered at ALTERED or more (its algorithm score: 0 to 2, a 3 counting as
2, and 7, 8 or 9, "not applicable", as 0); the CSS at CSS_HIGH or more. Items are numbered
as the old platform numbered them, which names each outcome `ados2_item_NN`."""
from core import tea
# The 22 items, in their number's order, and the modules that administer each.
ITEMS = {
1: ("vocalization_directed", ("toddler", "module_1")),
2: ("pointing", ("toddler", "module_1", "module_2")),
3: ("gestures", ("toddler", "module_1", "module_2")),
4: ("unusual_eye_contact", ("toddler", "module_1", "module_2")),
5: ("facial_expressions", ("toddler", "module_1", "module_2")),
6: ("gaze_integration", ("toddler", "module_1")),
7: ("shared_enjoyment", ("toddler", "module_1", "module_2")),
8: ("response_to_name", ("toddler",)),
9: ("ignoring", ("toddler",)),
10: ("requesting", ("toddler",)),
11: ("showing", ("toddler", "module_1", "module_2")),
12: ("joint_attention_initiation", ("toddler", "module_1", "module_2")),
13: ("joint_attention_response", ("toddler", "module_1")),
14: ("social_overtures_quality", ("toddler", "module_1", "module_2")),
15: ("social_overtures_caregiver", ("toddler",)),
16: ("reciprocal_communication", ("module_2",)),
17: ("rapport_quality", ("toddler", "module_2")),
18: ("intonation", ("toddler", "module_1")),
19: ("stereotyped_language", ("module_1", "module_2")),
20: ("unusual_sensory_interest", ("toddler", "module_1", "module_2")),
21: ("hand_finger_mannerisms", ("toddler", "module_1", "module_2")),
22: ("repetitive_interests", ("toddler", "module_1", "module_2")),
}
assert [n for n, _ in ITEMS.values()] == tea.SOCIAL_AFFECT_ITEMS + tea.RESTRICTED_REPETITIVE_ITEMS
# The items each zone's spikes are related to.
ZONE_ITEMS = {
"frontal_left": (1, 2, 3, 9, 10, 11, 12, 14, 15, 16),
"frontal_right": (4, 5, 7, 14, 22),
"frontal_midline": (6, 11, 12, 13, 14),
"central": (21,),
"parietal": (6, 13, 20),
"temporal_left": (1, 16, 18, 19),
"temporal_right": (4, 5, 8),
"occipital": (4, 20),
}
SPINDLE_ZONES = ("frontal_left", "frontal_right", "frontal_midline", "central", "parietal")
RHYTHM_ITEMS = (20, 22)
# Each biomarker's EEG metric (models.tea.eeg.biomarkers.CODES).
BIOMARKERS = {
"spikes": "paroxysmal_spikes",
"spindles": "spindles_n2",
"posterior_rhythm": "posterior_rhythm",
"gradient": "anteroposterior_gradient",
}
ZONED = ("spikes", "spindles")
CSS = "CSS"
CSS_HIGH = 8
ALTERED = 1
NOT_APPLICABLE = (7, 8, 9)
# Below this many children with item scores the association is fitted on the CSS only.
MIN_ITEM_CHILDREN = 10
ADJUST = ("age_months", "module")
def item_code(n: int) -> str:
return f"ados2_item_{n:02d}"
def pairs(level: str) -> list[dict]:
"""Every (biomarker, zone, predictor, outcome) the association fits at `level`: `item`
(each zone against its items) or `domain` (against the CSS)."""
def outcomes(numbers) -> list[tuple[str, object]]:
return [("item", n) for n in numbers] if level == "item" else [("domain", CSS)]
out = [
{
"biomarker": "spikes",
"zone": zone,
"predictor": f"z_spikes_{zone}",
"kind": k,
"outcome": o,
}
for zone, numbers in ZONE_ITEMS.items()
for k, o in outcomes(numbers)
]
out += [
{
"biomarker": "spindles",
"zone": zone,
"predictor": f"z_spindles_{zone}",
"kind": "domain",
"outcome": CSS,
}
for zone in SPINDLE_ZONES
]
out += [
{
"biomarker": "posterior_rhythm",
"zone": "posterior",
"predictor": "z_posterior_rhythm",
"kind": k,
"outcome": o,
}
for k, o in outcomes(RHYTHM_ITEMS)
]
out.append(
{
"biomarker": "gradient",
"zone": "global",
"predictor": "z_gradient",
"kind": "domain",
"outcome": CSS,
}
)
return out
+11
View File
@@ -0,0 +1,11 @@
import sqlalchemy.orm as orm
from sqlmodel import SQLModel
registry = orm.registry()
class TeaModel(SQLModel, registry=registry):
"""Base class for every TEA table. Own SQLAlchemy registry/metadata,
same as CaCu/CaMa, so each domain's Alembic environment can target its
own metadata independently.
"""
+299
View File
@@ -0,0 +1,299 @@
# -*- coding: utf-8 -*-
"""Vocabularios controlados del proyecto TEA.
Capa Core: sin importaciones de infraestructura. Seguro de importar
desde cualquier módulo de src/.
Generado desde spec/tablas_TEA.md. No editar a mano.
"""
from enum import Enum
class Parentesco(str, Enum):
"""pac_parentesco in table pacientes."""
HIJO = "HIJO"
HIJA = "HIJA"
HIJASTRO = "HIJASTRO"
TUTELADO = "TUTELADO"
OTRO = "OTRO"
class SexoBiologico(str, Enum):
"""pac_sexo in table pacientes."""
F = "F"
M = "M"
I = "I"
class Especialidad(str, Enum):
"""ord_especialidad in table ordenes_estudio."""
NEUROLOGIA_PEDIATRICA = "NEUROLOGIA_PEDIATRICA"
PEDIATRIA = "PEDIATRIA"
PSICOLOGIA = "PSICOLOGIA"
PSIQUIATRIA_INFANTIL = "PSIQUIATRIA_INFANTIL"
AUDIOLOGIA = "AUDIOLOGIA"
MEDICINA_FAMILIAR = "MEDICINA_FAMILIAR"
ENFERMERIA = "ENFERMERIA"
OTRO = "OTRO"
class TipoEstudio(str, Enum):
"""ord_tipo_estudio in table ordenes_estudio."""
ELECTROENCEFALOGRAMA = "ELECTROENCEFALOGRAMA"
POTENCIALES_EVOCADOS_AUDITIVOS = "POTENCIALES_EVOCADOS_AUDITIVOS"
EVALUACION_PSICOLOGICA_TEA = "EVALUACION_PSICOLOGICA_TEA"
OTRO = "OTRO"
class EstatusEstudio(str, Enum):
"""ord_estatus in table ordenes_estudio."""
SOLICITADO = "SOLICITADO"
EN_PROCESO = "EN_PROCESO"
REALIZADO = "REALIZADO"
RESULTADO_DISPONIBLE = "RESULTADO_DISPONIBLE"
CANCELADO = "CANCELADO"
NO_ACUDIO = "NO_ACUDIO"
class VentanaMadurativa(str, Enum):
"""ord_ventana_madurativa in table ordenes_estudio."""
V1_16_23 = "V1_16_23"
V2_24_30 = "V2_24_30"
V3_31_36 = "V3_31_36"
FUERA_DE_RANGO = "FUERA_DE_RANGO"
class TipoNota(str, Enum):
"""nm_tipo_nota in table nota_medica."""
PRIMERA_VEZ = "PRIMERA_VEZ"
TAMIZAJE = "TAMIZAJE"
INTERPRETACION_EEG = "INTERPRETACION_EEG"
TRATAMIENTO = "TRATAMIENTO"
SEGUIMIENTO = "SEGUIMIENTO"
INTERCONSULTA = "INTERCONSULTA"
URGENCIA = "URGENCIA"
OTRO = "OTRO"
class Pronostico(str, Enum):
"""nm_pronostico in table nota_medica."""
BUENO = "BUENO"
RESERVADO = "RESERVADO"
MALO = "MALO"
NO_ESPECIFICADO = "NO_ESPECIFICADO"
class InstrumentoTamizaje(str, Enum):
"""psi_instrumento_tamizaje in table evaluacion_psicologica."""
M_CHAT_R = "M_CHAT_R"
M_CHAT_RF = "M_CHAT_RF"
OTRO = "OTRO"
NO_REGISTRADO = "NO_REGISTRADO"
class NivelRiesgoTamizaje(str, Enum):
"""psi_tamizaje_riesgo in table evaluacion_psicologica."""
BAJO = "BAJO"
MEDIO = "MEDIO"
ALTO = "ALTO"
NO_APLICA = "NO_APLICA"
class ModuloAdos2(str, Enum):
"""psi_ados2_modulo in table evaluacion_psicologica."""
TODDLER = "TODDLER"
MODULO_1 = "MODULO_1"
MODULO_2 = "MODULO_2"
NO_REGISTRADO = "NO_REGISTRADO"
class ClasificacionAdos2(str, Enum):
"""psi_ados2_clasificacion in table evaluacion_psicologica."""
NO_TEA = "NO_TEA"
ESPECTRO_AUTISTA = "ESPECTRO_AUTISTA"
AUTISMO = "AUTISMO"
PREOCUPACION_LEVE_MODERADA = "PREOCUPACION_LEVE_MODERADA"
PREOCUPACION_SEVERA = "PREOCUPACION_SEVERA"
class GradoHipoacusia(str, Enum):
"""pea_grado_hipoacusia in table potenciales_evocados_auditivos."""
NORMAL = "NORMAL"
LEVE = "LEVE"
MODERADA = "MODERADA"
SEVERA = "SEVERA"
PROFUNDA = "PROFUNDA"
NO_CONCLUYENTE = "NO_CONCLUYENTE"
class FuenteInterpretacionEeg(str, Enum):
"""eeg_fuente_interpretacion in table eeg_estudio."""
REPORTE_NEUROPEDIATRIA = "REPORTE_NEUROPEDIATRIA"
NOTA_MEDICA = "NOTA_MEDICA"
AMBAS = "AMBAS"
NINGUNA = "NINGUNA"
class EstadoRegistroEeg(str, Enum):
"""eeg_estado_registro in table eeg_estudio."""
VIGILIA = "VIGILIA"
SUENO_ESPONTANEO = "SUENO_ESPONTANEO"
SUENO_INDUCIDO = "SUENO_INDUCIDO"
MIXTO = "MIXTO"
NO_ESPECIFICADO = "NO_ESPECIFICADO"
class CalidadTecnicaEeg(str, Enum):
"""eeg_calidad_tecnica in table eeg_estudio."""
SATISFACTORIA = "SATISFACTORIA"
LIMITADA_POR_ARTEFACTO = "LIMITADA_POR_ARTEFACTO"
LIMITADA_POR_COLABORACION = "LIMITADA_POR_COLABORACION"
NO_VALORABLE = "NO_VALORABLE"
NO_ESPECIFICADA = "NO_ESPECIFICADA"
class Simetria(str, Enum):
"""eeg_simetria in table eeg_estudio."""
SIMETRICO = "SIMETRICO"
ASIMETRICO_IZQUIERDO = "ASIMETRICO_IZQUIERDO"
ASIMETRICO_DERECHO = "ASIMETRICO_DERECHO"
NO_ESPECIFICADA = "NO_ESPECIFICADA"
class TipoGrafoelemento(str, Enum):
"""eeg_tipo_grafoelemento in table eeg_estudio."""
NINGUNO = "NINGUNO"
ESPIGA = "ESPIGA"
ONDA_AGUDA = "ONDA_AGUDA"
COMPLEJO_ESPIGA_ONDA = "COMPLEJO_ESPIGA_ONDA"
COMPLEJO_POLIESPIGA_ONDA = "COMPLEJO_POLIESPIGA_ONDA"
PUNTA_ONDA_LENTA = "PUNTA_ONDA_LENTA"
DESCARGA_RITMICA = "DESCARGA_RITMICA"
OTRO = "OTRO"
class DistribucionAnormalidad(str, Enum):
"""eeg_distribucion_anormalidad in table eeg_estudio."""
FOCAL = "FOCAL"
MULTIFOCAL = "MULTIFOCAL"
GENERALIZADA = "GENERALIZADA"
LATERALIZADA = "LATERALIZADA"
NO_ESPECIFICADA = "NO_ESPECIFICADA"
class Lentificacion(str, Enum):
"""eeg_lentificacion in table eeg_estudio."""
NINGUNA = "NINGUNA"
FOCAL = "FOCAL"
GENERALIZADA = "GENERALIZADA"
INTERMITENTE = "INTERMITENTE"
class RespuestaFotoestimulacion(str, Enum):
"""eeg_respuesta_fotoestimulacion in table eeg_estudio."""
NORMAL = "NORMAL"
RESPUESTA_FOTOPAROXISTICA = "RESPUESTA_FOTOPAROXISTICA"
SIN_RESPUESTA = "SIN_RESPUESTA"
NO_PRACTICADA = "NO_PRACTICADA"
class ConclusionEeg(str, Enum):
"""eeg_conclusion_categoria in table eeg_estudio."""
NORMAL_PARA_LA_EDAD = "NORMAL_PARA_LA_EDAD"
NORMAL_CON_VARIANTES = "NORMAL_CON_VARIANTES"
ANORMAL_EPILEPTIFORME = "ANORMAL_EPILEPTIFORME"
ANORMAL_NO_EPILEPTIFORME = "ANORMAL_NO_EPILEPTIFORME"
ANORMAL_MIXTO = "ANORMAL_MIXTO"
NO_CONCLUYENTE = "NO_CONCLUYENTE"
class FuenteAntecedenteMaterno(str, Enum):
"""amg_fuente_antecedente in table antecedentes_maternos_gestacion."""
EXPEDIENTE_MATERNO = "EXPEDIENTE_MATERNO"
INTERROGATORIO_NM11 = "INTERROGATORIO_NM11"
AMBAS = "AMBAS"
NO_LOCALIZADO = "NO_LOCALIZADO"
class CategoriaPesoMaterno(str, Enum):
"""amg_categoria_peso_materno in table antecedentes_maternos_gestacion."""
BAJO_PESO = "BAJO_PESO"
NORMAL = "NORMAL"
SOBREPESO = "SOBREPESO"
OBESIDAD_I = "OBESIDAD_I"
OBESIDAD_II = "OBESIDAD_II"
OBESIDAD_III = "OBESIDAD_III"
NO_REGISTRADA = "NO_REGISTRADA"
class TipoEmbarazo(str, Enum):
"""amg_embarazo_multiple in table antecedentes_maternos_gestacion."""
UNICO = "UNICO"
GEMELAR = "GEMELAR"
TRIPLE_O_MAS = "TRIPLE_O_MAS"
NO_REGISTRADO = "NO_REGISTRADO"
class TrastornoHipertensivoGestacion(str, Enum):
"""amg_hipertension_preeclampsia in table antecedentes_maternos_gestacion."""
NINGUNO = "NINGUNO"
HIPERTENSION_GESTACIONAL = "HIPERTENSION_GESTACIONAL"
PREECLAMPSIA = "PREECLAMPSIA"
ECLAMPSIA = "ECLAMPSIA"
SINDROME_HELLP = "SINDROME_HELLP"
NO_REGISTRADO = "NO_REGISTRADO"
class VolumenLiquidoAmniotico(str, Enum):
"""amg_liquido_amniotico in table antecedentes_maternos_gestacion."""
NORMAL = "NORMAL"
OLIGOHIDRAMNIOS = "OLIGOHIDRAMNIOS"
POLIHIDRAMNIOS = "POLIHIDRAMNIOS"
NO_REGISTRADO = "NO_REGISTRADO"
class FuenteAntecedenteNeonatal(str, Enum):
"""pnn_fuente_antecedente in table parto_neonatal."""
NOTA_RECIEN_NACIDO = "NOTA_RECIEN_NACIDO"
NOTA_RESOLUCION_OBSTETRICA = "NOTA_RESOLUCION_OBSTETRICA"
INTERROGATORIO_NM11 = "INTERROGATORIO_NM11"
AMBAS = "AMBAS"
NO_LOCALIZADA = "NO_LOCALIZADA"
class TipoParto(str, Enum):
"""pnn_tipo_parto in table parto_neonatal."""
VAGINAL_ESPONTANEO = "VAGINAL_ESPONTANEO"
VAGINAL_INSTRUMENTADO = "VAGINAL_INSTRUMENTADO"
CESAREA_ELECTIVA = "CESAREA_ELECTIVA"
CESAREA_URGENCIA = "CESAREA_URGENCIA"
NO_REGISTRADO = "NO_REGISTRADO"
class ComplicacionIntraparto(str, Enum):
"""pnn_complicacion_tipo in table parto_neonatal."""
NINGUNA = "NINGUNA"
HIPOXIA = "HIPOXIA"
ISQUEMIA = "ISQUEMIA"
TRAUMA_OBSTETRICO = "TRAUMA_OBSTETRICO"
CIRCULAR_DE_CORDON = "CIRCULAR_DE_CORDON"
SUFRIMIENTO_FETAL_AGUDO = "SUFRIMIENTO_FETAL_AGUDO"
OTRA = "OTRA"
class ClasificacionEdadGestacional(str, Enum):
"""pnn_clasificacion_eg in table parto_neonatal."""
PRETERMINO_EXTREMO = "PRETERMINO_EXTREMO"
MUY_PRETERMINO = "MUY_PRETERMINO"
PRETERMINO_TARDIO = "PRETERMINO_TARDIO"
TERMINO = "TERMINO"
POSTERMINO = "POSTERMINO"
NO_DETERMINADA = "NO_DETERMINADA"
class TamanoParaEdadGestacional(str, Enum):
"""pnn_tamano_para_eg in table parto_neonatal."""
PEQUENO = "PEQUENO"
ADECUADO = "ADECUADO"
GRANDE = "GRANDE"
NO_DETERMINADO = "NO_DETERMINADO"
-104
View File
@@ -1,104 +0,0 @@
"""TEA's follow-up list (pure): the children of the screening cohort active in the window, where
each stands on the route by the cut-off day, and their EEG.
- status (the route): mchat_only, psychology (ADOS-2), neuropediatrics (a neurology note), eeg
(a good EEG after it);
- case: confirmed (the neurologist confirmed TEA), not_confirmed, or in_process;
- EEG: the study EEG is her first valid one known by the cut-off, else her latest; its status
is no_valid_eeg without a valid one, abnormal when any of its metrics falls outside the age
curve's band (its alterations, each `<metric>:<above|below>`), else normal.
A child is on the list when any step of hers happened within the window."""
from datetime import date
from core import tea
from core.measures import as_day
from core.tea import ados2
WINDOWS = tea.FOLLOW_UP_WINDOWS
SORTS = ("-recent",)
DEFAULT_HORIZON = None
STATUS_SYSTEM = "tea-follow-up-status"
PROCEDURES: tuple[str, ...] = ()
REPORT_FACTS: dict[str, str] = {}
STEPS = (("psychology_date", "psychology"), ("neuro_date", "neuropediatrics"),
("eeg_date", "eeg")) # fmt: skip
DATES = ("mchat_date", "psychology_date", "neuro_date", "confirmed_date", "not_confirmed_date",
"eeg_date") # fmt: skip
def _by(day, cutoff: date) -> date | None:
found = as_day(day)
return found if found is not None and found <= cutoff else None
def stage(row: dict, cutoff: date) -> str:
reached = "mchat_only"
for column, name in STEPS:
if _by(row.get(column), cutoff):
reached = name
return reached
def case(row: dict, cutoff: date) -> str:
if _by(row.get("confirmed_date"), cutoff):
return "confirmed"
if _by(row.get("not_confirmed_date"), cutoff):
return "not_confirmed"
return "in_process"
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
"""From each child's screening row joined to her EEGs and their metrics outside the band
(one row per child, EEG and such metric), who is on the list, most recent step first."""
children: dict[str, dict] = {}
eegs: dict[str, dict[str, dict]] = {}
for row in rows:
person = row["person_id"]
if not _by(row.get("mchat_date"), cutoff):
continue
children.setdefault(person, row)
studied = _by(row.get("eeg_study_date"), cutoff)
if row.get("eeg_id") and studied:
eeg = eegs.setdefault(person, {}).setdefault(
row["eeg_id"], {"date": studied, "valid": row.get("valid"), "altered": set()}
)
if row.get("metric") and row.get("outside"):
side = "above" if row["outside"] > 0 else "below"
eeg["altered"].add(f"{row['metric']}:{side}")
out = []
for person, row in children.items():
steps = [d for c in DATES if (d := _by(row.get(c), cutoff))]
recent = max(steps)
if recent < start:
continue
mine = sorted(eegs.get(person, {}).values(), key=lambda e: e["date"])
valid = [e for e in mine if e["valid"]]
study = valid[0] if valid else (mine[-1] if mine else None)
if not valid:
eeg_status, altered = "no_valid_eeg", []
else:
altered = sorted(study["altered"])
eeg_status = "abnormal" if altered else "normal"
css = None
if row.get("module") and as_day(row.get("evaluation_date")):
evaluated = {**row, "evaluation_date": as_day(row["evaluation_date"])}
css, _ = ados2.score(evaluated, as_day(row.get("birth_date")))
out.append({
"person_id": person, "birth_date": row.get("birth_date"),
"status": stage(row, cutoff), "priority": None, "recent": recent,
"age_group": row.get("age_group"), "case": case(row, cutoff),
"eeg_status": eeg_status, "alterations": altered,
"last_eeg": mine[-1]["date"] if mine else None,
"mchat_score": row.get("score"), "ados2_css": css,
}) # fmt: skip
return sorted(out, key=lambda r: (-r["recent"].toordinal(), r["person_id"]))
def status(row: dict, cutoff: date) -> None:
"""A child's status exists only on the list."""
return None
def ordered(rows: list[dict], sort: str, risks: dict, horizon) -> list[dict]:
return rows
-59
View File
@@ -1,59 +0,0 @@
"""TEA's measures (`core.measures` evaluates them), over gold's screening chain: one row per
child of the cohort (`gold.tea_screening`) with the day she reached each step, and her EEGs
(`gold.tea_eegs`).
A child is on the books from her first M-CHAT until the period after her chain ended with a
good EEG; in a period she is in the latest step, and diagnosis state, reached by its end."""
from core.measures import (
AtEnd,
Composition,
Measure,
StatusComposition,
StatusDuration,
StatusProportion,
as_day,
reached,
)
DIAGNOSIS = AtEnd("mchat_date", "eeg_date", (
("in_process", "mchat_date"), ("not_confirmed", "not_confirmed_date"),
("confirmed", "confirmed_date"),
)) # fmt: skip
STEPS = AtEnd("mchat_date", "eeg_date", (
("mchat_only", "mchat_date"), ("psychology", "psychology_date"),
("neuropediatrics", "neuro_date"), ("eeg", "eeg_date"),
)) # fmt: skip
AGE = ("age_group", lambda row, p: row["age_group"])
CONFIRMED = lambda row, state, p: state == "confirmed" # noqa: E731
MEASURES = {m.id: m for m in [
Measure("M21_DIAGNOSTICADOS_CON_EEG", "Pacientes con diagnóstico de TEA con EEG",
"screening",
StatusProportion(DIAGNOSIS, CONFIRMED,
lambda row, s, p: reached(row, "eeg_date", p), strata=(AGE,)),
"increase"),
Measure("M22_DIAGNOSTICADOS_SIN_EEG", "Pacientes con diagnóstico de TEA sin EEG",
"screening",
StatusProportion(DIAGNOSIS, CONFIRMED,
lambda row, s, p: not reached(row, "eeg_date", p), strata=(AGE,)),
"decrease"),
Measure("M23_PACIENTES_EVALUADOS", "Pacientes evaluados por resultado diagnóstico",
"screening",
StatusComposition(DIAGNOSIS, admit=lambda s: s in ("confirmed", "in_process"))),
Measure("M24_CONFIRMACION_DIAGNOSTICO", "Confirmación diagnóstica", "screening",
StatusProportion(DIAGNOSIS, lambda row, s, p: s in ("confirmed", "in_process"),
CONFIRMED, strata=(AGE,)),
"increase"),
Measure("M25_DIAS_MCHAT_DIAGNOSTICO", "Días de M-CHAT a diagnóstico positivo", "screening",
StatusDuration(STEPS, "days_mchat_confirmed", "confirmed_date"), "decrease"),
Measure("M26_DIAS_MCHAT_ADOS2", "Días de M-CHAT a ADOS-2", "screening",
StatusDuration(STEPS, "days_mchat_psychology", "psychology_date"), "decrease"),
Measure("M27_DIAS_ADOS2_DIAGNOSTICO", "Días de ADOS-2 a valoración neuropediátrica",
"screening",
StatusDuration(STEPS, "days_psychology_neuro", "neuro_date"), "decrease"),
Measure("M28_CASOS_POR_ESTADO", "Casos por estatus", "screening", StatusComposition(STEPS)),
Measure("M29_CALIDAD_EEG", "Calidad del EEG", "eegs",
Composition(lambda r: (as_day(r["study_date"]),), lambda r: r["quality"],
unit="eeg_id", date="study_date")),
]} # fmt: skip
+332
View File
@@ -0,0 +1,332 @@
"""Modelos ORM del proyecto TEA. Capa Storage: permisiva. Todos los campos
de dominio son Optional para que el loader nunca rechace un renglón. Los
booleanos se guardan como INTEGER y los enums como TEXT; la coerción es
trabajo de una capa de validación (no incluida en Core). Generado desde
spec/tablas_TEA.md. No editar a mano.
"""
import uuid
from datetime import date, datetime
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.tea.base import TeaModel
class Pacientes(TeaModel, table=True):
__tablename__ = "pacientes"
pac_id: Optional[str] = Field(
default_factory=lambda: str(uuid.uuid4()),
sa_column=sa.Column(sa.String(36), primary_key=True),
)
pac_id_hospital: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pac_id_titular: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pac_parentesco: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pac_fecha_nacimiento: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
pac_sexo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pac_codigo_postal_vigente: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pac_dependencia: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pac_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
pac_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
pac_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
class OrdenesEstudio(TeaModel, table=True):
__tablename__ = "ordenes_estudio"
ord_id: Optional[str] = Field(
default_factory=lambda: str(uuid.uuid4()),
sa_column=sa.Column(sa.String(36), primary_key=True),
)
ord_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_nota_medica_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_id_hospital: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_fecha: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
ord_medico_solicitante: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_especialidad: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_diagnostico_asignado: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_cie_asignado: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_dias_vigencia: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
ord_fecha_vencimiento: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
ord_tipo_estudio: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_estatus: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_fecha_realizacion: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
ord_fecha_resultado: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
ord_dias_espera: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
ord_proveedor: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_edad_meses: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
ord_ventana_madurativa: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_pdf_ruta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_observaciones: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
ord_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
ord_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
class NotaMedica(TeaModel, table=True):
__tablename__ = "nota_medica"
nm_id: Optional[str] = Field(
default_factory=lambda: str(uuid.uuid4()),
sa_column=sa.Column(sa.String(36), primary_key=True),
)
nm_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_id_hospital: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_nota_previa_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_tipo_nota: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_especialidad: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_fecha: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
nm_edad_meses: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
nm_ventana_madurativa: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_medico_tratante: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_motivo_consulta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_interrogatorio: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_regresion_referida: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
nm_antecedente_familiar_tea: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
nm_perimetro_cefalico: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
nm_diagnostico_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_cie_codigo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_cie_descripcion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_tratamiento_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_receta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_plan_estudios: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_pronostico: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_observaciones: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_masa_corporal: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
nm_talla: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
nm_imc_visita: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
nm_frecuencia_cardiaca: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
nm_frecuencia_respiratoria: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
nm_presion_arterial_sistolica: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
nm_presion_arterial_diastolica: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
nm_temperatura: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
nm_pdf_ruta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
nm_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
nm_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
class EvaluacionPsicologica(TeaModel, table=True):
__tablename__ = "evaluacion_psicologica"
psi_id: Optional[str] = Field(
default_factory=lambda: str(uuid.uuid4()),
sa_column=sa.Column(sa.String(36), primary_key=True),
)
psi_ord_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_fecha_evaluacion: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
psi_psicologo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_edad_meses: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
psi_ventana_madurativa: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_instrumento_tamizaje: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_tamizaje_puntaje: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_tamizaje_riesgo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_ados2_modulo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
# Columnas de item del ADOS-2 (Anexo B del diccionario de datos) — el rango
# valido y la pertenencia a modulo dependen de psi_ados2_modulo.
psi_ados2_sa_a2: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_a6: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_a7: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_a8: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b1: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b2: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b3: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b4: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b5: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b6: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b7: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b8: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b9: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b10: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b11: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b12: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b13: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b14: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b15: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b16b: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b18: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_rrb_a3: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_rrb_a4: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_rrb_a5: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_rrb_d1: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_rrb_d2: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_rrb_d4: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_rrb_d5: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_rrb: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_total: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_css: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_css_sa: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_css_rrb: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_clasificacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_rgd: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_cociente_desarrollo: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
psi_css_umbral_aplicado: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_caso_confirmado: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_cars_total: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
psi_otros_instrumentos: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_regresion_desarrollo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_diagnostico_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
psi_nlp_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
psi_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
class PotencialesEvocadosAuditivos(TeaModel, table=True):
__tablename__ = "potenciales_evocados_auditivos"
pea_id: Optional[str] = Field(
default_factory=lambda: str(uuid.uuid4()),
sa_column=sa.Column(sa.String(36), primary_key=True),
)
pea_ord_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pea_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pea_fecha_estudio: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
pea_medico_interpreta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pea_umbral_od: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pea_umbral_oi: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pea_latencia_v_od: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pea_latencia_v_oi: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pea_interpico_i_v_od: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pea_interpico_i_v_oi: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pea_grado_hipoacusia: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pea_conclusion_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pea_flag_diferencial_auditivo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pea_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pea_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
pea_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
class EegEstudio(TeaModel, table=True):
__tablename__ = "eeg_estudio"
eeg_id: Optional[str] = Field(
default_factory=lambda: str(uuid.uuid4()),
sa_column=sa.Column(sa.String(36), primary_key=True),
)
eeg_ord_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_reporte_disponible: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_fuente_interpretacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_fecha_nacimiento_declarada: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
eeg_edad_meses: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
eeg_fecha_estudio: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
eeg_fecha_reporte: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
eeg_dias_respuesta: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_medico_interpreta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_estado_registro: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_privacion_sueno: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_sedacion: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_sedacion_farmaco: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_duracion_min: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_calidad_tecnica: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_descripcion_senal: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_ritmo_base_frecuencia: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
eeg_ritmo_base_amplitud: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_simetria: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_anormalidad_presente: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_actividad_epileptiforme: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_tipo_grafoelemento: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_distribucion_anormalidad: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_localizacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_activacion_sueno: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_lentificacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_crisis_registradas: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_respuesta_fotoestimulacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_conclusion_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_conclusion_categoria: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_id_registro_laboratorio: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_pdf_ruta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
eeg_nlp_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
eeg_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
class AntecedentesMaternosGestacion(TeaModel, table=True):
__tablename__ = "antecedentes_maternos_gestacion"
amg_id: Optional[str] = Field(
default_factory=lambda: str(uuid.uuid4()),
sa_column=sa.Column(sa.String(36), primary_key=True),
)
amg_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_id_madre_seudonimo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_fuente_antecedente: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_flag_vinculo_verificado: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_imc_pregestacional: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
amg_categoria_peso_materno: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_tabaquismo_gestacion: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_acido_folico_preconcepcional: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_intervalo_intergenesico_meses: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_antecedente_aborto: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_embarazo_multiple: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_infeccion_gestacion: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_infeccion_tipo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_infeccion_hospitalizacion: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_diabetes_gestacional: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_hipertension_preeclampsia: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_hipotiroidismo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_hipertiroidismo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_incompatibilidad_rh: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_crisis_convulsivas: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_proceso_proinflamatorio: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_enfermedad_autoinmune: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_migrana: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_asma: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_hipoxia_materna: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_estres_agudo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_trastorno_neurologico: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_liquido_amniotico: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_medicamentos_gestacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_farmaco_riesgo_neurodesarrollo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_observaciones: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
amg_nlp_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
amg_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
amg_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
class PartoNeonatal(TeaModel, table=True):
__tablename__ = "parto_neonatal"
pnn_id: Optional[str] = Field(
default_factory=lambda: str(uuid.uuid4()),
sa_column=sa.Column(sa.String(36), primary_key=True),
)
pnn_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pnn_fuente_antecedente: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pnn_tipo_parto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pnn_complicaciones_intraparto: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_complicacion_tipo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pnn_peso_nacer_g: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_talla_nacer_cm: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pnn_perimetro_cefalico_nacer_cm: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pnn_edad_gestacional_sem: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pnn_clasificacion_eg: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pnn_tamano_para_eg: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pnn_peso_nacer_zscore: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pnn_apgar_1min: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_apgar_5min: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_ingreso_ucin: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_dias_ucin: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_encefalopatia_hipoxico_isquemica: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_hipotermia_nacer: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_hiperbilirrubinemia: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_fototerapia: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_hipoglucemia_neonatal: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_anoxia: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_sindrome_congenito: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_sindrome_congenito_desc: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pnn_flag_riesgo_neonatal: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_observaciones: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pnn_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pnn_nlp_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pnn_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
pnn_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
pnn_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
+13 -12
View File
@@ -1,19 +1,20 @@
[project]
name = "core"
version = "0.0.0"
description = "Domain types, clinical parameters, Measures and FHIR mappers. Imports nothing in the project."
requires-python = ">=3.12"
version = "0.1.0"
description = "Shared SQLModel schema for the CaCu, CaMa and TEA screening data marts."
requires-python = ">=3.11"
dependencies = [
"dateparser>=1.5.1",
"fhir-resources>=8",
"pydantic>=2.11",
"pyyaml>=6.0",
"sqlmodel>=0.0.22",
]
[build-system]
requires = ["uv_build>=0.12,<0.13"]
build-backend = "uv_build"
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.uv.build-backend]
module-name = "core"
module-root = ""
[tool.hatch.build.targets.wheel]
packages = ["core"]
[dependency-groups]
dev = [
"pytest>=8.0.0",
]
+473
View File
@@ -0,0 +1,473 @@
# Diccionario de datos y reglas de validación — Proyecto TEA
Este documento describe la base de datos del proyecto. Para cada tabla se listan sus
variables, el tipo de dato, la unidad (cuando aplica) y la validación que debe
cumplir cada una.
---
## 1. Tabla `pacientes`
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `pac_id` | VARCHAR(36), llave primaria | — | — | — |
| `pac_id_hospital` | TEXT | — | — | — |
| `pac_id_titular` | TEXT | — | — | — |
| `pac_parentesco` | TEXT | — | Catálogo cerrado `Parentesco`: `HIJO, HIJA, HIJASTRO, TUTELADO, OTRO`. | — |
| `pac_fecha_nacimiento` | DATE | — | No puede ser una fecha futura. | — |
| `pac_sexo` | TEXT | — | Catálogo cerrado `SexoBiologico`: `F, M, I`. | — |
| `pac_codigo_postal_vigente` | TEXT | — | Debe quedar en 5 dígitos numéricos exactos (se completa con ceros a la izquierda si llega con menos). | — |
| `pac_dependencia` | TEXT | — | — | — |
| `pac_created_at` | DATETIME | — | — | — |
| `pac_updated_at` | DATETIME | — | — | — |
| `pac_fuente_sistema` | TEXT | — | — | — |
Sin validaciones cruzadas.
---
## 2. Tabla `ordenes_estudio`
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `ord_id` | VARCHAR(36), llave primaria | — | — | — |
| `ord_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
| `ord_nota_medica_id` | TEXT | — | — | → `nota_medica.nm_id` |
| `ord_id_hospital` | TEXT | — | — | — |
| `ord_fecha` | DATE | — | No puede ser una fecha futura. | — |
| `ord_medico_solicitante` | TEXT | — | — | — |
| `ord_especialidad` | TEXT | — | Catálogo `Especialidad`: `NEUROLOGIA_PEDIATRICA, PEDIATRIA, PSICOLOGIA, PSIQUIATRIA_INFANTIL, AUDIOLOGIA, MEDICINA_FAMILIAR, ENFERMERIA, OTRO`. | — |
| `ord_diagnostico_asignado` | TEXT | — | — | — |
| `ord_cie_asignado` | TEXT | — | Formato CIE: una letra mayúscula, dos dígitos, y opcionalmente un punto con uno o dos dígitos más (ejemplo: `A09.1`). | — |
| `ord_dias_vigencia` | INTEGER | días | Entre 1 y 365. | — |
| `ord_fecha_vencimiento` | DATE | — | Ver validación cruzada. | — |
| `ord_proveedor` | TEXT | — | — | — |
| `ord_tipo_estudio` | TEXT | — | Catálogo `TipoEstudio`: `ELECTROENCEFALOGRAMA, POTENCIALES_EVOCADOS_AUDITIVOS, EVALUACION_PSICOLOGICA_TEA, OTRO`. | — |
| `ord_estatus` | TEXT | — | Catálogo `EstatusEstudio`: `SOLICITADO, EN_PROCESO, REALIZADO, RESULTADO_DISPONIBLE, CANCELADO, NO_ACUDIO`. | — |
| `ord_fecha_realizacion` | DATE | — | No puede ser una fecha futura. Ver validación cruzada. | — |
| `ord_fecha_resultado` | DATE | — | No puede ser una fecha futura. Ver validación cruzada. | — |
| `ord_dias_espera` | INTEGER | días | Entre 0 y 180. | — |
| `ord_edad_meses` | FLOAT | meses | Entre 16.0 y 36.0. | — |
| `ord_ventana_madurativa` | TEXT | — | Catálogo `VentanaMadurativa`: `V1_16_23, V2_24_30, V3_31_36, FUERA_DE_RANGO`. Ver validación cruzada. | — |
| `ord_pdf_ruta` | TEXT | — | — | — |
| `ord_observaciones` | TEXT | — | — | — |
| `ord_created_at` | DATETIME | — | — | — |
| `ord_updated_at` | DATETIME | — | — | — |
| `ord_fuente_sistema` | TEXT | — | — | — |
**Validaciones cruzadas de `ordenes_estudio`:**
- `ord_fecha_vencimiento` debe ser igual a `ord_fecha + ord_dias_vigencia` días, cuando ambos valores existen.
- `ord_fecha_realizacion` no puede ser anterior a `ord_fecha`.
- `ord_fecha_resultado` no puede ser anterior a `ord_fecha_realizacion`.
- `ord_ventana_madurativa` debe corresponder a `ord_edad_meses` según la tabla de ventanas (Anexo A).
---
## 3. Tabla `nota_medica`
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `nm_id` | VARCHAR(36), llave primaria | — | — | — |
| `nm_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
| `nm_id_hospital` | TEXT | — | — | — |
| `nm_nota_previa_id` | TEXT | — | — | → `nota_medica.nm_id` (autorreferencia: nota previa del mismo paciente) |
| `nm_tipo_nota` | TEXT | — | Catálogo `TipoNota`: `PRIMERA_VEZ, TAMIZAJE, INTERPRETACION_EEG, TRATAMIENTO, SEGUIMIENTO, INTERCONSULTA, URGENCIA, OTRO`. | — |
| `nm_especialidad` | TEXT | — | Catálogo `Especialidad` (mismo que `ord_especialidad`). | — |
| `nm_fecha` | DATE | — | No puede ser una fecha futura. | — |
| `nm_edad_meses` | FLOAT | meses | Entre 16.0 y 36.0. | — |
| `nm_ventana_madurativa` | TEXT | — | Catálogo `VentanaMadurativa`. Ver validación cruzada. | — |
| `nm_medico_tratante` | TEXT | — | — | — |
| `nm_motivo_consulta` | TEXT | — | — | — |
| `nm_interrogatorio` | TEXT | — | — | — |
| `nm_regresion_referida` | BOOL | — | — | — |
| `nm_antecedente_familiar_tea` | BOOL | — | — | — |
| `nm_perimetro_cefalico` | FLOAT | cm | Entre 38.0 y 58.0. | — |
| `nm_diagnostico_texto` | TEXT | — | — | — |
| `nm_cie_codigo` | TEXT | — | Formato CIE: una letra mayúscula, dos dígitos, punto opcional con uno o dos dígitos más. | — |
| `nm_cie_descripcion` | TEXT | — | — | — |
| `nm_tratamiento_texto` | TEXT | — | — | — |
| `nm_receta` | TEXT | — | — | — |
| `nm_plan_estudios` | TEXT | — | — | — |
| `nm_pronostico` | TEXT | — | Catálogo `Pronostico`: `BUENO, RESERVADO, MALO, NO_ESPECIFICADO`. | — |
| `nm_observaciones` | TEXT | — | — | — |
| `nm_masa_corporal` | FLOAT | kg | Entre 2.0 y 40.0. | — |
| `nm_talla` | FLOAT | m | Entre 0.4 y 1.4. | — |
| `nm_imc_visita` | FLOAT | kg/m² | Entre 5.0 y 40.0. Ver validación cruzada con peso y talla. | — |
| `nm_frecuencia_cardiaca` | INTEGER | lpm | Entre 50 y 230. | — |
| `nm_frecuencia_respiratoria` | INTEGER | rpm | Entre 10 y 80. | — |
| `nm_presion_arterial_sistolica` | INTEGER | mmHg | Entre 45 y 160. Ver validación cruzada. | — |
| `nm_presion_arterial_diastolica` | INTEGER | mmHg | Entre 25 y 110. Ver validación cruzada. | — |
| `nm_temperatura` | FLOAT | °C | Entre 32.0 y 43.0. | — |
| `nm_pdf_ruta` | TEXT | — | — | — |
| `nm_created_at` | DATETIME | — | — | — |
| `nm_updated_at` | DATETIME | — | — | — |
| `nm_fuente_sistema` | TEXT | — | — | — |
**Validaciones cruzadas de `nota_medica`:**
- La presión sistólica debe ser mayor que la diastólica.
- `nm_imc_visita` debe ser aproximadamente igual a `nm_masa_corporal / nm_talla²` (tolerancia de 0.5).
- `nm_ventana_madurativa` debe corresponder a `nm_edad_meses` (Anexo A).
---
## 4. Tabla `evaluacion_psicologica`
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `psi_id` | VARCHAR(36), llave primaria | — | — | — |
| `psi_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
| `psi_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
| `psi_fecha_evaluacion` | DATE | — | No puede ser una fecha futura. | — |
| `psi_psicologo` | TEXT | — | — | — |
| `psi_edad_meses` | FLOAT | meses | Entre 16.0 y 36.0. | — |
| `psi_ventana_madurativa` | TEXT | — | Catálogo `VentanaMadurativa`. Ver validación cruzada. | — |
| `psi_instrumento_tamizaje` | TEXT | — | Catálogo `InstrumentoTamizaje`: `M_CHAT_R, M_CHAT_RF, OTRO, NO_REGISTRADO`. | — |
| `psi_tamizaje_puntaje` | INTEGER | — | Entre 0 y 20. | — |
| `psi_tamizaje_riesgo` | TEXT | — | Catálogo `NivelRiesgoTamizaje`: `BAJO, MEDIO, ALTO, NO_APLICA`. | — |
| `psi_ados2_modulo` | TEXT | — | Catálogo `ModuloAdos2`: `TODDLER, MODULO_1, MODULO_2, NO_REGISTRADO`. Define qué ítems del ADOS-2 aplican (Anexo B). | — |
| `psi_ados2_sa` | INTEGER | — | Entre 0 y 30. Ver validación cruzada. | — |
| `psi_ados2_rrb` | INTEGER | — | Entre 0 y 20. Ver validación cruzada. | — |
| `psi_ados2_total` | INTEGER | — | Entre 0 y 50. Debe ser igual a `psi_ados2_sa + psi_ados2_rrb`. | — |
| `psi_ados2_css` | INTEGER | — | Entre 1 y 10. | — |
| `psi_ados2_css_sa` | INTEGER | — | Entre 1 y 10. | — |
| `psi_ados2_css_rrb` | INTEGER | — | Entre 1 y 10. | — |
| `psi_ados2_clasificacion` | TEXT | — | Catálogo `ClasificacionAdos2`: `NO_TEA, ESPECTRO_AUTISTA, AUTISMO, PREOCUPACION_LEVE_MODERADA, PREOCUPACION_SEVERA`. | — |
| `psi_rgd` | BOOL | — | Ver validación cruzada (retraso global del desarrollo). | — |
| `psi_cociente_desarrollo` | FLOAT | — | Entre 20.0 y 160.0. | — |
| `psi_css_umbral_aplicado` | INTEGER | — | Entre 1 y 10. Ver validación cruzada. | — |
| `psi_caso_confirmado` | BOOL | — | Ver validación cruzada. | — |
| `psi_cars_total` | FLOAT | — | Entre 15.0 y 60.0. Solo válido a partir de los 24 meses (ver validación cruzada). | — |
| `psi_otros_instrumentos` | TEXT | — | — | — |
| `psi_regresion_desarrollo` | BOOL | — | — | — |
| `psi_diagnostico_texto` | TEXT | — | — | — |
| `psi_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
| `psi_nlp_version` | TEXT | — | — | — |
| `psi_created_at` | DATETIME | — | — | — |
| `psi_updated_at` | DATETIME | — | — | — |
**Columnas de ítem del ADOS-2** (mismo tipo y patrón de validación que los puntajes enteros de arriba):
| Variable | Tipo | Unidad | Validación |
|---|---|---|---|
| `psi_ados2_sa_a2`, `psi_ados2_sa_a6`, `psi_ados2_sa_a7`, `psi_ados2_sa_a8`, `psi_ados2_sa_b1` … `psi_ados2_sa_b16b`, `psi_ados2_sa_b18` | INTEGER | — | Rango permitido según el módulo (Anexo B); fuera de rango se rechaza. |
| `psi_ados2_rrb_a3`, `psi_ados2_rrb_a4`, `psi_ados2_rrb_a5`, `psi_ados2_rrb_d1`, `psi_ados2_rrb_d2`, `psi_ados2_rrb_d4`, `psi_ados2_rrb_d5` | INTEGER | — | Rango permitido según el módulo (Anexo B); fuera de rango se rechaza. |
El detalle exacto de rango por código y por módulo, la validación de completitud y
la validación de pertenencia a módulo están en el **Anexo B**.
**Validaciones cruzadas de `evaluacion_psicologica`:**
- `psi_ados2_total` debe ser igual a `psi_ados2_sa + psi_ados2_rrb`.
- `psi_css_umbral_aplicado` debe ser 6 si `psi_rgd` es verdadero, y 5 si es falso.
- `psi_caso_confirmado` debe ser igual a `psi_ados2_css >= psi_css_umbral_aplicado`.
- `psi_cars_total` solo es válido si la ventana madurativa no es `V1_16_23` (la escala CARS aplica desde los 24 meses).
- `psi_ventana_madurativa` debe corresponder a `psi_edad_meses` (Anexo A).
- `psi_rgd` debe ser verdadero cuando `psi_cociente_desarrollo` es menor o igual a 75.0, y falso en caso contrario.
Las validaciones cruzadas propias del Anexo B (completitud y pertenencia a módulo) se
suman a esta lista.
---
## 5. Tabla `potenciales_evocados_auditivos`
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `pea_id` | VARCHAR(36), llave primaria | — | — | — |
| `pea_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
| `pea_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
| `pea_fecha_estudio` | DATE | — | No puede ser una fecha futura. | — |
| `pea_medico_interpreta` | TEXT | — | — | — |
| `pea_umbral_od` | INTEGER | dB | Entre 0 y 120 (oído derecho). | — |
| `pea_umbral_oi` | INTEGER | dB | Entre 0 y 120 (oído izquierdo). | — |
| `pea_latencia_v_od` | FLOAT | ms | Entre 3.5 y 12.0. | — |
| `pea_latencia_v_oi` | FLOAT | ms | Entre 3.5 y 12.0. | — |
| `pea_interpico_i_v_od` | FLOAT | ms | Entre 2.0 y 8.0. | — |
| `pea_interpico_i_v_oi` | FLOAT | ms | Entre 2.0 y 8.0. | — |
| `pea_grado_hipoacusia` | TEXT | — | Catálogo `GradoHipoacusia`: `NORMAL, LEVE, MODERADA, SEVERA, PROFUNDA, NO_CONCLUYENTE`. | — |
| `pea_conclusion_texto` | TEXT | — | — | — |
| `pea_flag_diferencial_auditivo` | BOOL | — | Ver validación cruzada. | — |
| `pea_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
| `pea_created_at` | DATETIME | — | — | — |
| `pea_updated_at` | DATETIME | — | — | — |
**Validación cruzada de `potenciales_evocados_auditivos`:**
- Si `pea_grado_hipoacusia` es `MODERADA`, `SEVERA` o `PROFUNDA`, entonces `pea_flag_diferencial_auditivo` debe ser verdadero.
---
## 6. Tabla `eeg_estudio`
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `eeg_id` | VARCHAR(36), llave primaria | — | — | — |
| `eeg_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
| `eeg_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
| `eeg_reporte_disponible` | BOOL | — | Ver validación cruzada. | — |
| `eeg_fuente_interpretacion` | TEXT | — | Catálogo `FuenteInterpretacionEeg`: `REPORTE_NEUROPEDIATRIA, NOTA_MEDICA, AMBAS, NINGUNA`. | — |
| `eeg_fecha_nacimiento_declarada` | DATE | — | No puede ser una fecha futura. | — |
| `eeg_edad_meses` | FLOAT | meses | Entre 16.0 y 36.0. | — |
| `eeg_fecha_estudio` | DATE | — | No puede ser una fecha futura. | — |
| `eeg_fecha_reporte` | DATE | — | No puede ser una fecha futura. Ver validación cruzada. | — |
| `eeg_dias_respuesta` | INTEGER | días | Entre 0 y 60. Ver validación cruzada. | — |
| `eeg_medico_interpreta` | TEXT | — | — | — |
| `eeg_estado_registro` | TEXT | — | Catálogo `EstadoRegistroEeg`: `VIGILIA, SUENO_ESPONTANEO, SUENO_INDUCIDO, MIXTO, NO_ESPECIFICADO`. | — |
| `eeg_privacion_sueno` | BOOL | — | — | — |
| `eeg_sedacion` | BOOL | — | Ver validación cruzada. | — |
| `eeg_sedacion_farmaco` | TEXT | — | Ver validación cruzada. | — |
| `eeg_duracion_min` | INTEGER | min | Entre 10 y 1440. | — |
| `eeg_calidad_tecnica` | TEXT | — | Catálogo `CalidadTecnicaEeg`: `SATISFACTORIA, LIMITADA_POR_ARTEFACTO, LIMITADA_POR_COLABORACION, NO_VALORABLE, NO_ESPECIFICADA`. | — |
| `eeg_descripcion_senal` | TEXT | — | — | — |
| `eeg_ritmo_base_frecuencia` | FLOAT | Hz | Entre 2.0 y 14.0. | — |
| `eeg_ritmo_base_amplitud` | INTEGER | µV | Entre 5 y 300. | — |
| `eeg_simetria` | TEXT | — | Catálogo `Simetria`: `SIMETRICO, ASIMETRICO_IZQUIERDO, ASIMETRICO_DERECHO, NO_ESPECIFICADA`. | — |
| `eeg_anormalidad_presente` | BOOL | — | Ver validación cruzada. | — |
| `eeg_actividad_epileptiforme` | BOOL | — | Ver validación cruzada. | — |
| `eeg_tipo_grafoelemento` | TEXT | — | Catálogo `TipoGrafoelemento`: `NINGUNO, ESPIGA, ONDA_AGUDA, COMPLEJO_ESPIGA_ONDA, COMPLEJO_POLIESPIGA_ONDA, PUNTA_ONDA_LENTA, DESCARGA_RITMICA, OTRO`. Ver validación cruzada. | — |
| `eeg_distribucion_anormalidad` | TEXT | — | Catálogo `DistribucionAnormalidad`: `FOCAL, MULTIFOCAL, GENERALIZADA, LATERALIZADA, NO_ESPECIFICADA`. | — |
| `eeg_localizacion` | TEXT | — | — | — |
| `eeg_activacion_sueno` | BOOL | — | — | — |
| `eeg_lentificacion` | TEXT | — | Catálogo `Lentificacion`: `NINGUNA, FOCAL, GENERALIZADA, INTERMITENTE`. | — |
| `eeg_crisis_registradas` | BOOL | — | — | — |
| `eeg_respuesta_fotoestimulacion` | TEXT | — | Catálogo `RespuestaFotoestimulacion`: `NORMAL, RESPUESTA_FOTOPAROXISTICA, SIN_RESPUESTA, NO_PRACTICADA`. | — |
| `eeg_conclusion_texto` | TEXT | — | Ver validación cruzada. | — |
| `eeg_conclusion_categoria` | TEXT | — | Catálogo `ConclusionEeg`: `NORMAL_PARA_LA_EDAD, NORMAL_CON_VARIANTES, ANORMAL_EPILEPTIFORME, ANORMAL_NO_EPILEPTIFORME, ANORMAL_MIXTO, NO_CONCLUYENTE`. Ver validación cruzada. | — |
| `eeg_id_registro_laboratorio` | TEXT | — | — | — |
| `eeg_pdf_ruta` | TEXT | — | — | — |
| `eeg_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
| `eeg_nlp_version` | TEXT | — | — | — |
| `eeg_created_at` | DATETIME | — | — | — |
| `eeg_updated_at` | DATETIME | — | — | — |
**Validaciones cruzadas de `eeg_estudio`:**
- `eeg_fecha_reporte` no puede ser anterior a `eeg_fecha_estudio`.
- `eeg_dias_respuesta` debe ser igual a la diferencia en días entre `eeg_fecha_reporte` y `eeg_fecha_estudio`.
- Si `eeg_actividad_epileptiforme` es falso, `eeg_tipo_grafoelemento` debe quedar vacío o en `NINGUNO`.
- Si `eeg_actividad_epileptiforme` es verdadero, `eeg_anormalidad_presente` debe ser verdadero.
- Si `eeg_sedacion` es falso, `eeg_sedacion_farmaco` debe quedar vacío.
- Si `eeg_reporte_disponible` es verdadero, `eeg_conclusion_texto` no puede quedar vacío.
- Si `eeg_conclusion_categoria` es `NORMAL_PARA_LA_EDAD` o `NORMAL_CON_VARIANTES`, entonces `eeg_anormalidad_presente` debe ser falso.
---
## 7. Tabla `antecedentes_maternos_gestacion`
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `amg_id` | VARCHAR(36), llave primaria | — | — | — |
| `amg_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
| `amg_id_madre_seudonimo` | TEXT | — | Ver validación cruzada. | — |
| `amg_fuente_antecedente` | TEXT | — | Catálogo `FuenteAntecedenteMaterno`: `EXPEDIENTE_MATERNO, INTERROGATORIO_NM11, AMBAS, NO_LOCALIZADO`. Ver validación cruzada. | — |
| `amg_flag_vinculo_verificado` | BOOL | — | — | — |
| `amg_imc_pregestacional` | FLOAT | kg/m² | Entre 12.0 y 70.0. Ver validación cruzada. | — |
| `amg_categoria_peso_materno` | TEXT | — | Catálogo `CategoriaPesoMaterno`: `BAJO_PESO, NORMAL, SOBREPESO, OBESIDAD_I, OBESIDAD_II, OBESIDAD_III, NO_REGISTRADA`. Ver validación cruzada. | — |
| `amg_tabaquismo_gestacion` | BOOL | — | — | — |
| `amg_acido_folico_preconcepcional` | BOOL | — | — | — |
| `amg_intervalo_intergenesico_meses` | INTEGER | meses | Entre 0 y 360. | — |
| `amg_antecedente_aborto` | BOOL | — | — | — |
| `amg_embarazo_multiple` | TEXT | — | Catálogo `TipoEmbarazo`: `UNICO, GEMELAR, TRIPLE_O_MAS, NO_REGISTRADO`. | — |
| `amg_infeccion_gestacion` | BOOL | — | Ver validación cruzada. | — |
| `amg_infeccion_tipo` | TEXT | — | Ver validación cruzada. | — |
| `amg_infeccion_hospitalizacion` | BOOL | — | Ver validación cruzada. | — |
| `amg_diabetes_gestacional` | BOOL | — | — | — |
| `amg_hipertension_preeclampsia` | TEXT | — | Catálogo `TrastornoHipertensivoGestacion`: `NINGUNO, HIPERTENSION_GESTACIONAL, PREECLAMPSIA, ECLAMPSIA, SINDROME_HELLP, NO_REGISTRADO`. | — |
| `amg_hipotiroidismo` | BOOL | — | — | — |
| `amg_hipertiroidismo` | BOOL | — | — | — |
| `amg_incompatibilidad_rh` | BOOL | — | — | — |
| `amg_crisis_convulsivas` | BOOL | — | — | — |
| `amg_proceso_proinflamatorio` | BOOL | — | — | — |
| `amg_enfermedad_autoinmune` | BOOL | — | — | — |
| `amg_migrana` | BOOL | — | — | — |
| `amg_asma` | BOOL | — | — | — |
| `amg_hipoxia_materna` | BOOL | — | — | — |
| `amg_estres_agudo` | BOOL | — | — | — |
| `amg_trastorno_neurologico` | BOOL | — | — | — |
| `amg_liquido_amniotico` | TEXT | — | Catálogo `VolumenLiquidoAmniotico`: `NORMAL, OLIGOHIDRAMNIOS, POLIHIDRAMNIOS, NO_REGISTRADO`. | — |
| `amg_medicamentos_gestacion` | TEXT | — | Ver validación cruzada. | — |
| `amg_farmaco_riesgo_neurodesarrollo` | BOOL | — | Ver validación cruzada. | — |
| `amg_observaciones` | TEXT | — | — | — |
| `amg_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
| `amg_nlp_version` | TEXT | — | — | — |
| `amg_created_at` | DATETIME | — | — | — |
| `amg_updated_at` | DATETIME | — | — | — |
| `amg_fuente_sistema` | TEXT | — | — | — |
**Validaciones cruzadas de `antecedentes_maternos_gestacion`:**
- Si `amg_fuente_antecedente` es `EXPEDIENTE_MATERNO` o `AMBAS`, `amg_id_madre_seudonimo` debe estar presente.
- `amg_categoria_peso_materno` debe corresponder al valor de `amg_imc_pregestacional` (Anexo A).
- Si `amg_infeccion_gestacion` es falso, `amg_infeccion_tipo` debe quedar vacío y `amg_infeccion_hospitalizacion` debe ser falso o vacío.
- Si `amg_farmaco_riesgo_neurodesarrollo` es verdadero, `amg_medicamentos_gestacion` no puede quedar vacío.
---
## 8. Tabla `parto_neonatal`
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `pnn_id` | VARCHAR(36), llave primaria | — | — | — |
| `pnn_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
| `pnn_fuente_antecedente` | TEXT | — | Catálogo `FuenteAntecedenteNeonatal`: `NOTA_RECIEN_NACIDO, NOTA_RESOLUCION_OBSTETRICA, INTERROGATORIO_NM11, AMBAS, NO_LOCALIZADA`. | — |
| `pnn_tipo_parto` | TEXT | — | Catálogo `TipoParto`: `VAGINAL_ESPONTANEO, VAGINAL_INSTRUMENTADO, CESAREA_ELECTIVA, CESAREA_URGENCIA, NO_REGISTRADO`. | — |
| `pnn_complicaciones_intraparto` | BOOL | — | Ver validación cruzada. | — |
| `pnn_complicacion_tipo` | TEXT | — | Catálogo `ComplicacionIntraparto`: `NINGUNA, HIPOXIA, ISQUEMIA, TRAUMA_OBSTETRICO, CIRCULAR_DE_CORDON, SUFRIMIENTO_FETAL_AGUDO, OTRA`. Ver validación cruzada. | — |
| `pnn_peso_nacer_g` | INTEGER | g | Entre 400 y 6000. | — |
| `pnn_talla_nacer_cm` | FLOAT | cm | Entre 25.0 y 60.0. | — |
| `pnn_perimetro_cefalico_nacer_cm` | FLOAT | cm | Entre 25.0 y 42.0. | — |
| `pnn_edad_gestacional_sem` | FLOAT | semanas | Entre 22.0 y 43.0. | — |
| `pnn_clasificacion_eg` | TEXT | — | Catálogo `ClasificacionEdadGestacional`: `PRETERMINO_EXTREMO, MUY_PRETERMINO, PRETERMINO_TARDIO, TERMINO, POSTERMINO, NO_DETERMINADA`. Ver validación cruzada. | — |
| `pnn_tamano_para_eg` | TEXT | — | Catálogo `TamanoParaEdadGestacional`: `PEQUENO, ADECUADO, GRANDE, NO_DETERMINADO`. | — |
| `pnn_peso_nacer_zscore` | FLOAT | — | Entre -5.0 y 5.0. | — |
| `pnn_apgar_1min` | INTEGER | — | Entre 0 y 10. Ver validación cruzada. | — |
| `pnn_apgar_5min` | INTEGER | — | Entre 0 y 10. Ver validación cruzada. | — |
| `pnn_ingreso_ucin` | BOOL | — | Ver validación cruzada. | — |
| `pnn_dias_ucin` | INTEGER | días | Entre 0 y 365. Ver validación cruzada. | — |
| `pnn_encefalopatia_hipoxico_isquemica` | BOOL | — | — | — |
| `pnn_hipotermia_nacer` | BOOL | — | — | — |
| `pnn_hiperbilirrubinemia` | BOOL | — | Ver validación cruzada. | — |
| `pnn_fototerapia` | BOOL | — | Ver validación cruzada. | — |
| `pnn_hipoglucemia_neonatal` | BOOL | — | — | — |
| `pnn_anoxia` | BOOL | — | — | — |
| `pnn_sindrome_congenito` | BOOL | — | Ver validación cruzada. | — |
| `pnn_sindrome_congenito_desc` | TEXT | — | Ver validación cruzada. | — |
| `pnn_flag_riesgo_neonatal` | BOOL | — | Ver validación cruzada. | — |
| `pnn_observaciones` | TEXT | — | — | — |
| `pnn_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
| `pnn_nlp_version` | TEXT | — | — | — |
| `pnn_created_at` | DATETIME | — | — | — |
| `pnn_updated_at` | DATETIME | — | — | — |
| `pnn_fuente_sistema` | TEXT | — | — | — |
**Validaciones cruzadas de `parto_neonatal`:**
- `pnn_clasificacion_eg` debe corresponder a `pnn_edad_gestacional_sem` (Anexo A).
- `pnn_apgar_5min` no puede ser menor que `pnn_apgar_1min`.
- Si `pnn_dias_ucin` es mayor que 0, `pnn_ingreso_ucin` debe ser verdadero.
- Si `pnn_fototerapia` es verdadero, `pnn_hiperbilirrubinemia` debe ser verdadero.
- Si `pnn_complicaciones_intraparto` es falso, `pnn_complicacion_tipo` debe quedar vacío o en `NINGUNA`.
- Si `pnn_sindrome_congenito` es falso, `pnn_sindrome_congenito_desc` debe quedar vacío.
- `pnn_flag_riesgo_neonatal` debe ser verdadero si se cumple al menos una de estas cuatro condiciones: `pnn_apgar_5min < 7`, `pnn_ingreso_ucin` verdadero, `pnn_encefalopatia_hipoxico_isquemica` verdadero, o `pnn_anoxia` verdadero. Si no se cumple ninguna, debe ser falso.
---
## Anexo A — Funciones de referencia usadas en varias validaciones cruzadas
**Ventana madurativa según edad en meses** (usada en `ordenes_estudio`, `nota_medica`, `evaluacion_psicologica`):
| Edad en meses | Ventana |
|---|---|
| 16.0 a 23.9 | `V1_16_23` |
| 24.0 a 30.9 | `V2_24_30` |
| 31.0 a 36.0 | `V3_31_36` |
| Cualquier otro valor | `FUERA_DE_RANGO` |
**Categoría de peso materno según IMC pregestacional** (usada en `antecedentes_maternos_gestacion`, clasificación estándar de adultos de la OMS):
| IMC (kg/m²) | Categoría |
|---|---|
| Menor a 18.5 | `BAJO_PESO` |
| 18.5 a 24.9 | `NORMAL` |
| 25.0 a 29.9 | `SOBREPESO` |
| 30.0 a 34.9 | `OBESIDAD_I` |
| 35.0 a 39.9 | `OBESIDAD_II` |
| 40.0 o más | `OBESIDAD_III` |
**Clasificación por edad gestacional al nacer** (usada en `parto_neonatal`):
| Semanas de gestación | Clasificación |
|---|---|
| Menos de 28.0 | `PRETERMINO_EXTREMO` |
| 28.0 a 31.9 | `MUY_PRETERMINO` |
| 32.0 a 36.9 | `PRETERMINO_TARDIO` |
| 37.0 a 41.9 | `TERMINO` |
| 42.0 o más | `POSTERMINO` |
---
## Anexo B — Validación de los códigos del ADOS-2 (`evaluacion_psicologica`)
El campo `psi_ados2_modulo` fija qué módulo del ADOS-2 se aplicó al paciente. Cada
módulo usa un subconjunto distinto de códigos, dentro de los dos dominios que ya
existen como columnas agregadas: `SA` (Interacción social recíproca / comunicación) y
`RRB` (Conductas restringidas y repetitivas). Equivalencia entre el catálogo
`ModuloAdos2` y los módulos del manual: `TODDLER` = Módulo T, `MODULO_1` = Módulo 1,
`MODULO_2` = Módulo 2.
### B.1 Rango válido de cada código, por módulo
| Código | Dominio | Módulo T | Módulo 1 | Módulo 2 |
|---|---|---|---|---|
| a2 | SA | 0–3 | 0–3 | — |
| a6 | SA | — | — | 0–3 |
| a7 | SA | 0–3 | 0–3 | 0–3, 8 |
| a8 | SA | 0–3, 8 | 0–2, 8 | — |
| b1 | SA | 0–3 | 0, 2 | 0, 2 |
| b2 | SA | — | — | 0–2 |
| b3 | SA | — | 0–2 | 0–3 |
| b4 | SA | 0–3 | 0–3 | — |
| b5 | SA | 0–3 | 0–3 | 0–2 |
| b6 | SA | 0–3 | — | 0–2 |
| b7 | SA | 0–3 | — | — |
| b8 | SA | 0–3 | — | 0–3 |
| b9 | SA | 0–3 | 0–2 | — |
| b10 | SA | — | 0–2 | — |
| b11 | SA | — | 0–3 | 0–3 |
| b12 | SA | 0–3 | 0–3 | 0–3 |
| b13 | SA | 0–3 | — | — |
| b14 | SA | 0–3 | — | — |
| b15 | SA | 0–3 | — | — |
| b16b | SA | 0–3, 7, 8 | — | — |
| b18 | SA | 0–3 | — | — |
| a3 | RRB | 0–3, 8 | 0–2, 8 | — |
| a4 | RRB | — | — | 0–3 |
| a5 | RRB | — | 0–3, 8 | — |
| d1 | RRB | 0–3 | 0–3 | 0–3 |
| d2 | RRB | 0–3 | 0–3 | 0–3 |
| d4 | RRB | — | 0–3 | 0–3 |
| d5 | RRB | 0–3 | — | — |
Nota de lectura: "0–3, 8" significa que, además de los valores enteros 0 a 3, el
manual permite el código adicional 8 en ese ítem y módulo. Una celda con "—" quiere
decir que ese código no existe para ese módulo (ver regla de pertenencia, B.3).
**Validación de rango por código:** si la columna correspondiente al código no está
vacía, su valor debe ser un entero dentro del conjunto permitido para el módulo
indicado en `psi_ados2_modulo`. Cualquier valor fuera del conjunto (incluido un
entero "razonable" pero no listado, como un 4 donde el máximo es 3) se rechaza.
### B.2 Validación de completitud del módulo
Todos los códigos que pertenecen al módulo indicado en `psi_ados2_modulo` (columna
correspondiente en la tabla de B.1) deben tener un valor, es decir, no pueden quedar
vacíos. Si al menos uno de los códigos propios del módulo está vacío, el renglón se
considera incompleto y se rechaza.
Ejemplo: si `psi_ados2_modulo = MODULO_1`, deben estar llenas las columnas
`psi_ados2_sa_a2, sa_a7, sa_a8, sa_b1, sa_b3, sa_b4, sa_b5, sa_b9, sa_b10, sa_b11,
sa_b12, rrb_a3, rrb_a5, rrb_d1, rrb_d2, rrb_d4`.
### B.3 Validación de pertenencia a módulo
Los códigos que **no** pertenecen al módulo indicado (celda "—" en B.1 para ese
módulo) deben quedar vacíos. Si alguno de esos códigos trae un valor, el renglón se
rechaza, porque ese código no corresponde a la versión de la prueba aplicada.
Ejemplo: si `psi_ados2_modulo = TODDLER`, las columnas `psi_ados2_sa_b2,
sa_b3, sa_b10, sa_b11, rrb_a4, rrb_a5, rrb_d4` (propias de otros módulos) deben
quedar vacías.
---
## Anexo C — Llaves foráneas (resumen)
| Columna | Tabla y columna referenciada |
|---|---|
| `ordenes_estudio.ord_pac_id` | `pacientes.pac_id` |
| `ordenes_estudio.ord_nota_medica_id` | `nota_medica.nm_id` |
| `nota_medica.nm_pac_id` | `pacientes.pac_id` |
| `nota_medica.nm_nota_previa_id` | `nota_medica.nm_id` (autorreferencia) |
| `evaluacion_psicologica.psi_ord_id` | `ordenes_estudio.ord_id` |
| `evaluacion_psicologica.psi_pac_id` | `pacientes.pac_id` |
| `potenciales_evocados_auditivos.pea_ord_id` | `ordenes_estudio.ord_id` |
| `potenciales_evocados_auditivos.pea_pac_id` | `pacientes.pac_id` |
| `eeg_estudio.eeg_ord_id` | `ordenes_estudio.ord_id` |
| `eeg_estudio.eeg_pac_id` | `pacientes.pac_id` |
| `antecedentes_maternos_gestacion.amg_pac_id` | `pacientes.pac_id` |
| `parto_neonatal.pnn_pac_id` | `pacientes.pac_id` |
+88
View File
@@ -0,0 +1,88 @@
"""Smoke tests: each domain's models import cleanly and register on their
own isolated metadata (no cross-domain table-name collisions)."""
import sqlalchemy as sa
from core.cacu.base import CaCuModel
from core.cama.base import CaMaModel
from core.tea.base import TeaModel
from core.auth.base import AuthModel
from core.cacu import models as cacu_models
from core.cama import models as cama_models
from core.tea import models as tea_models
def test_cacu_tables_registered():
names = set(CaCuModel.metadata.tables.keys())
assert names == {"paciente", "ordenesestudio", "citologiacervical", "biopsiacervical", "notamedica", "biometriahematica"}
def test_cama_tables_registered():
names = set(CaMaModel.metadata.tables.keys())
assert names == {"paciente", "ordenesestudio", "mastografia", "biopsiamama", "notamedica", "biometriahematica"}
def test_tea_tables_registered():
names = set(TeaModel.metadata.tables.keys())
assert names == {
"pacientes",
"ordenes_estudio",
"nota_medica",
"evaluacion_psicologica",
"potenciales_evocados_auditivos",
"eeg_estudio",
"antecedentes_maternos_gestacion",
"parto_neonatal",
}
def test_domains_do_not_share_metadata():
assert CaCuModel.metadata is not CaMaModel.metadata
assert CaCuModel.metadata is not TeaModel.metadata
assert CaMaModel.metadata is not TeaModel.metadata
assert AuthModel.metadata is not CaCuModel.metadata
assert AuthModel.metadata is not CaMaModel.metadata
assert AuthModel.metadata is not TeaModel.metadata
def test_auth_tables_registered():
assert set(AuthModel.metadata.tables) == {"user", "role", "user_role"}
def test_auth_primary_keys_and_foreign_keys():
users = AuthModel.metadata.tables["user"]
roles = AuthModel.metadata.tables["role"]
user_roles = AuthModel.metadata.tables["user_role"]
assert [column.name for column in users.primary_key.columns] == ["id"]
assert [column.name for column in roles.primary_key.columns] == ["code"]
assert {column.name for column in user_roles.primary_key.columns} == {"user_id", "role_code"}
assert {foreign_key.target_fullname for foreign_key in user_roles.foreign_keys} == {
"user.id",
"role.code",
}
ondelete_by_column = {
next(iter(user_roles.c[column_name].foreign_keys)).parent.name:
next(iter(user_roles.c[column_name].foreign_keys)).ondelete
for column_name in ("user_id", "role_code")
}
assert ondelete_by_column == {"user_id": "CASCADE", "role_code": None}
def test_auth_essential_constraints():
users = AuthModel.metadata.tables["user"]
roles = AuthModel.metadata.tables["role"]
assert any(
list(constraint.columns.keys()) == ["username"]
for constraint in users.constraints
if isinstance(constraint, sa.UniqueConstraint)
)
username_check = next(
constraint
for constraint in users.constraints
if isinstance(constraint, sa.CheckConstraint)
and constraint.name == "ck_user_username_format"
)
assert "length(username) BETWEEN 3 AND 64" in str(username_check.sqltext)
assert "username NOT GLOB '*[^a-z0-9._-]*'" in str(username_check.sqltext)
assert any(constraint.name == "ck_role_code_allowed" for constraint in roles.constraints)
-48
View File
@@ -1,48 +0,0 @@
# One Python image for the API, the Dagster webserver and the Dagster daemon.
FROM python:3.12-slim AS app
RUN apt-get update \
&& apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-spa ghostscript \
postgresql-client \
&& rm -rf /var/lib/apt/lists/*
COPY --from=ghcr.io/astral-sh/uv:0.12.21 /uv /bin/uv
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PROJECT_ENVIRONMENT=/venv PATH=/venv/bin:$PATH
WORKDIR /app
COPY . .
# Optional extras a machine opts into (`--extra dask` where a Dask cluster runs the batches).
ARG EXTRAS=""
RUN uv sync --frozen --no-dev $EXTRAS
ENV ISSSTELEON_DATA=/data DAGSTER_HOME=/data/dagster DLT_DATA_DIR=/data/dlt
# The same image plus the dev tools: what CI and `docker compose run --rm test` run.
# The HL7 validator is pinned by checksum; its FHIR 4.3.0 packages are fetched here, once,
# so tests validate offline.
FROM app AS test
RUN apt-get update \
&& apt-get install -y --no-install-recommends default-jre-headless \
&& rm -rf /var/lib/apt/lists/*
ADD --checksum=sha256:9dfe9f305b0f9389eceade2a4a1c9a2740d7b0e614066fdf07a78b571c76d92f \
https://github.com/hapifhir/org.hl7.fhir.core/releases/download/7.0.5/validator_cli.jar \
/opt/fhir/validator_cli.jar
RUN echo '{"resourceType":"Basic","code":{"text":"warm-up"}}' > /tmp/warm.json \
&& java -jar /opt/fhir/validator_cli.jar /tmp/warm.json -version 4.3.0 -tx n/a > /dev/null \
&& rm /tmp/warm.json
ENV FHIR_VALIDATOR_JAR=/opt/fhir/validator_cli.jar
# Synthea, pinned: seeded synthetic patients sent through the FHIR door in tests.
ADD --checksum=sha256:ed43c20ad40ba5c3bc724503a5af032715fe3c491620b766148e7c2361e6ecc1 \
https://github.com/synthetichealth/synthea/releases/download/v4.0.0/synthea-with-dependencies.jar \
/opt/synthea/synthea.jar
ENV SYNTHEA_JAR=/opt/synthea/synthea.jar
RUN uv sync --frozen
# The pages (-m webapp) run in CI's web job, which has Node and a browser.
CMD ["pytest", "-q", "-rs", "-m", "not webapp"]
# A Dask worker for testing on a cluster (not part of the product): the app's Python and code
# with the `dask` extra, run as the cluster runs its workers (user dask, one thread per math
# library). The cluster gives the command (`dask worker <scheduler>`).
FROM app AS dask-worker
RUN uv sync --frozen --no-dev --extra dask \
&& useradd --uid 10001 --create-home dask
ENV OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1
WORKDIR /home/dask
USER dask
CMD ["dask", "worker", "--help"]
+9
View File
@@ -0,0 +1,9 @@
__pycache__/
*.pyc
.venv/
.pytest_cache/
.coverage
*.egg-info/
.env
uv.lock
*.db
+97
View File
@@ -0,0 +1,97 @@
# Persistance
Database-agnostic SQLAlchemy/Alembic persistence layer for the three
screening data marts — CaCu, CaMa and TEA — built on top of the shared
schema in `../Core`. SQLite for now; swapping dialects is a `DATABASE_URL`
change, not a code change.
## Structure
- `persistance/settings.py` — one env var per domain (`CACU_DATABASE_URL`,
`CAMA_DATABASE_URL`, `TEA_DATABASE_URL`), since a single process now
serves three independent databases.
- `persistance/db.py` — engine/session factory per domain
(`get_cacu_session`, `get_cama_session`, `get_tea_session`).
- `persistance/repository.py` — the generic `Repository` class.
- `persistance/cacu/`, `persistance/cama/`, `persistance/tea/` — one
Alembic environment per domain, plus that domain's module-level
repository instances (see below).
## The repository pattern
`Repository` is one generic class parametrized by a `Core` model —
`get(id)` / `list(limit, offset, **filters)` / `count(**filters)`. Every
table gets one instance, wired up once per domain in that domain's
`__init__.py`:
```python
# persistance/cacu/__init__.py
paciente_repository = Repository(get_cacu_session, Paciente)
ordenes_estudio_repository = Repository(get_cacu_session, OrdenesEstudio)
citologia_cervical_repository = Repository(get_cacu_session, CitologiaCervical)
biopsia_cervical_repository = Repository(get_cacu_session, BiopsiaCervical)
nota_medica_repository = Repository(get_cacu_session, NotaMedica)
```
These module-level instances are the standard way every consumer reads
data — `WebApi`'s read routes and the `models` package's training code
both import the same instances from `persistance.cacu` /
`persistance.cama` / `persistance.tea`, so they're reading through the
exact same API, not two different paths to the same tables.
### Adding a repository for a new table
Two lines in that domain's `__init__.py`: import the model from `Core`,
instantiate `Repository(get_<domain>_session, TheModel)`. Nothing else to
write — `get`/`list`/`count` come for free.
### When a table needs more than get/list/count
Don't bolt a one-off method onto the generic `Repository`, and don't
write a standalone function that opens its own session outside the
pattern. Subclass `Repository` for just that one table:
```python
# persistance/cacu/repository.py
from sqlmodel import select
from core.cacu.models import CitologiaCervical
from persistance.repository import Repository
class CitologiaCervicalRepository(Repository[CitologiaCervical]):
def list_vph_positivo_confiable(self, umbral_confianza: float = 0.9):
with self._session_factory() as session:
statement = select(CitologiaCervical).where(
CitologiaCervical.cit_vph_resultado == "POSITIVO",
CitologiaCervical.cit_vph_ocr_confianza >= umbral_confianza,
)
return list(session.exec(statement))
```
Then swap the plain instantiation for the subclass in
`persistance/cacu/__init__.py`:
```python
citologia_cervical_repository = CitologiaCervicalRepository(get_cacu_session, CitologiaCervical)
```
Every existing caller keeps working unchanged (`.get()`/`.list()`/`.count()`
are inherited); the new method is just available too:
`citologia_cervical_repository.list_vph_positivo_confiable()`. Only
subclass the tables that actually need it — most are fine with the
generic `Repository` as-is.
## Migrations
Three independent Alembic environments, one per domain:
```bash
uv run alembic -c persistance/cacu/alembic.ini upgrade head
uv run alembic -c persistance/cama/alembic.ini upgrade head
uv run alembic -c persistance/tea/alembic.ini upgrade head
```
Each domain's migration history is a single, tool-generated
`create_table` migration against that domain's `Core` metadata. If the
schema changes, delete and regenerate — never hand-edit a migration file.
-4
View File
@@ -1,4 +0,0 @@
target/
logs/
dbt_packages/
.user.yml

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