Compare commits

..

41 Commits

Author SHA1 Message Date
edgar d6f79eff3e CaCu KPIs: HPV distribution and HPV groups in the referral PPVs
CACU_VPH counts each patient once, by her latest sample with an HPV result
in the period, with HPV 16 and 18 apart and initial and subsequent screening.
Both referral PPVs group by the referring cytology's HPV result (no_data
without one; the patient stays in the PPV). cacu_samples and
cacu_referral_facts carry hpv, hpv_16 and hpv_18.

Also reformats lines CI's ruff format check rejected.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJFdw3mNQ5GUFgzwz1
2026-11-27 20:41:48 -06:00
Angel Capetillo Zavala c5a92112c6 CaCu integration report and remote advances report 2026-11-27 18:43:48 -06:00
Angel Capetillo Zavala 3822959991 Point WebApp and WebApi at the CaCu follow-up, record and export commits 2026-11-27 18:43:47 -06:00
Angel Capetillo Zavala 758168de57 CaCu: biopsy and HPV report measures, biopsy request confirmation, ICD-10 diagnosis timing and individual stages
Gold models and measures for the HPV genotype and biopsy distributions, the biopsy
request confirmation and the sample-to-diagnosis time by ICD-10 code. Stage states and
dates are published on the diagnostic reports up to a cut-off, with their provenance
(structured link, temporal association, ambiguous or pending). Patient search takes age
bounds and a partial name or identifier. Each measure keeps the referral PPVs and the
screening-round strata already in the branch.
2026-11-27 18:43:47 -06:00
edgar f7faab7b56 CaCu KPIs: referral PPVs and screening-round breakdowns
Two PPVs, of the referral to colposcopy and to biopsy: of the patients with the
procedure in the period, those with histology LIEBG+. Each takes the latest
cytology sampled and reported strictly before its own procedure (up to 365 days
before), so no biopsy-cytology link is needed. A colposcopy is confirmed by a
biopsy requested that day. Once per patient, her first qualifying procedure;
cases are left out. Breakdowns: cytology (ASCUS+, LSIL+, HSIL+, overlapping),
histology (LIEBG+, LIEAG+, invasive, one denominator) and initial or
subsequent screening. Gold gives the facts and the measure chooses, so an
as-of evaluation picks among the cytologies known then.

The cytology distribution (CACU_EU7) gains the screening round and the results
within each round.

Still to confirm clinically: the 365 days, same-day biopsy matching and ASC-H in
LSIL+. The previous confirmation measure stays.

tests/ pass. On hospital_cacu a temporary copy of the end-to-end test, which
left the new measures and breakdowns out of the reference comparison, loaded,
built and compared, then stopped at HL7 validation (no validator configured).
WebApi/tests/test_cacu.py itself now fails: its reference lacks the new
measures and breakdowns. Web app labels are pending.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJFdw3mNQ5GUFgzwz1
2026-11-27 17:43:06 -06:00
edgar 67b551867a CaCu cytology: the sample date is the form's reception date
sample_date is "Fecha de recepción", not the form's "Fecha" at the top. Both the
cytology and the HPV steps read it, since it is the cytology's key: reading
different dates would split one cytology in two. "Fecha de interpretación"
stays the report date, which also dates the HPV result.

In the synthetic form the top date now comes 1-4 days before reception, so the
two can't be confused. Records already loaded by the old date, if it differed,
would get a new key on reprocessing.

Checked on a fake digital form: both steps read the reception date. The test
suite is deferred until all the new fields are in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJFdw3mNQ5GUFgzwz1
2026-11-27 16:45:54 -06:00
edgar 16b56b9457 CaCu cytology: take the result only from the squamous cell abnormalities answer
result was the first "negativo" or grade anywhere in the document. It is now
only the answer under "Anomalías en células escamosas", in the form's wording,
where "NO" is NILM; the section on epithelial abnormalities never sets it.
On a shared line a lone "NO" may be the neighbouring box's, so it stays empty.
ConceptMap, LLM hint and the synthetic form follow.

Checked on fake digital forms of the synthetic layout: no field took another's
text; the lone "NO" is the one answer missed. The test suite is deferred until
all the new fields are in; scans, OCR and the LLM path are untested.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJFdw3mNQ5GUFgzwz1
2026-11-27 16:22:04 -06:00
edgar b7f1b54f72 CaCu cytology: additional findings as the cytologist confirmed them
No grades or scales: the inflammation severity field and its code system are
gone (the raw text keeps the grade). The two endometrial-cell findings are one,
for 40 or older. Catalog, ConceptMap, extraction and synthetic site.

Tests are deferred until all the new fields are in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJFdw3mNQ5GUFgzwz1
2026-11-27 16:03:20 -06:00
edgar f79421dd49 CaCu cytology: capture the cytologist's additional findings (data capture)
Free text on the form, known with the report: the text as written, the
inflammation grade, and 28 booleans that are true when a whole statement says
the finding, otherwise unknown. Catalog, ConceptMap, extraction patterns and
LLM hint, and a findings box in the synthetic form.

ConceptMap lookup now ignores line breaks and repeated spaces (all fields),
since a captured phrase can wrap.

The findings section's boundaries and punctuation are assumed; no real sample
yet. Pending: web app labels; evidence in gold if a use needs it.
Tests are deferred until all the new fields are in; the patterns and OCR are
untested.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJFdw3mNQ5GUFgzwz1
2026-11-27 15:42:46 -06:00
edgar 2badff4ffc CaCu cytology: capture cervix_exam (data capture)
The form's "A la exploración se observa", recorded by the nurse at the sample:
catalog field and code system, ConceptMap, extraction pattern and LLM hint,
and the synthetic site.

Pending: evidence in gold (cohorts, KPIs, models), web app labels.
Tests are deferred until all the new fields are in; the pattern and OCR are
untested.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJFdw3mNQ5GUFgzwz1
2026-11-27 15:38:33 -06:00
edgar 578c6b3bcc CaCu cytology: capture "actualmente presenta" (data capture)
Four booleans recorded at the sample: the recorded answer is true, the others
stay unknown, never false. Catalog, ConceptMap, extraction patterns and LLM
hint, and the synthetic site.

Pending: evidence in gold (cohorts, KPIs, models), web app labels.
Tests are deferred until all the new fields are in; the patterns and OCR are
untested.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 14:50:23 -06:00
edgar 009f9e2727 CaCu cytology: capture gynaecological/obstetric conditions (data capture)
The form's "Condiciones ginecoobstétricas a la detección" as eight booleans
recorded at the sample. The source records only one, so the others stay
unknown, never false. Catalog, ConceptMap, extraction patterns and LLM hint,
and the synthetic site.

Pending: evidence in gold (cohorts, KPIs, models), web app labels.
Tests are deferred until all the new fields are in; the patterns and OCR are
untested.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 14:36:07 -06:00
edgar 765c24bf37 CaCu cytology: capture screening_history (data capture)
The form's "Detección de cáncer de cérvix": catalog field and code system,
the site's ConceptMap, its extraction pattern and LLM hint, and the four
answers in the synthetic site.

Pending: KPI stratifier, cohorts, web app labels.
Tests are deferred until all the new fields are in; the pattern and OCR are
untested.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 14:33:32 -06:00
Roberto Treviño 359c2415b4 Erick's site: OCR stage look-alikes in its map; review conflicts as an anti-join
ci / python (push) Successful in 48m49s
ci / web (push) Successful in 13m20s
2026-11-27 05:07:54 -06:00
Roberto Treviño 0bbbdaa130 ISSSTELEON's test source as the site: SQL Server ArchivosUni and ResultadosSubrogados in its layouts, fed by Synthea; cervical screening module as NOM-014 runs it 2026-11-27 01:45:16 -06:00
Roberto Treviño 23d8135040 CaMa catalog: biopsy results, stage and treatments; Synthea breast screening module and FHIR door pipeline
ci / python (push) Successful in 35m29s
ci / web (push) Successful in 8m37s
2026-11-26 19:03:39 -06:00
Roberto Treviño e13ae70e1c Files kept once at the source and carried by hash; reference cohorts loaded by a pipeline; tests drop dlt's staging schemas
ci / python (push) Failing after 36m49s
ci / web (push) Failing after 14m48s
2026-11-26 14:25:54 -06:00
Roberto Treviño d9f7d22029 Phase 4 part 2: TEA catalog, pipeline, gold and indicators, files kept by hash, EEG tables, status-at-period-end measures, ADOS-2 scoring
ci / python (push) Successful in 41m39s
ci / web (push) Successful in 10m36s
2026-11-26 07:06:53 -06:00
Roberto Treviño 266d0f876e Phase 4 part 1: domains as packages, CaMa measures and follow-up from gold, shared survival cohorts, references recaptured (CaMa, CaCu survival, TEA curves, CaMa recurrence) 2026-11-25 23:20:53 -06:00
Roberto Treviño 5d88098cea Names keep accents and ñ in silver; synthetic registry names written with them
ci / python (push) Successful in 28m32s
ci / web (push) Successful in 6m35s
2026-11-25 17:39:32 -06:00
Roberto Treviño 6de1175a7d Phase 3.5: catalog in Core, long silver with generated views, ConceptMaps, FHIR door, stable person ids; Synthea in tests
ci / python (push) Successful in 28m51s
ci / web (push) Successful in 6m53s
2026-11-25 16:17:24 -06:00
Roberto Treviño df3a819e5a WebApp: page tests serve on IPv4
ci / python (push) Successful in 18m3s
ci / web (push) Successful in 7m56s
2026-11-25 11:06:54 -06:00
Roberto Treviño 1c93ebc0b3 Phase 3: FHIR mappers and conformance in Core, follow-up gold table, HL7 validator in the test image and CI, page tests in the web job
ci / python (push) Successful in 18m16s
ci / web (push) Failing after 8m57s
2026-11-25 10:21:34 -06:00
Roberto Treviño 1d70946400 Phase 2 CaCu: hospital to silver, gold timeline, cohorts and measures, model registry
ci / python (push) Successful in 15m55s
ci / web (push) Failing after 1m14s
2026-11-25 01:16:45 -06:00
Roberto Treviño 1652a83722 CaCu reference recaptured at the last load; CaCu clinical parameters; models submodule 2026-11-25 00:28:43 -06:00
Roberto Treviño 75a5203219 Split patients: every split reaches review, decisions apply on the next run; stable record ids 2026-11-24 22:35:13 -06:00
Roberto Treviño d123f0105b Step 5: conectar API, masked secrets, review reads; every port on BIND_ADDRESS 2026-11-24 21:00:52 -06:00
Roberto Treviño 91b681c6f8 Silver from the graph: targets stage, dbt places, reviewers reject; pdfplumber layout text, deskewed OCR 2026-11-24 20:05:29 -06:00
Roberto Treviño 8a84cf48af Ingestion as a node graph DSL: typed nodes and edges, one output table per node 2026-11-24 18:20:28 -06:00
Roberto Treviño be66aa7fb2 Ingestion stages 1-2: dlt sources by import path, MarkItDown and OCRmyPDF, test image 2026-11-24 17:48:19 -06:00
Roberto Treviño be1e5daa92 Synthetic messy site: split identity, three PDF layouts, scans, conflicts 2026-11-24 17:06:15 -06:00
Roberto Treviño 4724b156b1 Core: platform schema and runtime ingestion config 2026-11-24 17:04:26 -06:00
Roberto Treviño ccf046ed9c Capture TEA reference outputs
ci / python (push) Successful in 2m44s
ci / postgres (push) Successful in 3m7s
ci / web (push) Successful in 1m32s
2026-11-24 12:46:52 -06:00
Roberto Treviño 9eb7ae6b12 Capture external models and per-EEG metrics
ci / python (push) Successful in 3m9s
ci / postgres (push) Successful in 3m0s
ci / web (push) Successful in 1m26s
2026-11-24 12:34:32 -06:00
Roberto Treviño 881df88ac1 Start the daemon and API once the code location has loaded
ci / python (push) Successful in 3m2s
ci / postgres (push) Successful in 3m56s
ci / web (push) Successful in 2m5s
2026-11-24 12:25:12 -06:00
Roberto Treviño 38fd443322 Capture CaMa reference outputs
ci / python (push) Successful in 4m28s
ci / postgres (push) Successful in 3m40s
ci / web (push) Successful in 1m45s
2026-11-24 12:07:51 -06:00
Roberto Treviño a00fec1946 Capture CaCu reference outputs
ci / python (push) Successful in 3m43s
ci / postgres (push) Successful in 4m23s
ci / web (push) Successful in 2m20s
2026-11-24 11:59:50 -06:00
rockdrigo bec066e0e6 Prepare the dbt manifest with dagster-dbt in CI and the image
ci / python (push) Successful in 3m28s
ci / postgres (push) Successful in 3m23s
ci / web (push) Successful in 1m44s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 11:50:47 -06:00
rockdrigo 0fb0b22093 Add the synthetic hospital databases to the fixtures
ci / python (push) Failing after 2m7s
ci / postgres (push) Failing after 1m46s
ci / web (push) Successful in 1m42s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 11:42:18 -06:00
rockdrigo 7c078dc6db Synthetic hospital from the reference instances' generator; WAL on silver
ci / python (push) Failing after 1m44s
ci / postgres (push) Failing after 1m44s
ci / web (push) Successful in 1m52s
- tests/fixtures/hospital: the CaCu and CaMa hospitals the dev-data poblar images
  build for the reference instances (seed 7), with a manifest; data only.
- The sample source reads the hospital with dlt's sql_table (types by reflection).
- synthetic/ now only renders an ArchivosUni table of PDFs from those rows.
- dbt sets WAL on the silver file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 11:42:09 -06:00
rockdrigo 0a0c467db8 Rebuild phase 0: uv workspace, layering contracts, CI, compose, synthetic hospital
ci / python (push) Failing after 4s
ci / postgres (push) Failing after 5s
ci / web (push) Failing after 3s
Orphan branch: nothing from the current platform is carried over.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 11:18:18 -06:00
484 changed files with 113135 additions and 21520 deletions
+7 -16
View File
@@ -1,16 +1,7 @@
# Read by the webapi build, whose context is the repo root.
.git/
WebApp/
**/__pycache__/
**/*.pyc
**/.venv/
**/*.egg-info/
**/.pytest_cache/
**/*.db
**/uv.lock
!WebApi/uv.lock
dist/
# The image compiles its own manifest.
Transformation/target/
Transformation/logs/
**/node_modules/
.venv
data
**/__pycache__
**/target
**/logs
WebApp
.git
-32
View File
@@ -1,32 +0,0 @@
# Copy to .env (docker compose reads it for the webapi service; Persistance's
# settings also read a .env in the working directory when run directly).
# --- Target databases (one per domain; SQLite files by default) ---
# CACU_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_cacu
# CAMA_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_cama
# TEA_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_tea
# GOVERNANCE_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_governance
CACU_DATABASE_URL=sqlite:////data/cacu.db
CAMA_DATABASE_URL=sqlite:////data/cama.db
TEA_DATABASE_URL=sqlite:////data/tea.db
# Stored predictions and the OCR extraction log.
GOVERNANCE_DATABASE_URL=sqlite:////data/governance.db
# --- SQL import sources a client may point the server at ---
# SQLAlchemy backend names. sqlite is excluded on purpose: its URL is a
# path on this server's disk.
WEBAPI_SQL_ALLOWED_DIALECTS=mysql,mariadb,postgresql,mssql
# Optional host allowlist (unset = any host reachable from the server).
# WEBAPI_SQL_ALLOWED_HOSTS=10.0.0.5,his-db.internal
# --- WebApi process ---
# Max request size (files travel inside import requests). Keep nginx's
# client_max_body_size (WebApp/nginx.conf) about 35% above it.
WEBAPI_MAX_UPLOAD_MB=200
# WEBAPI_WORKERS=2
# Seconds; OCR over many scanned pages runs inside one request.
# WEBAPI_TIMEOUT=600
# Tesseract languages for scanned documents.
# EXTRACTION_OCR_LANG=spa+eng
# Only for browser clients on another origin (the WebApp uses the proxy).
# WEBAPI_CORS_ORIGINS=https://example.internal
+106
View File
@@ -0,0 +1,106 @@
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
+9 -16
View File
@@ -1,17 +1,10 @@
# Local notes.
CLAUDE.md
AGENTS.md
HANDOFF*.md
# Local environment (database credentials); docker-compose reads it but git
# must never see it. Committed template lives in .env.example.
.venv/
__pycache__/
data/
*.db
.dlt/
.pytest_cache/
.ruff_cache/
compose.override.yml
!tests/fixtures/**/*.db
.env
.DS_Store
# Deliverable bundle: images and local state are built/created, not versioned.
dist/imagenes/
dist/.env
dist/datos/
dist/*.tar.gz
graphify-out/
+6 -3
View File
@@ -1,9 +1,12 @@
[submodule "WebApp"]
path = WebApp
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApp.git
[submodule "WebApi"]
path = WebApi
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApi.git
branch = rebuild
[submodule "WebApp"]
path = WebApp
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApp.git
branch = rebuild
[submodule "models"]
path = models
url = ssh://git@10.0.10.41:2222/ISSSTELEON/models.git
branch = rebuild
+26
View File
@@ -0,0 +1,26 @@
[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
@@ -0,0 +1 @@
3.12
-8
View File
@@ -1,8 +0,0 @@
__pycache__/
*.pyc
.venv/
.pytest_cache/
.coverage
*.egg-info/
.env
uv.lock
+92
View File
@@ -0,0 +1,92 @@
"""CaCu clinical parameters: the one place they are set. dbt reads them as vars, the models
import them. Codes are the platform's (core.schema)."""
# Biopsy grades that count as CIN2+ (the outcome) and as invasive cancer.
CIN2_PLUS = ["HSIL", "CIS", "carcinoma"]
CANCER = ["carcinoma"]
CASE = ["CIS", "carcinoma"] # a biopsy this grade makes her a case: she has cancer
# The follow-up list: patients with a cytology sampled within the window before the cut-off.
FOLLOW_UP_WINDOWS = [1, 3, 6, 12] # months
FOLLOW_UP_WINDOW = 3
# Index cytology in the six KPNC categories, least to most severe.
KPNC = {
"NILM": ["NILM"],
"ASC-US": ["ASC-US"],
"LSIL": ["LSIL"],
"ASC-H": ["ASC-H"],
"AGC": ["AGC"],
"HSIL+": ["HSIL", "CIS", "adenocarcinoma"],
}
# The three categories used after colposcopy and after treatment.
KPNC_3 = {
"NILM": ["NILM"],
"ASC-US/LSIL": ["ASC-US", "LSIL"],
"High Grade": ["ASC-H", "AGC", "HSIL", "CIS", "adenocarcinoma"],
}
# The referral PPVs (core.cacu.measures.ReferralPPV). Cytology groups overlap: each holds its
# grade and every more severe squamous one. Histology levels are numerators over one
# denominator; the first is the measure's score.
PPV_CYTOLOGY = {
"ASCUS+": ["ASC-US", "LSIL", "ASC-H", "HSIL", "CIS"],
"LSIL+": ["LSIL", "ASC-H", "HSIL", "CIS"],
"HSIL+": ["HSIL", "CIS"],
}
PPV_HISTOLOGY = {"LIEBG+": ["LSIL", *CIN2_PLUS], "LIEAG+": CIN2_PLUS, "invasive": CANCER}
PREVIOUS_SCREENING = ["1_year_or_less", "2_years", "3_years_or_more"] # screening_history
REFERRAL_CYTOLOGY_DAYS = 365 # the referring cytology's report is at most this old
# Results that show a patient free of CIN2+ at a visit: a negative co-test (both within
# INDEX_SAMPLE_DAYS of each other), or a biopsy below the outcome grades.
KNOWN_NEGATIVE = {"bethesda": ["NILM", "ASC-US"], "hpv": ["negative"]}
INDEX_SAMPLE_DAYS = 30 # results this many days after the index sample still describe it
PREVALENT_WINDOW_DAYS = 6 * 365.25 / 12 # an outcome this soon was there at the index
DAYS_PER_YEAR = 365.25
# Recruitment windows (start inclusive, end exclusive).
RECRUITMENT = ("2018-01-01", "2027-01-01")
POST_TREATMENT_RECRUITMENT = ("2024-01-01", "2027-01-01")
POST_TREATMENT_INDEX_AFTER_DAYS = 90 # the index cytology comes this long after treatment
POST_TREATMENT_LOOKBACK_DAYS = 365 # a biopsy result this long before treatment is required
POST_COLPOSCOPY_VISIT = 1 # index: the k-th surveillance cytology after the colposcopy result
REFERRAL_LOOKBACK_DAYS = 365 # results this long before colposcopy are why she was referred
HYSTERECTOMY_ICD10 = ["Z907"]
# Inferred procedures, from clinical notes (ICD-10 without the dot).
# Specialties are the platform's codes; each site's pipeline maps its own names to them.
DIAGNOSIS_SPECIALTIES = ["colposcopy", "oncology_surgery"]
COLPOSCOPY_SPECIALTIES = ["colposcopy"]
SAMPLE_TO_DIAGNOSIS_DAYS = 120 # a diagnosis note this soon after a sample assesses it
DIAGNOSIS_ICD10 = [
"Z014", "Z124", "B977", "R876", "N87", "N870", "N871", "N872", "N879",
"D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539",
] # fmt: skip
HISTORY_ICD10 = ["D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539"]
TREATMENT_ICD10 = ["D06", "D060", "D061", "D067", "D069"]
COLPOSCOPY_ICD10 = ["R876", "N87", "N870", "N871", "N872", "N879", "B977"]
COLPOSCOPY_REASONS = ["ACUDE A COLPOSCOPIA", "COLPOSCOPIA"]
COLPOSCOPY_DIAGNOSES = ["VIRUS DEL PAPILOMA HUMANO"]
SURVEILLANCE_SPECIALTIES = ["family_medicine", "colposcopy"]
# Measures (core.measures): the horizons of the screening route, in days; an interval
# that hasn't ended after its horizon counts as not ended.
HORIZONS = {
"sample_to_report": 60, "sample_to_treatment": 180, "diagnosis_to_treatment": 60,
"sample_to_colposcopy": 60, "sample_to_biopsy": 60, "result_to_colposcopy": 60,
"colposcopy_to_biopsy": 60, "biopsy_to_diagnosis": 60,
} # fmt: skip
ABNORMAL = ["ASC-US", "ASC-H", "LSIL", "HSIL", "CIS"] # IND1
HIGH_GRADE = ["ASC-H", "HSIL", "CIS"] # cytology that should be confirmed by biopsy
DETECTION = ["HSIL", "CIS", "carcinoma"] # biopsy grades counted as detected (EU13)
BIOPSY_SEVERITY = ["normal", "LSIL", "HSIL", "CIS", "carcinoma"] # least to most severe
AGE_GROUPS = [(25, 34), (35, 44), (45, 54), (55, 64)] # plus "<25" and "65+"
RISK_BAND_MODEL = "cacu.cin2_pim" # whose risk at the index visit is banded (surveillance)
RISK_BANDS = [("low", 0.04), ("intermediate", 0.25), ("high", None)] # below each cut
def dbt_vars() -> dict:
"""What dbt reads (`var('cacu')`)."""
return {k.lower(): v for k, v in globals().items() if k.isupper()}
-12
View File
@@ -1,12 +0,0 @@
import sqlalchemy.orm as orm
from sqlmodel import SQLModel
registry = orm.registry()
class CaCuModel(SQLModel, registry=registry):
"""Base class for every CaCu table.
Uses its own SQLAlchemy registry so table names such as `notamedica`
don't collide with CaMa's tables of the same name.
"""
@@ -1,34 +0,0 @@
## biometria_hematica
Tabla de resultados de laboratorio, 1 fila por reporte de biometría hemática.
Fuente: extracción OCR y NLP sobre PDF vinculado en Estudios Laboratorio (BH1).
Join hacia ordenes_estudio por ord_numero_hospital (lógico, sin FK constraint). Join hacia paciente por pac_id_hospital (resuelto en carga).
| Columna | Fuente | Descripción |
| ------------------------------ | -------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `bh_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | Join lógico hacia paciente.pac_id, resuelto en carga, nulo si no hay match al momento de ingesta |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, obligatorio para el join lógico hacia paciente |
| `ord_numero_hospital` | Hospital, BH4 | Número de orden HIS, join lógico hacia ordenes_estudio.ord_numero_hospital |
| `bh_fecha` | Hospital, BH2 | Fecha de solicitud del estudio; pendiente de distinción con BH3 (fecha resultado) según ETL |
| `eritrocitos_mill_ul` | Derivado, OCR sobre PDF BH1 | Conteo de eritrocitos (millones/µL) |
| `hemoglobina_g_dl` | Derivado, OCR sobre PDF BH1 | Concentración de hemoglobina (g/dL) |
| `hematocrito_pct` | Derivado, OCR sobre PDF BH1 | Hematocrito como porcentaje del volumen sanguíneo |
| `vcm_fl` | Derivado, OCR sobre PDF BH1 | Volumen corpuscular medio (fL) |
| `hcm_pg` | Derivado, OCR sobre PDF BH1 | Hemoglobina corpuscular media (pg) |
| `chcm_g_dl` | Derivado, OCR sobre PDF BH1 | Concentración de hemoglobina corpuscular media (g/dL) |
| `rdw_pct` | Derivado, OCR sobre PDF BH1 | Amplitud de distribución eritrocitaria (%) |
| `leucocitos_mil_ul` | Derivado, OCR sobre PDF BH1 | Conteo total de leucocitos (miles/µL) |
| `neutrofilos_pct` | Derivado, OCR sobre PDF BH1 | Neutrófilos totales como porcentaje del diferencial leucocitario |
| `linfocitos_pct` | Derivado, OCR sobre PDF BH1 | Linfocitos como porcentaje del diferencial leucocitario |
| `monocitos_pct` | Derivado, OCR sobre PDF BH1 | Monocitos como porcentaje del diferencial leucocitario |
| `eosinofilos_pct` | Derivado, OCR sobre PDF BH1 | Eosinófilos como porcentaje del diferencial leucocitario |
| `basofilos_pct` | Derivado, OCR sobre PDF BH1 | Basófilos como porcentaje del diferencial leucocitario |
| `neutrofilos_segmentados_pct` | Derivado, OCR sobre PDF BH1 | Neutrófilos segmentados, desglose del diferencial neutrofílico (%) |
| `neutrofilos_banda_pct` | Derivado, OCR sobre PDF BH1 | Neutrófilos en banda, desglose del diferencial neutrofílico (%) |
| `metamielocitos_pct` | Derivado, OCR sobre PDF BH1 | Metamielocitos, desglose del diferencial neutrofílico (%) |
| `mielocitos_pct` | Derivado, OCR sobre PDF BH1 | Mielocitos, desglose del diferencial neutrofílico (%) |
| `plaquetas_mil_ul` | Derivado, OCR sobre PDF BH1 | Conteo de plaquetas (miles/µL) |
| `vpm_fl` | Derivado, OCR sobre PDF BH1 | Volumen plaquetario medio (fL) |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
@@ -1 +0,0 @@
from core.cacu.biometria_hematica.model import BiometriaHematica
@@ -1,60 +0,0 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import HOSPITAL_ID_LENGTH
class BiometriaHematica(CaCuModel, table=True):
"""
Modelo ORM para biometría hemática.
No hay validación en esta capa, se almacena laxamente.
"""
bh_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# Logical join, resolved on import by looking up paciente.pac_id_hospital
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
# Hospital patient id: links studies to patients
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# Logical join to ordenes_estudio.ord_numero_hospital, no FK constraint
ord_numero_hospital: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
bh_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
eritrocitos_mill_ul: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
hemoglobina_g_dl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
hematocrito_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
vcm_fl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
hcm_pg: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
chcm_g_dl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
rdw_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
leucocitos_mil_ul: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
linfocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
monocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
basofilos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
eosinofilos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
neutrofilos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
mielocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
metamielocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
neutrofilos_banda_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
neutrofilos_segmentados_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
plaquetas_mil_ul: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
vpm_fl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
-21
View File
@@ -1,21 +0,0 @@
## biopsia_cervical
Tabla de resultados histopatológicos, 1 fila por reporte de biopsia cervical.
Fuente: extracción OCR y NLP sobre PDF vinculado en ordenes_estudio.
Join hacia ordenes_estudio por ord_numero_hospital (lógico, sin FK constraint). Join hacia paciente por pac_id_hospital (resuelto en carga).
| Columna | Fuente | Descripción |
| -------------------- | -------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `bx_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | Join lógico hacia paciente.pac_id, resuelto en carga, nulo si no hay match al momento de ingesta |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, obligatorio para el join lógico hacia paciente |
| `ord_numero_hospital`| Hospital, HPC1, TVPH1 | Número de orden HIS, join lógico hacia ordenes_estudio.ord_numero_hospital |
| `cit_id` | Derivado, FK citologiacervical | Citología cervical previa asociada, nulo si no documentada en el sistema |
| `bx_fecha_solicitud` | Hospital, HPC2 | Fecha de solicitud de la biopsia |
| `bx_fecha_reporte` | Derivado, OCR regex fecha | Fecha de emisión del reporte histopatológico por el patólogo |
| `bx_cin_grado` | Derivado, NLP regex PDF HPC1 | Grado CIN extraído del diagnóstico histopatológico, variable objetivo principal para modelos de riesgo |
| `bx_observaciones` | Hospital, — | Observaciones del reporte |
| `bx_ocr_confianza` | Derivado, pipeline OCR | Score de confianza global del motor OCR sobre el documento |
| `bx_pdf_blob` | Derivado, extracción ETL HPC1 | Contenido binario del PDF del reporte histopatológico |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
@@ -1 +0,0 @@
from core.cacu.biopsia_cervical.model import BiopsiaCervical
-22
View File
@@ -1,22 +0,0 @@
from enum import Enum
class GradoCIN(str, Enum):
NORMAL = "NORMAL"
LIEBG = "LIEBG" # histological low-grade — CIN1 equivalent
LIEAG = "LIEAG" # histological high-grade — CIN2/3 equivalent
CIS = "CIS" # carcinoma in situ
CARCINOMA = "CARCINOMA" # invasive
DESCONOCIDO = "DESCONOCIDO"
GRADO_CIN_ALIAS: dict[str, str] = {
"LESIÓN INTRAEPITELIAL ESCAMOSA DE BAJO GRADO": "LIEBG",
"LESION INTRAEPITELIAL ESCAMOSA DE BAJO GRADO": "LIEBG",
"LESIÓN INTRAEPITELIAL ESCAMOSA DE ALTO GRADO": "LIEAG",
"LESION INTRAEPITELIAL ESCAMOSA DE ALTO GRADO": "LIEAG",
"CARCINOMA IN SITU": "CIS",
"CARCINOMA INVASOR": "CARCINOMA",
# CIN/NIC grades as reports write them; CIN2 and CIN3 are both LIEAG.
"CIN1": "LIEBG", "CIN 1": "LIEBG", "CIN-1": "LIEBG", "NIC1": "LIEBG", "NIC 1": "LIEBG", "NIC-1": "LIEBG",
"CIN2": "LIEAG", "CIN 2": "LIEAG", "CIN-2": "LIEAG", "NIC2": "LIEAG", "NIC 2": "LIEAG", "NIC-2": "LIEAG",
"CIN3": "LIEAG", "CIN 3": "LIEAG", "CIN-3": "LIEAG", "NIC3": "LIEAG", "NIC 3": "LIEAG", "NIC-3": "LIEAG",
}
-82
View File
@@ -1,82 +0,0 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
class BiopsiaCervical(CaCuModel, table=True):
"""
Modelo ORM para biopsia cervical.
No hay validación en esta capa, se almacena laxamente.
"""
bx_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# Logical join, resolved on import by looking up paciente.pac_id_hospital
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
# Hospital patient id, required: links studies to patients
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# Logical join to ordenes_estudio.ord_numero_hospital, no FK constraint
ord_numero_hospital: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
cit_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("citologiacervical.cit_id"), index=True),
)
bx_fecha_solicitud: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
bx_fecha_reporte: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
bx_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Observaciones",
)
bx_cin_grado: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_pdf_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(FileBlob),
)
bx_ocr_confianza: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
# VAR-03
bx_ocr_estatus: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="valor de core.ocr.OcrEstatus guardado como texto",
)
bx_ocr_requiere_revision: Optional[bool] = Field(
default=None,
sa_column=sa.Column(sa.Boolean),
)
bx_ocr_metodo_principal: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_ocr_metodo_alternativo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
@@ -1,29 +0,0 @@
## citologia_cervical
Tabla de resultados, 1 fila por reporte citológico. Fuente: TC1-TC10, resultado VPH integrado (TVPH1).
Join hacia ordenes_estudio por ord_numero_hospital (lógico, sin FK constraint). Join hacia paciente por pac_id_hospital (resuelto en carga).
| Columna | Fuente | Descripción |
| --------------------------- | ------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `cit_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | Join lógico hacia paciente.pac_id, resuelto en carga, nulo si no hay match al momento de ingesta |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, obligatorio para el join lógico hacia paciente |
| `ord_numero_hospital` | Hospital, TC1, TVPH1 | Número de orden HIS, join lógico hacia ordenes_estudio.ord_numero_hospital |
| `cit_fecha_toma` | Hospital, TC1 | Fecha en que se realizó la toma de muestra |
| `cit_fecha_reporte` | Derivado, reporte VPH u otro | Fecha de disponibilidad del resultado para el paciente |
| `cit_calidad_especimen` | Hospital, TC5 | Calidad del espécimen según criterios del sistema Bethesda 2014 |
| `cit_dx_lesion` | Hospital, TC6 | Diagnóstico citológico general para lesión intraepitelial o malignidad |
| `cit_celulas_escamosas` | Hospital, TC7 | Categoría de anomalía en células escamosas según Bethesda |
| `cit_carcinoma_invasor` | Hospital, TC8 | Presencia de carcinoma epidermoide invasor |
| `cit_celulas_glandulares` | Hospital, TC9 | Categoría de anomalía en epitelio glandular según Bethesda |
| `cit_condiciones_ginecoobs` | Hospital, TC2 | Condiciones gineco-obstétricas al momento de la toma (embarazo, DIU, menopausia, etc.) |
| `cit_exploracion` | Hospital, TC4 | Hallazgos a la exploración: aspecto del cérvix, flujo, lesiones visibles |
| `cit_observaciones` | Hospital, TC10 | Observaciones libres del citólogo no capturadas en los campos estructurados |
| `cit_vph_resultado` | Derivado, OCR sobre PDF TVPH1 | Resultado cualitativo del tamizaje VPH co-solicitado con la citología |
| `cit_vph_genotipo_16` | Derivado, OCR sobre PDF TVPH1 | Detección específica de genotipo VPH-16 |
| `cit_vph_genotipo_18` | Derivado, OCR sobre PDF TVPH1 | Detección específica de genotipo VPH-18 |
| `cit_vph_ocr_confianza` | Derivado, pipeline OCR | Score de confianza global del motor OCR sobre el PDF VPH |
| `cit_pdf_blob` | Derivado, extracción ETL | Contenido binario del PDF del resultado citológico |
| `cit_vph_pdf_blob` | Derivado, extracción ETL TVPH1 | Contenido binario del PDF del resultado VPH, su presencia distingue VPH no solicitado de extracción fallida |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
@@ -1 +0,0 @@
from core.cacu.citologia_cervical.model import CitologiaCervical
@@ -1,41 +0,0 @@
from enum import Enum
class CelulasEscamosas(str, Enum):
"""
Resultado de celulas escamosas.
Los resultados de celulas escamosas estan en el sistema de terminos Bethesda.
Se normalizan para usar sus abreviaturas.
"""
NORMAL = "NORMAL"
ASC_US = "ASC-US"
ASC_H = "ASC-H"
LIEBG = "LIEBG"
LIEAG = "LIEAG"
CIS = "CIS"
CELULAS_ESCAMOSAS_ALIAS: dict[str,str] = {
# Long forms, as the hospital platform is expected to write them
"LESIÓN INTRAEPITELIAL ESCAMOSA DE BAJO GRADO (DISPLASIA LEVE Y/O VPH)": "LIEBG",
"LESION INTRAEPITELIAL ESCAMOSA DE BAJO GRADO (DISPLASIA LEVE Y/O VPH)": "LIEBG", # without accent
"LESIÓN INTRAEPITELIAL ESCAMOSA DE ALTO GRADO (DISPLASIA MODERADA Y GRAVE)": "LIEAG",
"LESION INTRAEPITELIAL ESCAMOSA DE ALTO GRADO (DISPLASIA MODERADA Y GRAVE)": "LIEAG",
"CARCINOMA IN SITU": "CIS",
# Bethesda "negative for intraepithelial lesion or malignancy" (NILM).
"NEGATIVO": "NORMAL",
"NILM": "NORMAL",
"NEGATIVO PARA LESION INTRAEPITELIAL O MALIGNIDAD": "NORMAL",
"NEGATIVO PARA LESIÓN INTRAEPITELIAL O MALIGNIDAD": "NORMAL",
}
CITO_CALIDAD_ESPECIMEN_ALIAS: dict[str,bool] = {
# String forms the source platforms are expected to send
"SATISFACTORIO": True,
"INSATISFACTORIO": False,
"1": True, # from JSON bool serialization
"0": False,
}
class ResultadoVPH(str, Enum):
POSITIVO = "POSITIVO"
NEGATIVO = "NEGATIVO"
INDETERMINADO = "INDETERMINADO" # extracted but ambiguous — not same as NULL
-122
View File
@@ -1,122 +0,0 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
class CitologiaCervical(CaCuModel, table=True):
cit_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# Logical join, resolved on import by looking up paciente.pac_id_hospital
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
# Hospital patient id, required: links studies to patients
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# Logical join to ordenes_estudio.ord_numero_hospital, no FK constraint
ord_numero_hospital: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
cit_fecha_toma: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha de toma de muestra",
)
cit_fecha_reporte: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha de disponibilidad de resultado para el paciente",
)
cit_calidad_especimen: Optional[str] = Field(
default=None
)
cit_pdf_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(FileBlob),
description="PDF de resultado",
)
cit_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Observaciones",
)
cit_condiciones_ginecoobs: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Condiciones gineco-obstétricas: embarazo, DIU, etc.",
)
cit_exploracion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Hallazgos en exploración",
)
cit_dx_lesion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="TC6 Diagnóstico citológico para lesión",
)
cit_celulas_glandulares: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="TC9 Anomalías del epitelio glandular",
)
cit_carcinoma_invasor: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="TC8 Carcinoma epidermoide invasor",
)
cit_celulas_escamosas: Optional[str] = Field(
default=None,
description="TC7 Anomalías de células escamosas"
)
cit_vph_pdf_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(FileBlob)
)
cit_vph_ocr_confianza: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float)
)
cit_vph_resultado: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text)
)
cit_vph_genotipo_16: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer)
)
cit_vph_genotipo_18: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer)
)
# VAR-03: besides the confidence, the status, the manual-review flag and the
# method (main or fallback) that produced the value.
cit_vph_ocr_estatus: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="valor de core.ocr.OcrEstatus guardado como texto",
)
cit_vph_ocr_requiere_revision: Optional[bool] = Field(
default=None,
sa_column=sa.Column(sa.Boolean),
)
cit_vph_ocr_metodo_principal: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
cit_vph_ocr_metodo_alternativo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
-6
View File
@@ -1,6 +0,0 @@
from core.cacu.paciente.enums import SexoBiologico, SEXO_BIOLOGICO_ALIAS
from core.cacu.citologia_cervical.enums import CelulasEscamosas, CELULAS_ESCAMOSAS_ALIAS, CITO_CALIDAD_ESPECIMEN_ALIAS, ResultadoVPH
from core.cacu.biopsia_cervical.enums import GradoCIN, GRADO_CIN_ALIAS
from core.cacu.nota_medica.enums import TipoNota, TIPO_NOTA_ALIAS, Especialidad, ESPECIALIDAD_ALIAS, Parentesco, PARENTESCO_ALIAS, Dependencia, DEPENDENCIA_ALIAS
from core.cacu.ordenes_estudio.enums import TipoEstudio, TIPO_ESTUDIO_ALIAS
from core.cacu.episodio_clinico.enums import TipoEpisodio, TIPO_EPISODIO_ALIAS
-17
View File
@@ -1,17 +0,0 @@
from enum import Enum
class TipoEpisodio(str, Enum):
"""IND-02: la unidad de análisis para evaluación de desempeño del
modelo es un episodio de tamizaje, diagnóstico o tratamiento."""
TAMIZAJE = "TAMIZAJE"
DIAGNOSTICO = "DIAGNOSTICO"
TRATAMIENTO = "TRATAMIENTO"
TIPO_EPISODIO_ALIAS: dict[str, str] = {
"SCREENING": "TAMIZAJE",
"DIAGNOSTIC": "DIAGNOSTICO",
"TREATMENT": "TRATAMIENTO",
}
-72
View File
@@ -1,72 +0,0 @@
from datetime import date, datetime, timezone
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import HOSPITAL_ID_LENGTH
class EpisodioClinico(CaCuModel, table=True):
"""IND-02/IND-03: a screening, diagnosis or treatment episode, the unit
of analysis for model evaluation.
An episode combines a CIE10 code and medical specialty, a time window
bounded by the previous episode (`episodio_anterior_id`), and the medical
note it originates from (`nm_id`). The CIE10 code and specialty are
usually copied from `NotaMedica` and stored here so episodes can be
filtered without joining back to the note. Storage only; building
episodes from notes and orders is not implemented yet.
"""
episodio_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
)
tipo_episodio: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="valor de core.cacu.episodio_clinico.enums.TipoEpisodio guardado como texto",
)
nm_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("notamedica.nm_id"), index=True),
description="nota médica cuyo contenido escrito origina/documenta el episodio",
)
cie10_codigo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
especialidad_medica: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
evento_fecha: date = Field(
sa_column=sa.Column(sa.Date, nullable=False),
description="fecha del evento de interés que define el episodio",
)
ventana_inicio: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="inicio de la ventana de tiempo fija delimitada a partir del evento anterior",
)
ventana_fin: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
episodio_anterior_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("episodioclinico.episodio_id"), index=True),
description="evento anterior que delimita la ventana de este episodio",
)
created_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_column=sa.Column(sa.DateTime, nullable=False),
)
+55
View File
@@ -0,0 +1,55 @@
"""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)
-214
View File
@@ -1,214 +0,0 @@
"""Las tablas de indicadores_kit en el dominio CaCu.
Viven en el registro de `CaCuModel`, en la misma base que el staging de
CaCu (ADR-004). Las columnas se declaran una vez en `core.indicadores`;
aquí solo se instancian. Ninguna llave foránea apunta a una tabla de
staging: `persona` es propia aunque repita a `paciente`.
"""
from core.cacu.base import CaCuModel
from core.indicadores.cohortes import (
CohorteArmadoBase,
CohorteExclusionBase,
CohorteMiembroBase,
CohorteVariableBase,
EvaluacionRiesgoBase,
EvaluacionRiesgoLoteBase,
armado_unico,
evaluacion_unica,
variable_con_un_valor,
)
from core.indicadores.catalogos import (
CatEstudioBase,
CatMapeoBase,
CatResultadoBase,
CatSistemaFuenteBase,
CatValorBase,
estado_de_valor_conocido,
reglas_de_mapeo,
tipo_de_valor_conocido,
vigencia_ordenada,
)
from core.indicadores.plata import (
ObservacionClinicaBase,
ProcedimientoClinicoBase,
clase_conocida,
indice_de_observacion,
indice_de_procedimiento,
observacion_en_catalogo,
llave_de_observacion,
llave_de_procedimiento,
)
from core.indicadores.comunes import CargaBase, PeriodoObservacionBase, PersonaDerechohabienteBase
from core.indicadores.registro import (
DefParametroBase,
DimFechaBase,
DimGrupoEdadBase,
DimPeriodoBase,
)
from core.indicadores.publicacion import (
CatEstratoBase,
CatEstratoValorBase,
CatMeasureBase,
CatMeasureEstratoBase,
CatMeasureGrupoBase,
CatMeasureResultadoBase,
CatMeasureValorBase,
MeasureReportUnidadBase,
MeasureReportUnidadEstratoBase,
contrato_y_unidad_conocidos,
origen_conocido,
poblacion_conocida,
una_poblacion_por_indicador,
unidad_de_estrato_conocida,
valor_de_estrato_en_catalogo,
)
from core.indicadores.reportes import (
MeasureReportBase,
)
class Persona(CaCuModel, PersonaDerechohabienteBase, table=True):
__tablename__ = "persona"
class PeriodoObservacion(CaCuModel, PeriodoObservacionBase, table=True):
__tablename__ = "periodo_observacion"
class Carga(CaCuModel, CargaBase, table=True):
__tablename__ = "carga"
class DefParametro(CaCuModel, DefParametroBase, table=True):
__tablename__ = "def_parametro"
class DimPeriodo(CaCuModel, DimPeriodoBase, table=True):
__tablename__ = "dim_periodo"
class DimFecha(CaCuModel, DimFechaBase, table=True):
__tablename__ = "dim_fecha"
class DimGrupoEdad(CaCuModel, DimGrupoEdadBase, table=True):
__tablename__ = "dim_grupo_edad"
class MeasureReport(CaCuModel, MeasureReportBase, table=True):
__tablename__ = "measure_report"
# --- El oro por unidad y su catálogo (§6f, MD-19) ---
class CatMeasure(CaCuModel, CatMeasureBase, table=True):
__tablename__ = "cat_measure"
__table_args__ = contrato_y_unidad_conocidos()
class CatMeasureResultado(CaCuModel, CatMeasureResultadoBase, table=True):
__tablename__ = "cat_measure_resultado"
__table_args__ = (poblacion_conocida(), una_poblacion_por_indicador())
class CatMeasureValor(CaCuModel, CatMeasureValorBase, table=True):
__tablename__ = "cat_measure_valor"
__table_args__ = (origen_conocido(),)
class CatMeasureGrupo(CaCuModel, CatMeasureGrupoBase, table=True):
__tablename__ = "cat_measure_grupo"
class CatEstrato(CaCuModel, CatEstratoBase, table=True):
__tablename__ = "cat_estrato"
__table_args__ = (unidad_de_estrato_conocida(),)
class CatEstratoValor(CaCuModel, CatEstratoValorBase, table=True):
__tablename__ = "cat_estrato_valor"
class CatMeasureEstrato(CaCuModel, CatMeasureEstratoBase, table=True):
__tablename__ = "cat_measure_estrato"
class MeasureReportUnidad(CaCuModel, MeasureReportUnidadBase, table=True):
__tablename__ = "measure_report_unidad"
class MeasureReportUnidadEstrato(CaCuModel, MeasureReportUnidadEstratoBase, table=True):
__tablename__ = "measure_report_unidad_estrato"
__table_args__ = (valor_de_estrato_en_catalogo(),)
# --- Catálogos de la plata (F1): estudio -> resultado -> valor, de core/catalogos/cacu.toml ---
class CatEstudio(CaCuModel, CatEstudioBase, table=True):
__tablename__ = "cat_estudio"
class CatResultado(CaCuModel, CatResultadoBase, table=True):
__tablename__ = "cat_resultado"
__table_args__ = (tipo_de_valor_conocido(),)
class CatValor(CaCuModel, CatValorBase, table=True):
__tablename__ = "cat_valor"
__table_args__ = (estado_de_valor_conocido(),)
class CatSistemaFuente(CaCuModel, CatSistemaFuenteBase, table=True):
__tablename__ = "cat_sistema_fuente"
__table_args__ = (vigencia_ordenada("cat_sistema_fuente"),)
class CatMapeo(CaCuModel, CatMapeoBase, table=True):
__tablename__ = "cat_mapeo"
__table_args__ = reglas_de_mapeo()
# --- La plata de dos tablas (F5, ADR-MD-007) ---
class Procedimiento(CaCuModel, ProcedimientoClinicoBase, table=True):
__tablename__ = "procedimiento"
__table_args__ = (clase_conocida(), llave_de_procedimiento(), indice_de_procedimiento())
class Observacion(CaCuModel, ObservacionClinicaBase, table=True):
__tablename__ = "observacion_clinica" # `observacion` choca con la CTE `observacion` del motor (T-18r)
__table_args__ = (*observacion_en_catalogo(), llave_de_observacion(), indice_de_observacion())
# --- Cohortes para modelos y estimaciones de riesgo (oro restringido, ADR-MD-003) ---
class CohorteArmado(CaCuModel, CohorteArmadoBase, table=True):
__tablename__ = "cohorte_armado"
__table_args__ = (armado_unico(),)
class CohorteMiembro(CaCuModel, CohorteMiembroBase, table=True):
__tablename__ = "cohorte_miembro"
class CohorteExclusion(CaCuModel, CohorteExclusionBase, table=True):
__tablename__ = "cohorte_exclusion"
class CohorteVariable(CaCuModel, CohorteVariableBase, table=True):
__tablename__ = "cohorte_variable"
__table_args__ = (variable_con_un_valor(),)
class EvaluacionRiesgoLote(CaCuModel, EvaluacionRiesgoLoteBase, table=True):
__tablename__ = "evaluacion_riesgo_lote"
class EvaluacionRiesgo(CaCuModel, EvaluacionRiesgoBase, table=True):
__tablename__ = "evaluacion_riesgo"
__table_args__ = (evaluacion_unica(),)
+386
View File
@@ -0,0 +1,386 @@
"""CaCu's measures (`core.measures` evaluates them) and the follow-up status they stratify by."""
from dataclasses import dataclass
from datetime import date
import statistics
from core import cacu
from core.measures import (
NO_BIOPSY,
NO_DATA,
Composition,
Duration,
Measure,
Period,
Proportion,
Result,
RiskBand,
Result,
age_group,
as_day,
desc,
wilson,
)
def follow_up_status(row: dict, at: date, through: bool = False) -> str:
"""Where the patient was in her follow-up just before `at` (`through`: by the end of
`at`), from the first day of each step (`gold.cacu_follow_up`). A case already has
cancer; what follows her is survival."""
def by(first: str) -> bool:
day = as_day(row.get(first))
return day is not None and (day <= at if through else day < at)
for first, status in (("first_case", "case"), ("first_treatment", "post_treatment"),
("first_colposcopy", "post_colposcopy")): # fmt: skip
if by(first):
return status
return "pre_colposcopy"
def valid(row: dict) -> bool:
"""A cytology with a result, reported, of satisfactory (or unknown) adequacy."""
return row["result_date"] is not None and row.get("adequacy") != "unsatisfactory"
def latest(row: dict) -> tuple:
"""A patient's latest valid sample ranks highest."""
return valid(row), as_day(row["sample_date"]), row["sample_id"]
def latest_most_severe_biopsy(row: dict) -> tuple:
"""Her latest valid sample, then its most severe reported biopsy, the latest first."""
reported = row.get("biopsy_report_date") is not None
return (*latest(row), reported, row.get("severity") or 0,
desc(as_day(row.get("biopsy_report_date"))), desc(row.get("biopsy_id"))) # fmt: skip
def result(row: dict) -> str:
return row["result"] if valid(row) else NO_DATA
def histology(row: dict) -> str:
"""The chosen biopsy's histology (NO_BIOPSY without one reported)."""
if not valid(row):
return NO_DATA
if row.get("biopsy_report_date") is None:
return NO_BIOPSY
return row.get("histology") or NO_DATA
@dataclass(frozen=True)
class BiopsyRequests:
"""Recorded request units, classified at the event cutoff, not all HIS referrals."""
kind: str = "composition"
def evaluate(self, rows, period, cutoff):
chosen = {}
severity = {grade: i for i, grade in enumerate(cacu.BIOPSY_SEVERITY, 1)}
for row in rows:
request = as_day(row.get("request_date"))
if request not in period or request > cutoff:
continue
reported = as_day(row.get("report_date"))
if (row.get("rows_merged") or 0) > 1:
category, rank = "ambiguous", (4, 0, date.min)
elif reported is None or reported > cutoff:
category, rank = "pending", (0, 0, date.min)
elif reported < request:
category, rank = "inconsistent", (1, 0, reported)
elif row.get("histology") is None:
category, rank = "no_grade", (2, 0, reported)
elif row["histology"] not in severity:
category, rank = "unclassified", (2, 0, reported)
else:
grade = row["histology"]
category = "high_grade" if grade in cacu.CIN2_PLUS else "below_high_grade"
rank = (3, severity[grade], reported)
key = row["request_id"]
if key not in chosen or rank > chosen[key][0]:
chosen[key] = (rank, category)
categories = {}
for _, category in chosen.values():
cell = categories.setdefault(category, {"initial-population": 0})
cell["initial-population"] += 1
count = len(chosen)
return Result({"initial-population": count, "measure-observation": count},
strata={"category": categories})
@dataclass(frozen=True)
class DiagnosisDurations:
kind: str = "continuous-variable"
strata: tuple = (("diagnosis_code", None),)
def evaluate(self, rows, period, cutoff):
rule = Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=lambda r: r["history"] == 0)
overall = rule.evaluate(rows, period, cutoff)
grouped = {}
for row in {r["sample_id"]: r for r in rows}.values():
if (row["sample_date"] not in period or row["history"] != 0
or row.get("days_sample_diagnosis") is None
or as_day(row.get("diagnosis_date")) is None
or as_day(row["diagnosis_date"]) > cutoff):
continue
code = row.get("diagnosis_code") or "sin_codigo"
grouped.setdefault(code, []).append(row)
cells, scores = {}, {}
for code, group in grouped.items():
values = sorted(float(r["days_sample_diagnosis"]) for r in group)
median = statistics.median(values)
q1, q3 = (values[0], values[0]) if len(values) == 1 else (statistics.quantiles(values, n=4, method="inclusive")[0], statistics.quantiles(values, n=4, method="inclusive")[2])
descriptions = {r.get("diagnosis_description") for r in group if r.get("diagnosis_description")}
label = code + (" | " + next(iter(descriptions)) if len(descriptions) == 1 else "")
cells[label] = {"measure-observation": len(values)}
scores[label] = {"value": median, "unit": "d", "extension": [
{"url": "https://isssteleon.org/fhir/StructureDefinition/q1", "valueDecimal": q1},
{"url": "https://isssteleon.org/fhir/StructureDefinition/q3", "valueDecimal": q3}]}
return Result(overall.populations, overall.score, overall.score_extensions, overall.unit,
{"diagnosis_code": cells}, {"diagnosis_code": scores})
def referring_cytology(cytologies: list[dict], day: date) -> dict | None:
"""Her latest valid cytology sampled and reported before `day` (a result of that same
day doesn't count: dates can't say which came first), its report at most
REFERRAL_CYTOLOGY_DAYS old."""
found = [
c for c in cytologies
if valid(c) and c.get("result") is not None
and as_day(c["date"]) < day and as_day(c["result_date"]) < day
and (day - as_day(c["result_date"])).days <= cacu.REFERRAL_CYTOLOGY_DAYS
] # fmt: skip
return max(found, key=lambda c: (as_day(c["date"]), as_day(c["result_date"]),
c["sample_id"]), default=None) # fmt: skip
def screening_round(cytology: dict | None) -> str:
"""`subsequent`: screened before (as her form says) or already past colposcopy or
treatment at the sample; `initial`: the first screening of her life, before colposcopy."""
if cytology is None:
return NO_DATA
# a referral fact is dated `date`; a gold sample `sample_date`
status = follow_up_status(cytology, as_day(cytology.get("date") or cytology["sample_date"]))
history = cytology.get("screening_history")
if history in cacu.PREVIOUS_SCREENING or status in ("post_colposcopy", "post_treatment"):
return "subsequent"
return "initial" if history == "first_time" else NO_DATA
def hpv_result(row: dict) -> str | None:
"""Her high-risk HPV result on a sample; none when it has none."""
return None if row.get("hpv") is None else "positive" if row["hpv"] else "negative"
def hpv_groups(cytology: dict | None) -> list[str]:
"""The referral PPVs' HPV groups of a referring cytology: its result and, apart, each
genotype it was positive for (they overlap with `positive`, and may with each other)."""
row = cytology or {}
found = [name for name in (hpv_result(row),) if name]
found += [name for name in ("hpv_16", "hpv_18") if row.get(name)]
return found or [NO_DATA]
@dataclass(frozen=True)
class ReferralPPV:
"""Of the patients with a procedure in the period, those whose histology confirms the
first level of PPV_HISTOLOGY. Rows are facts (`gold.cacu_referral_facts`: `fact` is
cytology, colposcopy or biopsy, each dated `date`), so the referring cytology is chosen
among those known at the evaluation's `as_of`.
A patient counts once, with her first procedure of the period that qualifies: she wasn't
a case already (at her referring sample, or at the procedure without one) and, for the
biopsy PPV, a biopsy requested that day has a histology. Its histology is that of the
biopsies requested that day and reported by the cut-off; with none, not confirmed."""
procedure: str # "colposcopy" or "biopsy"
kind: str = "proportion"
strata: tuple[tuple[str, None], ...] = (
("referral_cytology", None), ("referral_hpv", None), ("histology_level", None),
("screening_round", None),
) # fmt: skip
def _units(self, rows: list[dict], period: Period, cutoff: date):
"""Per patient counted: the histologies of her procedure and its referring cytology."""
mine: dict[str, dict[str, list[dict]]] = {}
for row in rows:
mine.setdefault(row["person_id"], {}).setdefault(row["fact"], []).append(row)
for facts in mine.values():
procedures: dict[date, list[dict]] = {}
for row in facts.get(self.procedure, []):
day = as_day(row["date"])
if day in period and day <= cutoff:
procedures.setdefault(day, []).append(row)
for day in sorted(procedures):
found = {
b["histology"] for b in facts.get("biopsy", [])
if as_day(b["date"]) == day and b.get("histology") is not None
and b.get("report_date") is not None
and day <= as_day(b["report_date"]) <= cutoff
} # fmt: skip
if self.procedure == "biopsy" and not found:
continue
cytology = referring_cytology(facts.get("cytology", []), day)
at = day if cytology is None else as_day(cytology["date"])
if follow_up_status(cytology or procedures[day][0], at) == "case":
continue
yield found, cytology
break
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
units = list(self._units(rows, period, cutoff))
def cell(members: list, level: list[str]) -> dict[str, int]:
n = len(members)
return {"initial-population": n, "denominator": n,
"numerator": sum(bool(found & set(level)) for found, _ in members)} # fmt: skip
score_level = next(iter(cacu.PPV_HISTOLOGY.values()))
total = cell(units, score_level)
strata: dict[str, dict] = {name: {} for name, _ in self.strata}
if not units:
return Result(total, strata=strata)
groups: dict[str, list] = {}
for unit in units:
cytology = unit[1]
names = (
[NO_DATA]
if cytology is None
else [g for g, codes in cacu.PPV_CYTOLOGY.items() if cytology["result"] in codes]
)
for name in names:
groups.setdefault(name, []).append(unit)
strata["referral_cytology"] = {g: cell(u, score_level) for g, u in groups.items()}
by_hpv: dict[str, list] = {}
for unit in units:
for name in hpv_groups(unit[1]):
by_hpv.setdefault(name, []).append(unit)
strata["referral_hpv"] = {g: cell(u, score_level) for g, u in by_hpv.items()}
strata["histology_level"] = {
name: cell(units, level) for name, level in cacu.PPV_HISTOLOGY.items()
}
rounds: dict[str, list] = {}
for unit in units:
rounds.setdefault(screening_round(unit[1]), []).append(unit)
strata["screening_round"] = {g: cell(u, score_level) for g, u in rounds.items()}
k, n = total["numerator"], total["denominator"]
low, high = wilson(k, n)
return Result(total, k / n, {"ic-bajo": low, "ic-alto": high}, strata=strata)
H = cacu.HORIZONS
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no cervical cancer note before
AGE = ("age_group", lambda row, p: age_group(row.get("birth_date"), p.start, cacu.AGE_GROUPS))
STATUS = ("follow_up_status", lambda row, p: follow_up_status(row, p.start))
RESULT = ("result", lambda row, p: row["result"])
SCREENING = ("screening_round", lambda row, p: screening_round(row))
def results_of(wanted: str):
"""The results of the patients in one screening round (the others are in no group)."""
return (f"result_{wanted}",
lambda row, p: result(row) if screening_round(row) == wanted else None) # fmt: skip
def genotype(name: str):
"""A genotype's result on the chosen sample (in no group when not reported)."""
return (name, lambda row, p: None if row.get(name) is None
else "positive" if row[name] else "negative") # fmt: skip
def hpv_of(wanted: str):
"""The HPV results of the patients in one screening round."""
return (f"hpv_{wanted}",
lambda row, p: hpv_result(row) if screening_round(row) == wanted else None) # fmt: skip
MEASURES = {m.id: m for m in [
Measure("IND1", "Pacientes con citología anormal", "samples",
Proportion(lambda r: r["result"] in cacu.ABNORMAL), "decrease", group="principal"),
Measure("CACU_EU13", "Tasa de detección histopatológica", "sample_biopsies",
Proportion(lambda r: r.get("histology") in cacu.DETECTION
and r.get("biopsy_report_date") is not None,
strata=(AGE, STATUS)), group="principal"),
Measure("CACU_EU7", "Pacientes evaluadas por resultado de citología", "samples",
Composition(latest, result, strata=(
AGE, STATUS, SCREENING, results_of("initial"), results_of("subsequent")))),
Measure("CACU_VPH_GENOTIPO", "Resultados de VPH por genotipo", "hpv_reports",
Composition(lambda r: (as_day(r["report_date"]),), lambda r: r["category"],
unit="sample_id", date="sample_date"),
description="Reportes VPH con fecha de reporte y algún resultado VPH, por paciente y "
"fecha de toma; periodo por toma. Los nulos no son negativos; el contrato "
"booleano actual no representa resultados indeterminados."),
Measure("CACU_BIOPSIA_RESULTADOS", "Resultados de biopsia cervical", "biopsy_reports",
Composition(lambda r: (as_day(r["report_date"]),), lambda r: r["category"],
unit="biopsy_id", date="report_date"),
description="Reportes de biopsia por paciente y fecha de solicitud, incluidos los no "
"vinculados a una toma; periodo por fecha de reporte. El estrato no_data "
"identifica reportes sin grado; la distribución clasificable lo excluye."),
Measure("CACU_BIOPSIA_SOLICITUD_CONFIRMACION", "Resultados por solicitudes de biopsia registradas",
"biopsy_requests", BiopsyRequests(), known="order_known_at", supports_as_of=False,
description="Solicitudes de biopsia registradas por persona y fecha de solicitud, "
"según fecha de solicitud; resultados hasta el corte. La clave puede "
"agrupar órdenes y no se conocen cancelaciones ni cobertura de referencias. "
"No admite corte histórico de conocimiento as-of."),
# Her latest sample with an HPV result in the period, whatever its cytology says.
Measure("CACU_VPH", "Pacientes evaluadas por resultado de VPH", "samples",
Composition(lambda r: (as_day(r["sample_date"]), r["sample_id"]), hpv_result,
where=lambda r: r.get("hpv") is not None,
strata=(AGE, STATUS, genotype("hpv_16"), genotype("hpv_18"), SCREENING,
hpv_of("initial"), hpv_of("subsequent"))),
facts={"report_known_at": ("hpv", "hpv_16", "hpv_18")}),
Measure("CACU_CONFIRMACION_CITOLOGIA", "Confirmación histopatológica", "sample_biopsies",
Composition(latest_most_severe_biopsy, histology,
admit=lambda r: valid(r) and r["result"] in cacu.HIGH_GRADE,
strata=(RESULT,))),
# Rows become known with `known_at`; a report's values only with `report_known_at`.
*(Measure(f"CACU_VPP_{name}", f"VPP de la referencia a {title}", "referral_facts",
ReferralPPV(procedure),
facts={"report_known_at": ("result", "result_date", "adequacy",
"histology", "report_date",
"hpv", "hpv_16", "hpv_18")})
for name, title, procedure in (("COLPOSCOPIA", "colposcopía", "colposcopy"),
("BIOPSIA", "biopsia", "biopsy"))),
Measure("CACU_EU_TIEMPO_REPORTE", "Tiempo de toma a resultado de citología", "samples",
Duration("days_sample_result", "result_date", "sample_date", H["sample_to_report"],
ended="report_date"), "decrease"),
Measure("CACU_DIAS_TOMA_DIAGNOSTICO", "Tiempo de tamizaje a diagnóstico", "samples",
Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=NO_HISTORY), "decrease"),
Measure("CACU_TIEMPO_DIAGNOSTICO_CIE10", "Tiempo a diagnóstico por CIE-10 (exploratorio)",
"diagnosis_codes", DiagnosisDurations(),
description="Agrupa la fecha diagnóstica ya seleccionada por asociación temporal; no confirma vínculo clínico."),
Measure("CACU_DIAS_TOMA_TRATAMIENTO", "Tiempo de tamizaje a tratamiento", "samples",
Duration("days_sample_treatment", "treatment_date", "sample_date",
H["sample_to_treatment"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_DIAGNOSTICO_TRATAMIENTO", "Tiempo de diagnóstico a tratamiento", "samples",
Duration("days_diagnosis_treatment", "diagnosis_treatment_date", "diagnosis_date",
H["diagnosis_to_treatment"],
units=lambda r: r["history"] == 0 and r["diagnosis_date"] is not None),
"decrease"),
Measure("CACU_DIAS_TOMA_COLPOSCOPIA", "Tiempo de toma de muestra a colposcopía", "samples",
Duration("days_sample_colposcopy", "colposcopy_date", "sample_date",
H["sample_to_colposcopy"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_TOMA_BIOPSIA", "Tiempo de toma de muestra a resultado de biopsia", "samples",
Duration("days_sample_biopsy", "biopsy_date", "sample_date",
H["sample_to_biopsy"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_RESULTADO_COLPOSCOPIA", "Tiempo de resultado a colposcopía", "samples",
Duration("days_result_colposcopy", "result_colposcopy_date", "result_date",
H["result_to_colposcopy"],
units=lambda r: r["history"] == 0 and r["result_date"] is not None),
"decrease"),
Measure("CACU_DIAS_COLPOSCOPIA_BIOPSIA", "Tiempo de colposcopía a biopsia", "samples",
Duration("days_colposcopy_biopsy", "biopsy_date", "result_colposcopy_date",
H["colposcopy_to_biopsy"],
units=lambda r: r["history"] == 0
and r["result_colposcopy_date"] is not None), "decrease"),
Measure("CACU_DIAS_BIOPSIA_DIAGNOSTICO", "Tiempo de biopsia a diagnóstico", "samples",
Duration("days_biopsy_diagnosis", "biopsy_diagnosis_date", "biopsy_date",
H["biopsy_to_diagnosis"],
units=lambda r: r["history"] == 0 and r["biopsy_date"] is not None),
"decrease"),
Measure("CACU_RIESGO_BANDA", "Banda de riesgo de CIN2+ en vigilancia", "risk",
RiskBand(tuple(cacu.RISK_BANDS)),
periods=("semester",), params={"model": cacu.RISK_BAND_MODEL}),
]} # fmt: skip
-17
View File
@@ -1,17 +0,0 @@
from core.cacu.paciente.model import Paciente
from core.cacu.ordenes_estudio.model import OrdenesEstudio
from core.cacu.citologia_cervical.model import CitologiaCervical
from core.cacu.biopsia_cervical.model import BiopsiaCervical
from core.cacu.nota_medica.model import NotaMedica
from core.cacu.biometria_hematica.model import BiometriaHematica
from core.cacu.episodio_clinico.model import EpisodioClinico
__all__ = [
"Paciente",
"OrdenesEstudio",
"CitologiaCervical",
"BiopsiaCervical",
"NotaMedica",
"BiometriaHematica",
"EpisodioClinico",
]
-35
View File
@@ -1,35 +0,0 @@
## nota_medica
| Columna | Fuente | Descripción |
|---|---|---|
| `nm_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | FK lógica hacia `paciente.pac_id` — resuelto en carga, nulo si no hay match |
| `pac_id_hospital` | Hospital, DG1 | Identificador hospitalario del paciente |
| `nm_id_hospital` | Hospital, — | Identificador original de la nota en el HIS |
| `nm_nota_previa_id` | Hospital, — | FK autorreferencial para cadena de seguimiento |
| `nm_tipo_nota` | Hospital, NM1 | Tipo de visita |
| `nm_especialidad` | Hospital, NM1 | Especialidad médica que emite la nota |
| `nm_fecha` | Hospital, NM3 | Fecha de la consulta o procedimiento |
| `nm_medico_tratante` | Hospital, NM4 | Médico que emite la nota |
| `nm_motivo_consulta` | Hospital, NM10 | Motivo de consulta referido o registrado |
| `nm_interrogatorio` | Hospital, NM11 | Antecedentes relevantes e historia clínica |
| `nm_diagnostico_texto` | Hospital, NM2 | Diagnóstico clínico en texto libre |
| `nm_cie_codigo` | Hospital, NM17 | Código CIE-10 del diagnóstico principal |
| `nm_cie_descripcion` | Hospital, NM17 | Descripción del código CIE-10 |
| `nm_tratamiento_texto` | Hospital, NM12 | Descripción del tratamiento indicado |
| `nm_receta` | Hospital, NM14 | Medicamentos prescritos |
| `nm_plan_estudios` | Hospital, NM15 | Estudios planeados con orden, fecha y resultado esperado |
| `nm_pronostico` | Hospital, NM13 | Pronóstico registrado por el médico |
| `nm_observaciones` | Hospital, NM16 | Observaciones adicionales del médico |
| `nm_masa_corporal` | Hospital, NM5 | Peso corporal en la visita (kg) |
| `nm_talla` | Hospital, NM5 | Talla registrada en la visita (m) |
| `nm_imc_visita` | Derivado, pipeline | IMC calculado a partir de peso y talla |
| `nm_frecuencia_cardiaca` | Hospital, NM6 | Frecuencia cardíaca (lpm) |
| `nm_frecuencia_respiratoria` | Hospital, NM7 | Frecuencia respiratoria (rpm) |
| `nm_presion_arterial_sistolica` | Hospital, NM8 | Presión arterial sistólica (mmHg) |
| `nm_presion_arterial_diastolica` | Hospital, NM8 | Presión arterial diastólica (mmHg) |
| `nm_temperatura` | Hospital, NM9 | Temperatura corporal (°C) |
---
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
-1
View File
@@ -1 +0,0 @@
from core.cacu.nota_medica.model import NotaMedica
-40
View File
@@ -1,40 +0,0 @@
from enum import Enum
class TipoNota(str, Enum):
CONSULTA = "CONSULTA"
EGRESO = "EGRESO"
INGRESO = "INGRESO"
URG_EGRESO = "URG_EGRESO"
TIPO_NOTA_ALIAS: dict[str, str] = {
"URG. EGRESO": "URG_EGRESO",
}
class Especialidad(str, Enum):
MEDICINA_FAMILIAR = "MEDICINA_FAMILIAR"
CIRUGIA_ONCOLOGICA = "CIRUGIA_ONCOLOGICA"
CLINICA_MUJER_COLPOSCOPIA = "CLINICA_MUJER_COLPOSCOPIA"
ESPECIALIDAD_ALIAS: dict[str, str] = {
"MEDICINA FAMILIAR": "MEDICINA_FAMILIAR",
"CIRUGIA ONCOLOGICA": "CIRUGIA_ONCOLOGICA",
"CLINICA DE MUJER Y COLPOSCOPIA": "CLINICA_MUJER_COLPOSCOPIA",
}
class Parentesco(str, Enum):
AFILIADO = "Afiliado"
# Other values pending confirmation with the HIS administrator.
PARENTESCO_ALIAS: dict[str, str] = {
"AFILIADO": "Afiliado",
}
class Dependencia(str, Enum):
GOBIERNO = "GOBIERNO"
CALLES_Y_CAMINOS = "CALLES Y CAMINOS"
# Tentative values, pending confirmation with the HIS administrator.
DEPENDENCIA_ALIAS: dict[str, str] = {
"CALLES Y CAMINOS": "CALLES Y CAMINOS",
}
-124
View File
@@ -1,124 +0,0 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import HOSPITAL_ID_LENGTH
class NotaMedica(CaCuModel, table=True):
"""
Notas medicas del paciente
"""
nm_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="rellenado por el loader via lookup en paciente.pac_id_hospital; puede quedar nulo",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
description="DG1: identificador hospitalario obligatorio para vincular estudios con pacientes",
)
# Bounded and indexed: part of the natural key (with pac_id_hospital)
# the import layer upserts/merges notes on.
nm_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
)
nm_nota_previa_id: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_tipo_nota: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_especialidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
nm_medico_tratante: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_motivo_consulta: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_interrogatorio: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_diagnostico_texto: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_cie_codigo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_cie_descripcion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_tratamiento_texto: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_receta: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_plan_estudios: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_pronostico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_masa_corporal: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
nm_talla: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
nm_imc_visita: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
nm_frecuencia_cardiaca: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_frecuencia_respiratoria: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_presion_arterial_sistolica: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_presion_arterial_diastolica: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_temperatura: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
-23
View File
@@ -1,23 +0,0 @@
## ordenes_estudio
Al parecer no aparece en la plataforma el pdf de la orden del estudio emitido.
Tabla de órdenes, 1 fila por solicitud médica. Fuente: TC2 parcial, TVPH2, HPC2, NM3, NM4
| Columna | Fuente | Descripción |
| ------------------------ | ---------------------------- | ----------------------------------------------------------------------------------------------------- |
| `ord_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | FK hacia paciente.pac_id, resuelto en carga por lookup en paciente |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, desnormalizado para joins sin pasar por paciente |
| `ord_numero_hospital` | Hospital, TC1, TVPH1, HPC1 | Número de orden de 5 dígitos asignado por el HIS, índice único, join lógico hacia tablas de resultado |
| `ord_tipo_estudio` | Hospital, TC1, TVPH1, HPC1 | Tipo de estudio solicitado, texto libre, enum pendiente de confirmar con administrador |
| `ord_fecha` | Hospital, TVPH2, HPC2 | Fecha en que el médico emitió la orden |
| `ord_fecha_solicitud` | Hospital, TVPH2, HPC2 | Fecha sugerida por el médico para realizar el estudio |
| `ord_fecha_resultado` | Hospital, HPC3, TVPH4 | Fecha en que el resultado estuvo disponible, nulo hasta que llegue |
| `ord_estatus` | Hospital, TVPH4, HPC3 | Estatus de la orden, texto libre, enum pendiente de confirmar con administrador |
| `ord_diagnostico` | Hospital, ord | Diagnóstico presuntivo del médico (pantalla Asignar diagnóstico) |
| `ord_observaciones` | Hospital, — | Observaciones generales de la orden |
| `ord_especialidad` | Hospital, NM1 | Especialidad del médico solicitante |
| `ord_medico_solicitante` | Hospital, NM4 | Nombre o clave del médico tratante que emite la orden |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
@@ -1 +0,0 @@
from core.cacu.ordenes_estudio.model import OrdenesEstudio
-11
View File
@@ -1,11 +0,0 @@
from enum import Enum
class TipoEstudio(str, Enum):
BIOPSIA_CHICA = "BIOPSIA_CHICA"
SOLICITUD_PAPANICOLAO_BASE_LIQUIDA = "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA"
TIPO_ESTUDIO_ALIAS: dict[str, str] = {
"BIOPSIA CHICA": "BIOPSIA_CHICA",
"SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
"Solicitud de Papanicolao en Base Liquida": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
}
-77
View File
@@ -1,77 +0,0 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import HOSPITAL_ID_LENGTH
class OrdenesEstudio(CaCuModel, table=True):
"""
Modelo ORM para órdenes de estudio.
Condensa cabecera y detalle en una sola tabla.
Una orden corresponde a un único tipo de estudio.
El resultado (citología, biopsia) referencia esta tabla via ord_numero_hospital (join logico).
"""
ord_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("paciente.pac_id"), index=True),
)
# Denormalized so studies join without going through paciente
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
ord_numero_hospital: int = Field(
sa_column=sa.Column(sa.Integer, unique=True, index=True, nullable=False),
description="TC1/TVPH1/HPC1: numero de orden de 5 digitos asignado por el HIS",
)
ord_tipo_estudio: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Citología Base líquida, Biopsia Cervical"
)
ord_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha de emisión de la orden por el médico",
)
ord_fecha_solicitud: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha sugerida por el médico para realizar el estudio",
)
ord_fecha_resultado: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha en que el resultado estuvo disponible, nulo hasta que llegue",
)
ord_estatus: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="REALIZADO E INTERPRETADO",
)
ord_diagnostico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Diagnóstico, pantalla: Asignar diagnostico",
)
ord_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
ord_especialidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="",
)
ord_medico_solicitante: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Nombre o clave del médico NM4",
)
-14
View File
@@ -1,14 +0,0 @@
## pacientes
| Columna | Fuente | Descripción |
| ---------------------- | ----------------------- | ---------------------------------------------------------------------------------------------- |
| `pac_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, índice único, permite lookup desde tablas de resultado |
| `pac_fecha_nacimiento` | Hospital, DG2 | Fecha de nacimiento |
| `pac_sexo` | Hospital, DG3 | Sexo biológico |
| `pac_codigo_postal` | Hospital, DG4 | Código postal de residencia |
| `pac_dependencia` | Hospital, DG5 | Unidad de cobertura o dependencia administrativa |
| `pac_parentesco` | Hospital, — | Parentesco del titular respecto al trabajador |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
-1
View File
@@ -1 +0,0 @@
from core.cacu.paciente.model import Paciente
-18
View File
@@ -1,18 +0,0 @@
from enum import Enum
class SexoBiologico(str, Enum):
"""
Sexo biológico del paciente.
Hasta ahora asumieremos que se guarda como texto en el mercado de datos:
("Femenino", "Masculino").
Solamente se usará en la capa de validación.
"""
F = "Femenino"
M = "Masculino"
SEXO_BIOLOGICO_ALIAS: dict[str, str] = {
"F": "Femenino",
"M": "Masculino",
"FEMENINO": "Femenino",
"MASCULINO": "Masculino",
}
-49
View File
@@ -1,49 +0,0 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import HOSPITAL_ID_LENGTH
class Paciente(CaCuModel, table=True):
"""
Modelo ORM, solamente almacena.
Se reservan las validaciones de dominio para otra capa.
"""
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# The patient's original HIS id (DG1), uniquely indexed for lookups
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), unique=True, index=True, nullable=False),
)
pac_sexo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
# IND-01: required; age at each event of interest (clinical episode) is
# computed from it.
pac_fecha_nacimiento: date = Field(
sa_column=sa.Column(sa.Date, nullable=False),
)
pac_codigo_postal: Optional[str] = Field(
default=None,
sa_column=sa.Column(
sa.CHAR(5),
),
description="Código postal de 5 dígitos",
)
pac_dependencia: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Dependencia",
)
pac_parentesco: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Parentesco",
)
+27
View File
@@ -0,0 +1,27 @@
"""Stage facts for a sample, using gold's dates and explicit biopsy links."""
def stage_facts(sample, biopsies, events, cutoff):
def day(value):
return str(value)[:10] if value is not None else None
start, end = day(sample['sample_date']), str(cutoff)[:10]
out = {}
for kind, column in [('colposcopy', 'colposcopy_date'), ('diagnosis', 'diagnosis_date')]:
selected = day(sample.get(column))
if selected and start < selected <= end:
matches = {(e['source_table'], e['source_id']) for e in events
if e['type'] == kind and day(e['date']) == selected}
out[kind] = ('inferred', selected) if len(matches) == 1 else ('ambiguous', None)
linked = [b for b in biopsies if day(b.get('cytology_sample_date')) == start
and day(b.get('request_date')) and start <= day(b['request_date']) <= end]
if len(linked) > 1 or any((b.get('rows_merged') or 0) > 1 for b in linked):
out['biopsy'] = ('ambiguous', None)
elif linked:
b = linked[0]
reported = day(b.get('report_date'))
if reported and reported < day(b['request_date']):
out['biopsy'] = ('ambiguous', None)
elif reported and reported <= end:
out['biopsy'] = ('structured', reported)
else:
out['biopsy'] = ('pending', None)
return out
+48
View File
@@ -0,0 +1,48 @@
"""CaMa clinical parameters: the one place they are set. dbt reads them as vars, the measures
and models import them. Codes are the platform's (core.catalog)."""
# BI-RADS, least to most severe: an incomplete study (0) asks for more and weighs more than a
# benign one; a 4 without subcategory weighs less than 4A.
BIRADS_SEVERITY = ["1", "2", "3", "0", "4", "4A", "4B", "4C", "5", "6"]
BIRADS_4_TO_6 = ["4", "4A", "4B", "4C", "5", "6"]
SUSPICIOUS = ["4", "4A", "4B", "4C", "5"] # should be confirmed by biopsy (not 6: already is)
# Biopsy grades, least to most severe.
BIOPSY_SEVERITY = ["benign", "in_situ", "invasive"]
CANCER = ["in_situ", "invasive"] # detected (detection rate)
INVASIVE = ["invasive"]
# Survival: indexed at the first biopsy reported with one of these, within the recruitment
# window (start inclusive, end exclusive).
SURVIVAL_GRADES = ["invasive"]
RECRUITMENT = ("2018-01-01", "2027-01-01")
# Inferred from clinical notes (ICD-10 without the dot; specialties are the platform's codes):
# - diagnosis: a note that resolves a mammogram, with a diagnosis ICD-10 by a diagnosing
# specialty;
# - history: a breast cancer note, whoever wrote it.
DIAGNOSIS_SPECIALTIES = ["oncology_surgery"]
HISTORY_ICD10 = [
"D05", "D050", "D051", "D057", "D059",
"C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509",
] # fmt: skip
DIAGNOSIS_ICD10 = [
"Z123", "N60", "N600", "N601", "N602", "N603", "N604", "N608", "N609", "N61", "N62", "N63",
"N64", "N640", "N641", "N642", "N643", "N644", "N645", "N648", "N649", "D24", "R92",
*HISTORY_ICD10,
] # fmt: skip
# Measures (core.measures): the horizons, in days; an interval that hasn't ended after its
# horizon counts as not ended. A diagnosis this soon after the mammogram resolves it.
HORIZONS = {"sample_to_report": 60, "to_diagnosis": 180}
AGE_GROUPS = [(40, 49), (50, 59), (60, 69)] # plus "<40" and "70+"
# The follow-up list: patients whose latest mammogram, taken within the window before the
# cut-off, is BI-RADS 4 to 6.
FOLLOW_UP_WINDOWS = [1, 3, 6, 12] # months
FOLLOW_UP_WINDOW = 3
def dbt_vars() -> dict:
"""What dbt reads (`var('cama')`)."""
return {k.lower(): v for k, v in globals().items() if k.isupper()}
-12
View File
@@ -1,12 +0,0 @@
import sqlalchemy.orm as orm
from sqlmodel import SQLModel
registry = orm.registry()
class CaMaModel(SQLModel, registry=registry):
"""Base class for every CaMa table.
Uses its own SQLAlchemy registry so table names such as `notamedica`
don't collide with CaCu's tables of the same name.
"""
@@ -1,34 +0,0 @@
## biometria_hematica
Tabla de resultados de laboratorio, 1 fila por reporte de biometría hemática.
Fuente: extracción OCR y NLP sobre PDF vinculado en Estudios Laboratorio (BH1).
Join hacia ordenes_estudio por ord_numero_hospital (lógico, sin FK constraint). Join hacia paciente por pac_id_hospital (resuelto en carga).
| Columna | Fuente | Descripción |
| ------------------------------ | -------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `bh_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | Join lógico hacia paciente.pac_id, resuelto en carga, nulo si no hay match al momento de ingesta |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, obligatorio para el join lógico hacia paciente |
| `ord_numero_hospital` | Hospital, BH4 | Número de orden HIS, join lógico hacia ordenes_estudio.ord_numero_hospital |
| `bh_fecha` | Hospital, BH2 | Fecha de solicitud del estudio; pendiente de distinción con BH3 (fecha resultado) según ETL |
| `eritrocitos_mill_ul` | Derivado, OCR sobre PDF BH1 | Conteo de eritrocitos (millones/µL) |
| `hemoglobina_g_dl` | Derivado, OCR sobre PDF BH1 | Concentración de hemoglobina (g/dL) |
| `hematocrito_pct` | Derivado, OCR sobre PDF BH1 | Hematocrito como porcentaje del volumen sanguíneo |
| `vcm_fl` | Derivado, OCR sobre PDF BH1 | Volumen corpuscular medio (fL) |
| `hcm_pg` | Derivado, OCR sobre PDF BH1 | Hemoglobina corpuscular media (pg) |
| `chcm_g_dl` | Derivado, OCR sobre PDF BH1 | Concentración de hemoglobina corpuscular media (g/dL) |
| `rdw_pct` | Derivado, OCR sobre PDF BH1 | Amplitud de distribución eritrocitaria (%) |
| `leucocitos_mil_ul` | Derivado, OCR sobre PDF BH1 | Conteo total de leucocitos (miles/µL) |
| `neutrofilos_pct` | Derivado, OCR sobre PDF BH1 | Neutrófilos totales como porcentaje del diferencial leucocitario |
| `linfocitos_pct` | Derivado, OCR sobre PDF BH1 | Linfocitos como porcentaje del diferencial leucocitario |
| `monocitos_pct` | Derivado, OCR sobre PDF BH1 | Monocitos como porcentaje del diferencial leucocitario |
| `eosinofilos_pct` | Derivado, OCR sobre PDF BH1 | Eosinófilos como porcentaje del diferencial leucocitario |
| `basofilos_pct` | Derivado, OCR sobre PDF BH1 | Basófilos como porcentaje del diferencial leucocitario |
| `neutrofilos_segmentados_pct` | Derivado, OCR sobre PDF BH1 | Neutrófilos segmentados, desglose del diferencial neutrofílico (%) |
| `neutrofilos_banda_pct` | Derivado, OCR sobre PDF BH1 | Neutrófilos en banda, desglose del diferencial neutrofílico (%) |
| `metamielocitos_pct` | Derivado, OCR sobre PDF BH1 | Metamielocitos, desglose del diferencial neutrofílico (%) |
| `mielocitos_pct` | Derivado, OCR sobre PDF BH1 | Mielocitos, desglose del diferencial neutrofílico (%) |
| `plaquetas_mil_ul` | Derivado, OCR sobre PDF BH1 | Conteo de plaquetas (miles/µL) |
| `vpm_fl` | Derivado, OCR sobre PDF BH1 | Volumen plaquetario medio (fL) |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
@@ -1 +0,0 @@
from core.cama.biometria_hematica.model import BiometriaHematica
@@ -1,60 +0,0 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import HOSPITAL_ID_LENGTH
class BiometriaHematica(CaMaModel, table=True):
"""
Modelo ORM para biometría hemática.
No hay validación en esta capa, se almacena laxamente.
"""
bh_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# Logical join, resolved on import by looking up paciente.pac_id_hospital
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
# Hospital patient id: links studies to patients
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# Logical join to ordenes_estudio.ord_numero_hospital, no FK constraint
ord_numero_hospital: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
bh_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
eritrocitos_mill_ul: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
hemoglobina_g_dl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
hematocrito_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
vcm_fl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
hcm_pg: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
chcm_g_dl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
rdw_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
leucocitos_mil_ul: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
linfocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
monocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
basofilos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
eosinofilos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
neutrofilos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
mielocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
metamielocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
neutrofilos_banda_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
neutrofilos_segmentados_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
plaquetas_mil_ul: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
vpm_fl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
-18
View File
@@ -1,18 +0,0 @@
## biopsia_mama
Una fila por reporte de biopsia mamaria · fuente: sistema estructurado + OCR/NLP sobre PDF histopatológico
| Columna | Fuente | Descripción |
| --------------------- | ------------------------------- | --------------------------------------------------------------------- |
| `bx_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital| FK hacia paciente, resuelto en el loader, nulo si no hay match |
| `pac_id_hospital` | Hospital, DG1 | Identificador hospitalario del paciente, desnormalizado |
| `ord_id` | Derivado, lookup en ordenes_estudio | FK formal a `ordenesestudio.ord_id`; el loader lo resuelve comparando `ord_numero_hospital` de este registro con `ordenes_estudio.ord_numero_hospital` |
| `ord_numero_hospital` | Hospital, BX1 | Número de orden asignado por el HIS; clave de join para resolver `ord_id` |
| `mast_id` | Derivado, lookup mast_id | FK hacia mastografia, nulo si la biopsia no tiene mastografía previa |
| `bx_fecha_solicitud` | Hospital, BX2 | Fecha de solicitud de la biopsia |
| `bx_fecha_reporte` | Hospital, BX3 | Fecha de emisión del reporte histopatológico |
| `bx_grado_histologico`| Derivado, OCR sobre PDF BX5 | Grado histológico del resultado |
| `bx_pdf_blob` | Hospital, BX5 | Contenido binario del PDF del reporte histopatológico |
| `bx_ocr_confianza` | Derivado, pipeline OCR | Score de confianza del OCR sobre este documento |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
-1
View File
@@ -1 +0,0 @@
from core.cama.biopsia_mama.model import BiopsiaMama
-19
View File
@@ -1,19 +0,0 @@
from enum import Enum
class GradoHistologicoMama(str, Enum):
BENIGNO = "BENIGNO"
CARCINOMA_IN_SITU = "CARCINOMA_IN_SITU"
CARCINOMA_INVASOR = "CARCINOMA_INVASOR"
DESCONOCIDO = "DESCONOCIDO"
class TipoEstudio(str, Enum):
BIOPSIA_CHICA = "BIOPSIA_CHICA"
SOLICITUD_PAPANICOLAO_BASE_LIQUIDA = "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA"
TIPO_ESTUDIO_ALIAS: dict[str, str] = {
"BIOPSIA CHICA": "BIOPSIA_CHICA",
"SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
"Solicitud de Papanicolao en Base Liquida": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
}
-81
View File
@@ -1,81 +0,0 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
class BiopsiaMama(CaMaModel, table=True):
"""
Modelo ORM para biopsia de mama. Fechas en sa.Date (sistema estructurado).
"""
bx_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
description="identificador hospitalario, obligatorio para vincular estudios con pacientes",
)
ord_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("ordenesestudio.ord_id"), index=True),
description="FK resuelto por el loader via lookup en ordenes_estudio.ord_numero_hospital",
)
ord_numero_hospital: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
mast_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("mastografia.mast_id"), index=True),
)
bx_fecha_solicitud: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
bx_fecha_reporte: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
bx_grado_histologico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_pdf_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(FileBlob),
)
bx_ocr_confianza: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
# VARM-04a
bx_ocr_estatus: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="valor de core.ocr.OcrEstatus guardado como texto",
)
bx_ocr_requiere_revision: Optional[bool] = Field(
default=None,
sa_column=sa.Column(sa.Boolean),
)
bx_ocr_metodo_principal: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_ocr_metodo_alternativo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
-6
View File
@@ -1,6 +0,0 @@
from core.cama.paciente.enums import SexoBiologico, SEXO_BIOLOGICO_ALIAS
from core.cama.nota_medica.enums import TipoNota, TIPO_NOTA_ALIAS, Especialidad, ESPECIALIDAD_ALIAS, Parentesco, PARENTESCO_ALIAS, Dependencia, DEPENDENCIA_ALIAS
from core.cama.ordenes_estudio.enums import TipoEstudio, TIPO_ESTUDIO_ALIAS
from core.cama.biopsia_mama.enums import GradoHistologicoMama
from core.cama.mastografia.enums import BIRADS, BIRADS_ALIAS
from core.cama.episodio_clinico.enums import TipoEpisodio, TIPO_EPISODIO_ALIAS
-17
View File
@@ -1,17 +0,0 @@
from enum import Enum
class TipoEpisodio(str, Enum):
"""IND-02: la unidad de análisis para evaluación de desempeño del
modelo es un episodio de tamizaje, diagnóstico o tratamiento."""
TAMIZAJE = "TAMIZAJE"
DIAGNOSTICO = "DIAGNOSTICO"
TRATAMIENTO = "TRATAMIENTO"
TIPO_EPISODIO_ALIAS: dict[str, str] = {
"SCREENING": "TAMIZAJE",
"DIAGNOSTIC": "DIAGNOSTICO",
"TREATMENT": "TRATAMIENTO",
}
-62
View File
@@ -1,62 +0,0 @@
from datetime import date, datetime, timezone
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import HOSPITAL_ID_LENGTH
class EpisodioClinico(CaMaModel, table=True):
"""IND-02/IND-03: clinical episode for CaMa. Same structure as
`core.cacu.episodio_clinico.model.EpisodioClinico`."""
episodio_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
)
tipo_episodio: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="valor de core.cama.episodio_clinico.enums.TipoEpisodio guardado como texto",
)
nm_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("notamedica.nm_id"), index=True),
description="nota médica cuyo contenido escrito origina/documenta el episodio",
)
cie10_codigo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
especialidad_medica: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
evento_fecha: date = Field(
sa_column=sa.Column(sa.Date, nullable=False),
description="fecha del evento de interés que define el episodio",
)
ventana_inicio: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
ventana_fin: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
episodio_anterior_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("episodioclinico.episodio_id"), index=True),
)
created_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_column=sa.Column(sa.DateTime, nullable=False),
)
+77
View File
@@ -0,0 +1,77 @@
"""CaMa's follow-up list (pure): the patients whose latest mammogram reported by the cut-off
is BI-RADS 4 to 6 and was taken within the window, with where her biopsy stands and how soon
she should be seen.
Status, from the biopsies that mammogram led to, reported by the cut-off:
- cancer: one found cancer (in situ or invasive);
- pending_biopsy: none reported;
- biopsy_no_result: the latest has no grade;
- benign_biopsy: otherwise.
Priority: high for a cancer, or a pending biopsy after a BI-RADS 5 or 6; medium for any other
pending biopsy or one without result; low otherwise."""
from datetime import date
from core import cama
from core.measures import as_day
WINDOWS = cama.FOLLOW_UP_WINDOWS
SORTS = ("-recent",)
DEFAULT_HORIZON = None
STATUS_SYSTEM = "cama-follow-up-status"
PROCEDURES: tuple[str, ...] = ()
REPORT_FACTS: dict[str, str] = {}
URGENT = ["5", "6"] # BI-RADS whose pending biopsy is high priority
def _ranked(row: dict) -> tuple:
return as_day(row["exam_date"]), as_day(row["report_date"]), row["birads_rank"] or 0
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
"""From each reported mammogram and the biopsies it led to (`gold.cama_mammogram_biopsies`),
who is on the list, most recent mammogram first."""
latest: dict[str, dict] = {}
biopsies: dict[str, list[dict]] = {}
for row in rows:
exam, report = as_day(row["exam_date"]), as_day(row["report_date"])
if row["birads"] is None or report is None or not exam <= report <= cutoff:
continue
person = row["person_id"]
if person not in latest or _ranked(row) > _ranked(latest[person]):
latest[person] = row
found = as_day(row["biopsy_report_date"])
if found is not None and exam <= found <= cutoff:
biopsies.setdefault(row["mammogram_id"], []).append(row)
out = []
for person, row in latest.items():
if row["birads"] not in cama.BIRADS_4_TO_6 or not start <= as_day(row["exam_date"]):
continue
mine = biopsies.get(row["mammogram_id"], [])
shown = max(mine, key=lambda b: (as_day(b["biopsy_report_date"]), b["biopsy_id"]),
default=None) # fmt: skip
cancers = [as_day(b["biopsy_report_date"]) for b in mine if b["histology"] in cama.CANCER]
if cancers:
status, priority = "cancer", "high"
elif shown is None:
status = "pending_biopsy"
priority = "high" if row["birads"] in URGENT else "medium"
elif shown["histology"] is None:
status, priority = "biopsy_no_result", "medium"
else:
status, priority = "benign_biopsy", "low"
out.append({
"person_id": person, "birth_date": row["birth_date"], "status": status,
"priority": priority, "recent": as_day(row["exam_date"]),
"first_cancer": min(cancers, default=None),
}) # fmt: skip
return sorted(out, key=lambda r: (-r["recent"].toordinal(), r["person_id"]))
def status(row: dict, cutoff: date) -> None:
"""A patient's status exists only on the list."""
return None
def ordered(rows: list[dict], sort: str, risks: dict, horizon) -> list[dict]:
return rows
-214
View File
@@ -1,214 +0,0 @@
"""Las tablas de indicadores_kit en el dominio CaMa.
Viven en el registro de `CaMaModel`, en la misma base que el staging de
CaMa (ADR-004). Las columnas se declaran una vez en `core.indicadores`;
aquí solo se instancian. Ninguna llave foránea apunta a una tabla de
staging: `persona` es propia aunque repita a `paciente`.
"""
from core.cama.base import CaMaModel
from core.indicadores.cohortes import (
CohorteArmadoBase,
CohorteExclusionBase,
CohorteMiembroBase,
CohorteVariableBase,
EvaluacionRiesgoBase,
EvaluacionRiesgoLoteBase,
armado_unico,
evaluacion_unica,
variable_con_un_valor,
)
from core.indicadores.catalogos import (
CatEstudioBase,
CatMapeoBase,
CatResultadoBase,
CatSistemaFuenteBase,
CatValorBase,
estado_de_valor_conocido,
reglas_de_mapeo,
tipo_de_valor_conocido,
vigencia_ordenada,
)
from core.indicadores.plata import (
ObservacionClinicaBase,
ProcedimientoClinicoBase,
clase_conocida,
indice_de_observacion,
indice_de_procedimiento,
observacion_en_catalogo,
llave_de_observacion,
llave_de_procedimiento,
)
from core.indicadores.comunes import CargaBase, PeriodoObservacionBase, PersonaDerechohabienteBase
from core.indicadores.registro import (
DefParametroBase,
DimFechaBase,
DimGrupoEdadBase,
DimPeriodoBase,
)
from core.indicadores.publicacion import (
CatEstratoBase,
CatEstratoValorBase,
CatMeasureBase,
CatMeasureEstratoBase,
CatMeasureGrupoBase,
CatMeasureResultadoBase,
CatMeasureValorBase,
MeasureReportUnidadBase,
MeasureReportUnidadEstratoBase,
contrato_y_unidad_conocidos,
origen_conocido,
poblacion_conocida,
una_poblacion_por_indicador,
unidad_de_estrato_conocida,
valor_de_estrato_en_catalogo,
)
from core.indicadores.reportes import (
MeasureReportBase,
)
class Persona(CaMaModel, PersonaDerechohabienteBase, table=True):
__tablename__ = "persona"
class PeriodoObservacion(CaMaModel, PeriodoObservacionBase, table=True):
__tablename__ = "periodo_observacion"
class Carga(CaMaModel, CargaBase, table=True):
__tablename__ = "carga"
class DefParametro(CaMaModel, DefParametroBase, table=True):
__tablename__ = "def_parametro"
class DimPeriodo(CaMaModel, DimPeriodoBase, table=True):
__tablename__ = "dim_periodo"
class DimFecha(CaMaModel, DimFechaBase, table=True):
__tablename__ = "dim_fecha"
class DimGrupoEdad(CaMaModel, DimGrupoEdadBase, table=True):
__tablename__ = "dim_grupo_edad"
class MeasureReport(CaMaModel, MeasureReportBase, table=True):
__tablename__ = "measure_report"
# --- El oro por unidad y su catálogo (§6f, MD-19) ---
class CatMeasure(CaMaModel, CatMeasureBase, table=True):
__tablename__ = "cat_measure"
__table_args__ = contrato_y_unidad_conocidos()
class CatMeasureResultado(CaMaModel, CatMeasureResultadoBase, table=True):
__tablename__ = "cat_measure_resultado"
__table_args__ = (poblacion_conocida(), una_poblacion_por_indicador())
class CatMeasureValor(CaMaModel, CatMeasureValorBase, table=True):
__tablename__ = "cat_measure_valor"
__table_args__ = (origen_conocido(),)
class CatMeasureGrupo(CaMaModel, CatMeasureGrupoBase, table=True):
__tablename__ = "cat_measure_grupo"
class CatEstrato(CaMaModel, CatEstratoBase, table=True):
__tablename__ = "cat_estrato"
__table_args__ = (unidad_de_estrato_conocida(),)
class CatEstratoValor(CaMaModel, CatEstratoValorBase, table=True):
__tablename__ = "cat_estrato_valor"
class CatMeasureEstrato(CaMaModel, CatMeasureEstratoBase, table=True):
__tablename__ = "cat_measure_estrato"
class MeasureReportUnidad(CaMaModel, MeasureReportUnidadBase, table=True):
__tablename__ = "measure_report_unidad"
class MeasureReportUnidadEstrato(CaMaModel, MeasureReportUnidadEstratoBase, table=True):
__tablename__ = "measure_report_unidad_estrato"
__table_args__ = (valor_de_estrato_en_catalogo(),)
# --- Catálogos de la plata (F1): estudio -> resultado -> valor, de core/catalogos/cama.toml ---
class CatEstudio(CaMaModel, CatEstudioBase, table=True):
__tablename__ = "cat_estudio"
class CatResultado(CaMaModel, CatResultadoBase, table=True):
__tablename__ = "cat_resultado"
__table_args__ = (tipo_de_valor_conocido(),)
class CatValor(CaMaModel, CatValorBase, table=True):
__tablename__ = "cat_valor"
__table_args__ = (estado_de_valor_conocido(),)
class CatSistemaFuente(CaMaModel, CatSistemaFuenteBase, table=True):
__tablename__ = "cat_sistema_fuente"
__table_args__ = (vigencia_ordenada("cat_sistema_fuente"),)
class CatMapeo(CaMaModel, CatMapeoBase, table=True):
__tablename__ = "cat_mapeo"
__table_args__ = reglas_de_mapeo()
# --- La plata de dos tablas (F5, ADR-MD-007) ---
class Procedimiento(CaMaModel, ProcedimientoClinicoBase, table=True):
__tablename__ = "procedimiento"
__table_args__ = (clase_conocida(), llave_de_procedimiento(), indice_de_procedimiento())
class Observacion(CaMaModel, ObservacionClinicaBase, table=True):
__tablename__ = "observacion_clinica" # `observacion` choca con la CTE `observacion` del motor (T-18r)
__table_args__ = (*observacion_en_catalogo(), llave_de_observacion(), indice_de_observacion())
# --- Cohortes para modelos y estimaciones de riesgo (oro restringido, ADR-MD-003; CaMa desde MD-12) ---
class CohorteArmado(CaMaModel, CohorteArmadoBase, table=True):
__tablename__ = "cohorte_armado"
__table_args__ = (armado_unico(),)
class CohorteMiembro(CaMaModel, CohorteMiembroBase, table=True):
__tablename__ = "cohorte_miembro"
class CohorteExclusion(CaMaModel, CohorteExclusionBase, table=True):
__tablename__ = "cohorte_exclusion"
class CohorteVariable(CaMaModel, CohorteVariableBase, table=True):
__tablename__ = "cohorte_variable"
__table_args__ = (variable_con_un_valor(),)
class EvaluacionRiesgoLote(CaMaModel, EvaluacionRiesgoLoteBase, table=True):
__tablename__ = "evaluacion_riesgo_lote"
class EvaluacionRiesgo(CaMaModel, EvaluacionRiesgoBase, table=True):
__tablename__ = "evaluacion_riesgo"
__table_args__ = (evaluacion_unica(),)
-18
View File
@@ -1,18 +0,0 @@
## mastografia
Una fila por estudio de mastografía · fuente: DICOM + OCR/NLP sobre PDF de interpretación
| Columna | Fuente | Descripción |
| --------------------- | ------------------------------- | ------------------------------------------------------------------ |
| `mast_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital| FK hacia paciente, resuelto en el loader, nulo si no hay match |
| `pac_id_hospital` | Hospital, DG1 | Identificador hospitalario del paciente, desnormalizado |
| `ord_id` | Derivado, lookup en ordenes_estudio | FK formal a `ordenesestudio.ord_id`; el loader lo resuelve comparando `ord_numero_hospital` de este registro con `ordenes_estudio.ord_numero_hospital` |
| `ord_numero_hospital` | Hospital, IM1 | Número de orden asignado por el HIS; clave de join para resolver `ord_id` |
| `mast_fecha_toma` | Hospital, IM2 | Fecha de toma del estudio entregada por el sistema DICOM |
| `mast_fecha_reporte` | Hospital, IM5 | Fecha del reporte de interpretación |
| `mast_calidad_imagen` | Derivado, OCR sobre PDF IM5 | Calidad técnica del estudio para interpretación |
| `mast_birads` | Derivado, OCR sobre PDF IM5 | Clasificación BI-RADS del reporte de interpretación |
| `mast_dicom_blob` | Hospital, IM6 | Contenido binario del archivo DICOM |
| `mast_interpretacion` | Hospital, IM5 | Enlace o referencia a la interpretación del radiólogo |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
-1
View File
@@ -1 +0,0 @@
from core.cama.mastografia.model import Mastografia
-35
View File
@@ -1,35 +0,0 @@
from enum import Enum
class BIRADS(str, Enum):
B0 = "B0" # incomplete
B1 = "B1" # negative
B2 = "B2" # benign
B3 = "B3" # probably benign
B4 = "B4" # suspicious
B5 = "B5" # highly suggestive of malignancy
B6 = "B6" # known biopsy-proven malignancy
BIRADS_ALIAS: dict[str, str] = {
"BIRADS 0": "B0", "BIRADS 1": "B1", "BIRADS 2": "B2",
"BIRADS 3": "B3", "BIRADS 4": "B4", "BIRADS 5": "B5", "BIRADS 6": "B6",
"BI-RADS 0": "B0", "BI-RADS 1": "B1", "BI-RADS 2": "B2",
"BI-RADS 3": "B3", "BI-RADS 4": "B4", "BI-RADS 5": "B5", "BI-RADS 6": "B6",
"0": "B0", "1": "B1", "2": "B2", "3": "B3", "4": "B4", "5": "B5", "6": "B6",
# The 4A/4B/4C subcategories (ACR BI-RADS lexicon) are common in real
# reports; this schema doesn't track them separately, so they fold into
# the base B4 rather than being rejected as out-of-catalog.
"BIRADS 4A": "B4", "BIRADS 4B": "B4", "BIRADS 4C": "B4",
"BI-RADS 4A": "B4", "BI-RADS 4B": "B4", "BI-RADS 4C": "B4",
"4A": "B4", "4B": "B4", "4C": "B4",
# Raw hospital source values (mastografia.mast_birads) spell the
# subcategory directly onto the code, e.g. "B4A" rather than "4A".
"B4A": "B4", "B4B": "B4", "B4C": "B4",
}
class GradoHistologicoMama(str, Enum):
BENIGNO = "BENIGNO"
CARCINOMA_IN_SITU = "CARCINOMA_IN_SITU"
CARCINOMA_INVASOR = "CARCINOMA_INVASOR"
DESCONOCIDO = "DESCONOCIDO"
-62
View File
@@ -1,62 +0,0 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
class Mastografia(CaMaModel, table=True):
"""
Modelo ORM para mastografía.
"""
mast_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
description="identificador hospitalario, obligatorio para vincular estudios con pacientes",
)
ord_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("ordenesestudio.ord_id"), index=True),
description="FK resuelto por el loader via lookup en ordenes_estudio.ord_numero_hospital",
)
ord_numero_hospital: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
mast_fecha_toma: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
mast_fecha_reporte: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
mast_calidad_imagen: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
mast_birads: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
mast_dicom_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(FileBlob),
)
mast_interpretacion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="enlace o referencia a la interpretación del radiólogo; formato pendiente",
)
+114
View File
@@ -0,0 +1,114 @@
"""CaMa's measures (`core.measures` evaluates them), over the gold rows of
`persistance.measures`: mammograms, biopsies, and each mammogram with the biopsies it led to.
A mammogram's report, a biopsy's report and a diagnosis note can become known after the
mammogram itself; asked before then, a row has them empty (`facts`), so the mammogram counts
with no data instead of being left out."""
from core import cama
from core.measures import (
NO_BIOPSY,
NO_DATA,
Composition,
Duration,
Measure,
Proportion,
as_day,
desc,
)
H = cama.HORIZONS
REPORT = {"report_known_at": ("report_date", "birads", "birads_rank", "days_sample_report",
"report_diagnosis_date", "days_report_diagnosis")} # fmt: skip
DIAGNOSIS = {"diagnosis_known_at": ("diagnosis_date", "days_sample_diagnosis")}
BIOPSY = {"biopsy_known_at": ("biopsy_report_date", "histology", "histology_rank")}
def reported(row: dict) -> bool:
"""A mammogram with a reported BI-RADS."""
return row["birads"] is not None and row["report_date"] is not None
def most_severe(row: dict) -> tuple:
"""Her most severe reported mammogram ranks highest; on a tie, the latest."""
return reported(row), row["birads_rank"] or 0, as_day(row["exam_date"])
def then_its_most_severe_biopsy(row: dict) -> tuple:
"""Her most severe mammogram, then its most severe reported biopsy, the latest first."""
counted = row["biopsy_report_date"] is not None
return (*most_severe(row), counted, desc(row["histology_rank"]),
desc(as_day(row["biopsy_report_date"])), desc(row["biopsy_id"])) # fmt: skip
def birads(row: dict) -> str:
return row["birads"] if reported(row) else NO_DATA
def biopsy_histology(row: dict) -> str:
"""The chosen biopsy's grade (NO_BIOPSY when her mammogram led to none reported)."""
if row["biopsy_report_date"] is None:
return NO_BIOPSY
return row["histology"] or NO_DATA
def four_to_six(row: dict) -> bool:
return reported(row) and row["birads"] in cama.BIRADS_4_TO_6
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no breast cancer note before
BIRADS = ("birads", lambda row, p: row["birads"])
MEASURES = {m.id: m for m in [
Measure("CAMA_BIRADS", "Distribución de BI-RADS", "mammograms",
Composition(most_severe, birads, date="exam_date"), facts=REPORT),
Measure("CAMA_BIRADS456_PACIENTE",
"Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6", "mammograms",
Composition(most_severe, birads, admit=four_to_six, date="exam_date"), facts=REPORT),
Measure("CAMA_BIRADS456_MASTOGRAFIA",
"Porcentaje individual de mastografías con resultado BI-RADS 4, 5 y 6", "mammograms",
Composition(most_severe, birads, where=four_to_six, unit="mammogram_id",
date="exam_date"), facts=REPORT),
Measure("CAMA_BIRADS_CANCER_INVASOR", "BI-RADS de la mastografía previa a un cáncer invasor",
"biopsies",
Composition(lambda r: (r["birads"] is not None, as_day(r["report_date"]),
r["biopsy_id"]),
lambda r: r["birads"] or NO_DATA,
where=lambda r: r["histology"] in cama.INVASIVE, date="report_date"),
known="report_known_at"),
Measure("CAMA_BIOPSIAS", "Distribución de resultados de biopsia", "biopsies",
Composition(lambda r: (r["histology"] is not None, as_day(r["report_date"])),
lambda r: r["histology"] or NO_DATA, unit="biopsy_id",
date="report_date"),
known="report_known_at"),
Measure("CAMA_HISTOPATOLOGIA_BIRADS", "Resultado histopatológico por categoría BI-RADS",
"mammogram_biopsies",
Composition(then_its_most_severe_biopsy, biopsy_histology, admit=four_to_six,
strata=(BIRADS,), date="exam_date"),
facts=REPORT | BIOPSY),
Measure("CAMA_CONFIRMACION_BIRADS45", "Tasa de confirmación histopatológica",
"mammogram_biopsies",
Proportion(lambda r: r["biopsy_report_date"] is not None,
denominator=lambda r: r["report_date"] is not None
and r["birads"] in cama.SUSPICIOUS,
unit="mammogram_id", date="exam_date"),
"increase", group="principal", facts=REPORT | BIOPSY),
Measure("CAMA_TASA_DETECCION_HISTOPATOLOGICA", "Tasa de detección histopatológica",
"biopsies",
Proportion(lambda r: r["histology"] in cama.CANCER,
denominator=lambda r: r["histology"] in cama.BIOPSY_SEVERITY,
unit="biopsy_id", date="report_date"),
group="principal", known="report_known_at"),
Measure("CAMA_EU38A", "Días de la toma de la mastografía a su resultado", "mammograms",
Duration("days_sample_report", "report_date", "exam_date", H["sample_to_report"],
unit="mammogram_id", date="exam_date"), "decrease", facts=REPORT),
Measure("CAMA_DIAS_TOMA_DIAGNOSTICO", "Tiempo de tamizaje a diagnóstico", "mammograms",
Duration("days_sample_diagnosis", "diagnosis_date", "exam_date", H["to_diagnosis"],
units=NO_HISTORY, unit="mammogram_id", date="exam_date"),
"decrease", facts=DIAGNOSIS),
Measure("CAMA_DIAS_RESULTADO_DIAGNOSTICO", "Tiempo de resultado a diagnóstico", "mammograms",
Duration("days_report_diagnosis", "report_diagnosis_date", "report_date",
H["to_diagnosis"], units=NO_HISTORY, unit="mammogram_id",
date="report_date"),
"decrease", known="report_known_at"),
]} # fmt: skip
-17
View File
@@ -1,17 +0,0 @@
from core.cama.paciente.model import Paciente
from core.cama.ordenes_estudio.model import OrdenesEstudio
from core.cama.mastografia.model import Mastografia
from core.cama.biopsia_mama.model import BiopsiaMama
from core.cama.nota_medica.model import NotaMedica
from core.cama.biometria_hematica.model import BiometriaHematica
from core.cama.episodio_clinico.model import EpisodioClinico
__all__ = [
"Paciente",
"OrdenesEstudio",
"Mastografia",
"BiopsiaMama",
"NotaMedica",
"BiometriaHematica",
"EpisodioClinico",
]
-35
View File
@@ -1,35 +0,0 @@
## nota_medica
| Columna | Fuente | Descripción |
|---|---|---|
| `nm_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | FK lógica hacia `paciente.pac_id` — resuelto en carga, nulo si no hay match |
| `pac_id_hospital` | Hospital, DG1 | Identificador hospitalario del paciente |
| `nm_id_hospital` | Hospital, — | Identificador original de la nota en el HIS |
| `nm_nota_previa_id` | Hospital, — | FK autorreferencial para cadena de seguimiento |
| `nm_tipo_nota` | Hospital, NM1 | Tipo de visita |
| `nm_especialidad` | Hospital, NM1 | Especialidad médica que emite la nota |
| `nm_fecha` | Hospital, NM3 | Fecha de la consulta o procedimiento |
| `nm_medico_tratante` | Hospital, NM4 | Médico que emite la nota |
| `nm_motivo_consulta` | Hospital, NM10 | Motivo de consulta referido o registrado |
| `nm_interrogatorio` | Hospital, NM11 | Antecedentes relevantes e historia clínica |
| `nm_diagnostico_texto` | Hospital, NM2 | Diagnóstico clínico en texto libre |
| `nm_cie_codigo` | Hospital, NM17 | Código CIE-10 del diagnóstico principal |
| `nm_cie_descripcion` | Hospital, NM17 | Descripción del código CIE-10 |
| `nm_tratamiento_texto` | Hospital, NM12 | Descripción del tratamiento indicado |
| `nm_receta` | Hospital, NM14 | Medicamentos prescritos |
| `nm_plan_estudios` | Hospital, NM15 | Estudios planeados con orden, fecha y resultado esperado |
| `nm_pronostico` | Hospital, NM13 | Pronóstico registrado por el médico |
| `nm_observaciones` | Hospital, NM16 | Observaciones adicionales del médico |
| `nm_masa_corporal` | Hospital, NM5 | Peso corporal en la visita (kg) |
| `nm_talla` | Hospital, NM5 | Talla registrada en la visita (m) |
| `nm_imc_visita` | Derivado, pipeline | IMC calculado a partir de peso y talla |
| `nm_frecuencia_cardiaca` | Hospital, NM6 | Frecuencia cardíaca (lpm) |
| `nm_frecuencia_respiratoria` | Hospital, NM7 | Frecuencia respiratoria (rpm) |
| `nm_presion_arterial_sistolica` | Hospital, NM8 | Presión arterial sistólica (mmHg) |
| `nm_presion_arterial_diastolica` | Hospital, NM8 | Presión arterial diastólica (mmHg) |
| `nm_temperatura` | Hospital, NM9 | Temperatura corporal (°C) |
---
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
-1
View File
@@ -1 +0,0 @@
from core.cama.nota_medica.model import NotaMedica
-40
View File
@@ -1,40 +0,0 @@
from enum import Enum
class TipoNota(str, Enum):
CONSULTA = "CONSULTA"
EGRESO = "EGRESO"
INGRESO = "INGRESO"
URG_EGRESO = "URG_EGRESO"
TIPO_NOTA_ALIAS: dict[str, str] = {
"URG. EGRESO": "URG_EGRESO",
}
class Especialidad(str, Enum):
MEDICINA_FAMILIAR = "MEDICINA_FAMILIAR"
CIRUGIA_ONCOLOGICA = "CIRUGIA_ONCOLOGICA"
CLINICA_MUJER_COLPOSCOPIA = "CLINICA_MUJER_COLPOSCOPIA"
ESPECIALIDAD_ALIAS: dict[str, str] = {
"MEDICINA FAMILIAR": "MEDICINA_FAMILIAR",
"CIRUGIA ONCOLOGICA": "CIRUGIA_ONCOLOGICA",
"CLINICA DE MUJER Y COLPOSCOPIA": "CLINICA_MUJER_COLPOSCOPIA",
}
class Parentesco(str, Enum):
AFILIADO = "Afiliado"
# Other values pending confirmation with the HIS administrator.
PARENTESCO_ALIAS: dict[str, str] = {
"AFILIADO": "Afiliado",
}
class Dependencia(str, Enum):
GOBIERNO = "GOBIERNO"
CALLES_Y_CAMINOS = "CALLES Y CAMINOS"
# Tentative values, pending confirmation with the HIS administrator.
DEPENDENCIA_ALIAS: dict[str, str] = {
"CALLES Y CAMINOS": "CALLES Y CAMINOS",
}
-124
View File
@@ -1,124 +0,0 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import HOSPITAL_ID_LENGTH
class NotaMedica(CaMaModel, table=True):
"""
Notas medicas del paciente
"""
nm_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="rellenado por el loader via lookup en paciente.pac_id_hospital; puede quedar nulo",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
description="DG1: identificador hospitalario obligatorio para vincular estudios con pacientes",
)
# Bounded and indexed: part of the natural key (with pac_id_hospital)
# the import layer upserts/merges notes on.
nm_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
)
nm_nota_previa_id: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_tipo_nota: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_especialidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
nm_medico_tratante: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_motivo_consulta: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_interrogatorio: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_diagnostico_texto: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_cie_codigo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_cie_descripcion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_tratamiento_texto: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_receta: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_plan_estudios: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_pronostico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_masa_corporal: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
nm_talla: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
nm_imc_visita: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
nm_frecuencia_cardiaca: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_frecuencia_respiratoria: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_presion_arterial_sistolica: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_presion_arterial_diastolica: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_temperatura: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
-23
View File
@@ -1,23 +0,0 @@
## ordenes_estudio
Al parecer no aparece en la plataforma el pdf de la orden del estudio emitido.
Tabla de órdenes, 1 fila por solicitud médica. Fuente: TC2 parcial, TVPH2, HPC2, NM3, NM4
| Columna | Fuente | Descripción |
| ------------------------ | ---------------------------- | ----------------------------------------------------------------------------------------------------- |
| `ord_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | FK hacia paciente.pac_id, resuelto en carga por lookup en paciente |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, desnormalizado para joins sin pasar por paciente |
| `ord_numero_hospital` | Hospital, TC1, TVPH1, HPC1 | Número de orden de 5 dígitos asignado por el HIS, índice único, join lógico hacia tablas de resultado |
| `ord_tipo_estudio` | Hospital, TC1, TVPH1, HPC1 | Tipo de estudio solicitado, texto libre, enum pendiente de confirmar con administrador |
| `ord_fecha` | Hospital, TVPH2, HPC2 | Fecha en que el médico emitió la orden |
| `ord_fecha_solicitud` | Hospital, TVPH2, HPC2 | Fecha sugerida por el médico para realizar el estudio |
| `ord_fecha_resultado` | Hospital, HPC3, TVPH4 | Fecha en que el resultado estuvo disponible, nulo hasta que llegue |
| `ord_estatus` | Hospital, TVPH4, HPC3 | Estatus de la orden, texto libre, enum pendiente de confirmar con administrador |
| `ord_diagnostico` | Hospital, ord | Diagnóstico presuntivo del médico (pantalla Asignar diagnóstico) |
| `ord_observaciones` | Hospital, — | Observaciones generales de la orden |
| `ord_especialidad` | Hospital, NM1 | Especialidad del médico solicitante |
| `ord_medico_solicitante` | Hospital, NM4 | Nombre o clave del médico tratante que emite la orden |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
@@ -1 +0,0 @@
from core.cama.ordenes_estudio.model import OrdenesEstudio
-12
View File
@@ -1,12 +0,0 @@
from enum import Enum
class TipoEstudio(str, Enum):
MASTOGRAFIA = "MASTOGRAFIA" # the study this domain orders
BIOPSIA_CHICA = "BIOPSIA_CHICA"
SOLICITUD_PAPANICOLAO_BASE_LIQUIDA = "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA"
TIPO_ESTUDIO_ALIAS: dict[str, str] = {
"BIOPSIA CHICA": "BIOPSIA_CHICA",
"SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
"Solicitud de Papanicolao en Base Liquida": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
}
-77
View File
@@ -1,77 +0,0 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import HOSPITAL_ID_LENGTH
class OrdenesEstudio(CaMaModel, table=True):
"""
Modelo ORM para órdenes de estudio.
Condensa cabecera y detalle en una sola tabla.
Una orden corresponde a un único tipo de estudio.
El resultado (citología, biopsia) referencia esta tabla via ord_numero_hospital (join logico).
"""
ord_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("paciente.pac_id"), index=True),
)
# Denormalized so studies join without going through paciente
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
ord_numero_hospital: int = Field(
sa_column=sa.Column(sa.Integer, unique=True, index=True, nullable=False),
description="TC1/TVPH1/HPC1: numero de orden de 5 digitos asignado por el HIS",
)
ord_tipo_estudio: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Citología Base líquida, Biopsia Cervical"
)
ord_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha de emisión de la orden por el médico",
)
ord_fecha_solicitud: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha sugerida por el médico para realizar el estudio",
)
ord_fecha_resultado: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha en que el resultado estuvo disponible, nulo hasta que llegue",
)
ord_estatus: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="REALIZADO E INTERPRETADO",
)
ord_diagnostico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Diagnóstico, pantalla: Asignar diagnostico",
)
ord_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
ord_especialidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="",
)
ord_medico_solicitante: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Nombre o clave del médico NM4",
)
-14
View File
@@ -1,14 +0,0 @@
## pacientes
| Columna | Fuente | Descripción |
| ---------------------- | ----------------------- | ---------------------------------------------------------------------------------------------- |
| `pac_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, índice único, permite lookup desde tablas de resultado |
| `pac_fecha_nacimiento` | Hospital, DG2 | Fecha de nacimiento |
| `pac_sexo` | Hospital, DG3 | Sexo biológico |
| `pac_codigo_postal` | Hospital, DG4 | Código postal de residencia |
| `pac_dependencia` | Hospital, DG5 | Unidad de cobertura o dependencia administrativa |
| `pac_parentesco` | Hospital, — | Parentesco del titular respecto al trabajador |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
-1
View File
@@ -1 +0,0 @@
from core.cama.paciente.model import Paciente
-18
View File
@@ -1,18 +0,0 @@
from enum import Enum
class SexoBiologico(str, Enum):
"""
Sexo biológico del paciente.
Hasta ahora asumieremos que se guarda como texto en el mercado de datos:
("Femenino", "Masculino").
Solamente se usará en la capa de validación.
"""
F = "Femenino"
M = "Masculino"
SEXO_BIOLOGICO_ALIAS: dict[str, str] = {
"F": "Femenino",
"M": "Masculino",
"FEMENINO": "Femenino",
"MASCULINO": "Masculino",
}
-49
View File
@@ -1,49 +0,0 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import HOSPITAL_ID_LENGTH
class Paciente(CaMaModel, table=True):
"""
Modelo ORM, solamente almacena.
Se reservan las validaciones de dominio para otra capa.
"""
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# The patient's original HIS id (DG1), uniquely indexed for lookups
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), unique=True, index=True, nullable=False),
)
pac_sexo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
# IND-01: required; age at each event of interest (clinical episode) is
# computed from it.
pac_fecha_nacimiento: date = Field(
sa_column=sa.Column(sa.Date, nullable=False),
)
pac_codigo_postal: Optional[str] = Field(
default=None,
sa_column=sa.Column(
sa.CHAR(5),
),
description="Código postal de 5 dígitos",
)
pac_dependencia: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Dependencia",
)
pac_parentesco: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Parentesco",
)
+187
View File
@@ -0,0 +1,187 @@
"""The platform's clinical catalog: every study, the events it is made of, its fields, and the
code systems their values come from. It is data (the YAML files beside this module) and
changes only by a reviewed commit; nothing ships that it doesn't name.
Everything that validates, stores or serves a clinical value reads it: the pydantic model of
each study (what a pipeline's target checks rows against), the long silver tables and their
wide views (dbt), and the FHIR conformance resources the API serves.
"""
from datetime import date
from functools import cache
from pathlib import Path
from typing import Annotated, Any, ClassVar, Literal
import yaml
from pydantic import BaseModel, ConfigDict, Field, create_model, model_validator
HERE = Path(__file__).parent
EventClass = Literal["order", "encounter", "sample", "report", "part"]
# `file`: a document or signal kept whole (an EEG); silver holds its content hash, the
# platform keeps the content once (persistance.files).
ValueType = Literal["code", "boolean", "number", "date", "text", "file"]
class System(BaseModel):
model_config = ConfigDict(extra="forbid")
url: str
title: str
external: bool = False # a standard system we name but don't publish
class Event(BaseModel):
model_config = ConfigDict(extra="forbid")
date: str # the field that dates it
parent: EventClass | None = None
class FieldDef(BaseModel):
model_config = ConfigDict(extra="forbid")
type: ValueType
event: EventClass
title: str
system: str | None = None
codes: dict[str, str] = {} # allowed code -> display; empty: any code of `system`
pattern: str | None = None
unit: str | None = None
required: bool = False
@model_validator(mode="after")
def _codes_have_a_system(self):
if self.type == "code" and self.system is None:
raise ValueError("a code field names its system")
if self.type != "code" and (self.codes or self.system):
raise ValueError("only code fields take a system and codes")
return self
class Study(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str
key: list[str] # fields that, with the person, identify one study instance
events: dict[EventClass, Event]
fields: dict[str, FieldDef]
@model_validator(mode="after")
def _consistent(self):
for name in self.key:
if name not in self.fields:
raise ValueError(f"key field {name} is not a field")
for cls, event in self.events.items():
if self.fields.get(event.date, None) is None or self.fields[event.date].type != "date":
raise ValueError(f"{cls}: its date {event.date} is not a date field")
if event.parent and event.parent not in self.events:
raise ValueError(f"{cls}: parent {event.parent} is not an event")
for name, f in self.fields.items():
if f.event not in self.events:
raise ValueError(f"{name}: event {f.event} is not one of the study's")
return self
def _load(name: str) -> dict:
return yaml.safe_load((HERE / f"{name}.yaml").read_text(encoding="utf-8"))
@cache
def systems() -> dict[str, System]:
return {k: System.model_validate(v) for k, v in _load("systems").items()}
@cache
def files() -> dict[str, list[str]]:
"""Each catalog file (a domain, or `common` to all) and the studies it defines."""
return {
path.stem: list(_load(path.stem))
for path in sorted(HERE.glob("*.yaml"))
if path.stem != "systems"
}
def of_domain(domain: str) -> list[str]:
"""The studies a domain serves: its own and the common ones."""
return [*files().get(domain, []), *files().get("common", [])]
@cache
def studies() -> dict[str, Study]:
"""Every study of every catalog file, by name (names are unique across files)."""
found: dict[str, Study] = {}
for path in sorted(HERE.glob("*.yaml")):
if path.stem == "systems":
continue
for name, spec in _load(path.stem).items():
if name in found:
raise ValueError(f"study {name} is defined twice")
study = Study.model_validate(spec)
unknown = {f.system for f in study.fields.values() if f.system} - set(systems())
if unknown:
raise ValueError(f"{name}: unknown systems {sorted(unknown)}")
found[name] = study
return found
class Record(BaseModel):
"""One row of a study, as a pipeline's target receives it."""
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
key: ClassVar[tuple[str, ...]] = ()
study: ClassVar[str] = ""
_TYPES: dict[str, Any] = {
"boolean": bool,
"number": float,
"date": date,
"text": str,
"file": str,
} # fmt: skip (a file field holds its content hash)
def _annotation(f: FieldDef) -> Any:
if f.type == "code" and f.codes:
kind: Any = Literal[tuple(f.codes)] # type: ignore[valid-type]
elif f.type == "code":
kind = Annotated[str, Field(pattern=f.pattern)] if f.pattern else str
else:
kind = _TYPES[f.type]
return kind if f.required else kind | None
@cache
def model(study: str) -> type[Record]:
"""The pydantic model a row of this study is checked against."""
spec = studies()[study]
fields = {
name: (_annotation(f), ... if f.required else None) for name, f in spec.fields.items()
}
found = create_model(study, __base__=Record, **fields) # type: ignore[call-overload]
found.key = tuple(spec.key)
found.study = study
return found
def value_column(f: FieldDef) -> str:
"""The typed column of the long observation table a field's value is stored in."""
return {"boolean": "value_bool", "number": "value_num", "date": "value_date"}.get(
f.type, "value_text"
)
def dbt_vars() -> dict:
"""What dbt reads (`var('catalog')`): each study's key, events and typed fields."""
return {
name: {
"key": s.key,
"events": {c: e.model_dump() for c, e in s.events.items()},
"fields": {
f: {
"type": d.type,
"event": d.event,
"column": value_column(d),
"codes": list(d.codes),
}
for f, d in s.fields.items()
},
}
for name, s in studies().items()
}
+117
View File
@@ -0,0 +1,117 @@
# Cervical cancer screening.
cervical_cytology:
title: Citología cervical
key: [sample_date]
events:
sample: {date: sample_date}
report: {date: report_date, parent: sample}
fields:
sample_date: {type: date, event: sample, title: Fecha de toma, required: true}
screening_history:
type: code
event: sample
title: Detección de cáncer de cérvix
system: cervical-screening-history
codes:
first_time: Primera vez en la vida
1_year_or_less: Un año o menos
2_years: 2 años
3_years_or_more: 3 o más años
# Condiciones ginecoobstétricas a la detección, as recorded at the sample: true when the
# form says it; otherwise unknown, never false (the source records only one of them).
gyn_puerperium: {type: boolean, event: sample, title: "Puerperio postparto o postaborto"}
gyn_pregnancy: {type: boolean, event: sample, title: "Embarazo actual"}
gyn_iud: {type: boolean, event: sample, title: "DIU in situ"}
gyn_hormonal_treatment: {type: boolean, event: sample, title: "Tratamiento hormonal"}
gyn_other_treatment: {type: boolean, event: sample, title: "Otro tratamiento ginecológico"}
gyn_postmenopause: {type: boolean, event: sample, title: "Posmenopausia"}
gyn_hysterectomy: {type: boolean, event: sample, title: "Histerectomía"}
gyn_not_applicable: {type: boolean, event: sample, title: "Condiciones ginecoobstétricas: no aplica"}
# Actualmente presenta, recorded like the conditions above: true or unknown, never false.
presents_discharge: {type: boolean, event: sample, title: "Actualmente presenta: flujo"}
presents_vulvar_pruritus: {type: boolean, event: sample, title: "Actualmente presenta: prurito o ardor vulvar"}
presents_abnormal_bleeding: {type: boolean, event: sample, title: "Actualmente presenta: sangrado anormal"}
presents_none: {type: boolean, event: sample, title: "Actualmente presenta: ninguno"}
cervix_exam:
type: code
event: sample
title: A la exploración se observa
system: cervix-exam
codes:
healthy: Cuello sano
abnormal_with_lesion: Cuello anormal con lesión
not_visible: No se observa cuello
report_date: {type: date, event: report, title: Fecha de reporte}
adequacy:
type: code
event: report
title: Calidad de la muestra
system: adequacy
codes: {satisfactory: Satisfactoria, unsatisfactory: Insatisfactoria}
result:
type: code
event: report
title: Resultado (Bethesda)
system: bethesda
codes:
NILM: Negativo para lesión intraepitelial o malignidad
ASC-US: Células escamosas atípicas de significado indeterminado
ASC-H: Células escamosas atípicas, no se descarta LIEAG
LSIL: Lesión intraepitelial escamosa de bajo grado
HSIL: Lesión intraepitelial escamosa de alto grado
CIS: Carcinoma in situ
hpv: {type: boolean, event: report, title: VPH de alto riesgo}
hpv_16: {type: boolean, event: report, title: VPH 16}
hpv_18: {type: boolean, event: report, title: VPH 18}
# The cytologist's additional findings, free text on the form (known with the report).
# A finding is true when the text states it; otherwise unknown, never false.
cyto_findings_text: {type: text, event: report, title: Hallazgos adicionales}
cyto_inflammation: {type: boolean, event: report, title: "Inflamación"}
cyto_reactive_changes: {type: boolean, event: report, title: "Cambios reactivos"}
cyto_bacterial_vaginosis_flora: {type: boolean, event: report, title: "Flora sugestiva de vaginosis bacteriana"}
cyto_candida: {type: boolean, event: report, title: "Microorganismos compatibles con Candida sp"}
cyto_bacillary_flora_cytolysis: {type: boolean, event: report, title: "Aumento de la flora bacilar con citólisis"}
cyto_intermediate_cytolysis: {type: boolean, event: report, title: "Citólisis de las células intermedias"}
cyto_trichomonas: {type: boolean, event: report, title: "Trichomonas vaginalis"}
cyto_leptothrix: {type: boolean, event: report, title: "Microorganismos compatibles con Leptothrix"}
cyto_actinomyces_organisms: {type: boolean, event: report, title: "Microorganismos compatibles con Actinomyces sp"}
cyto_actinomyces_changes: {type: boolean, event: report, title: "Cambios celulares compatibles con Actinomyces sp"}
cyto_herpes_simplex_changes: {type: boolean, event: report, title: "Cambios celulares compatibles con virus herpes simple"}
cyto_squamous_tubular_metaplasia: {type: boolean, event: report, title: "Metaplasia escamosa tubular"}
cyto_keratotic_changes: {type: boolean, event: report, title: "Cambios queratósicos"}
cyto_pregnancy_changes: {type: boolean, event: report, title: "Cambios asociados al embarazo"}
cyto_atrophy: {type: boolean, event: report, title: "Atrofia"}
cyto_hypoestrogenism: {type: boolean, event: report, title: "Hipoestrogenismo"}
cyto_radiotherapy_effect: {type: boolean, event: report, title: "Efecto de radioterapia"}
cyto_iud_changes: {type: boolean, event: report, title: "Cambios compatibles con dispositivo intrauterino"}
cyto_post_hysterectomy_glandular_cells: {type: boolean, event: report, title: "Células glandulares post-histerectomía"}
cyto_bacteria: {type: boolean, event: report, title: "Bacterias"}
cyto_herpes_image: {type: boolean, event: report, title: "Imagen del virus del herpes"}
cyto_fungi: {type: boolean, event: report, title: "Hongos"}
cyto_radiation: {type: boolean, event: report, title: "Cambios reactivos: radiación"}
cyto_repair: {type: boolean, event: report, title: "Cambios reactivos: reparación"}
cyto_iud_effect: {type: boolean, event: report, title: "Efecto del DIU"}
cyto_endometrial_cells_40_plus: {type: boolean, event: report, title: "Células endometriales, 40 años o más"}
cyto_findings_none: {type: boolean, event: report, title: "Hallazgos adicionales: ninguno"}
cervical_biopsy:
title: Biopsia cervical
key: [request_date]
events:
order: {date: request_date}
report: {date: report_date, parent: order}
fields:
request_date: {type: date, event: order, title: Fecha de solicitud, required: true}
cytology_sample_date: {type: date, event: order, title: Toma de la citología que la originó}
report_date: {type: date, event: report, title: Fecha de reporte}
histology:
type: code
event: report
title: Histología
system: who-cervical-histology
codes:
normal: Sin lesión
LSIL: Lesión intraepitelial escamosa de bajo grado (CIN 1)
HSIL: Lesión intraepitelial escamosa de alto grado (CIN 2-3)
CIS: Carcinoma in situ
carcinoma: Carcinoma invasor
+119
View File
@@ -0,0 +1,119 @@
# Breast cancer screening.
mammography:
title: Mastografía
key: [exam_date]
events:
sample: {date: exam_date}
report: {date: report_date, parent: sample}
fields:
exam_date: {type: date, event: sample, title: Fecha del estudio, required: true}
report_date: {type: date, event: report, title: Fecha de reporte}
adequacy:
type: code
event: report
title: Calidad de la imagen
system: adequacy
codes: {satisfactory: Satisfactoria, unsatisfactory: Insatisfactoria}
birads:
type: code
event: report
title: BI-RADS
system: bi-rads
codes:
'0': Incompleta, requiere estudios adicionales
'1': Negativa
'2': Hallazgos benignos
'3': Probablemente benigna
'4': Sospechosa
4A: Sospecha baja de malignidad
4B: Sospecha moderada de malignidad
4C: Sospecha alta de malignidad
'5': Altamente sugestiva de malignidad
'6': Malignidad confirmada por biopsia
breast_biopsy:
title: Biopsia de mama
key: [request_date, mammogram_exam_date]
events:
order: {date: request_date}
report: {date: report_date, parent: order}
fields:
request_date: {type: date, event: order, title: Fecha de solicitud, required: true}
mammogram_exam_date: {type: date, event: order, title: Mastografía que la originó}
report_date: {type: date, event: report, title: Fecha de reporte}
histology:
type: code
event: report
title: Histología
system: breast-histology
codes: {benign: Benigno, in_situ: In situ, invasive: Invasor}
histologic_type:
type: code
event: report
title: Tipo histológico (CIE-O-3)
system: icd-o-3
grade:
type: code
event: report
title: Grado histológico (Nottingham)
system: nottingham-grade
codes: {'1': Grado 1, '2': Grado 2, '3': Grado 3}
er:
type: code
event: report
title: Receptor de estrógeno
system: receptor-status
codes: &receptor {positive: Positivo, negative: Negativo}
pr:
type: code
event: report
title: Receptor de progesterona
system: receptor-status
codes: *receptor
her2:
type: code
event: report
title: HER2
system: receptor-status
codes: *receptor
ki67_pct: {type: number, event: report, title: Ki-67, unit: '%'}
size_mm: {type: number, event: report, title: Tamaño del tumor, unit: mm}
stage:
type: code
event: report
title: Estadio clínico (AJCC)
system: ajcc-stage
codes:
'0': Estadio 0
I: Estadio I (sin subgrupo)
II: Estadio II (sin subgrupo)
III: Estadio III (sin subgrupo)
IA: Estadio IA
IB: Estadio IB
IIA: Estadio IIA
IIB: Estadio IIB
IIIA: Estadio IIIA
IIIB: Estadio IIIB
IIIC: Estadio IIIC
IV: Estadio IV
breast_treatment:
title: Tratamiento de cáncer de mama
key: [start_date, kind]
events:
encounter: {date: start_date}
fields:
start_date: {type: date, event: encounter, title: Fecha de inicio, required: true}
kind:
type: code
event: encounter
title: Tratamiento
system: breast-treatment
required: true
codes:
breast_conserving_surgery: Cirugía conservadora
mastectomy: Mastectomía
chemotherapy: Quimioterapia
radiotherapy: Radioterapia
hormone_therapy: Hormonoterapia
anti_her2: Terapia anti-HER2
+36
View File
@@ -0,0 +1,36 @@
# Studies every domain shares.
clinical_note:
title: Nota médica
key: [note_date, specialty]
events:
encounter: {date: note_date}
fields:
note_date: {type: date, event: encounter, title: Fecha de la nota}
specialty:
type: code
event: encounter
title: Especialidad
system: specialty
codes:
colposcopy: Clínica de la mujer y colposcopia
oncology_surgery: Cirugía oncológica
medical_oncology: Oncología médica
radiation_oncology: Radio-oncología
family_medicine: Medicina familiar
pediatric_neurology: Neurología pediátrica
icd10:
type: code
event: encounter
title: Diagnóstico (CIE-10)
system: icd-10
pattern: '^[A-Z]\d{2}(\.\d{1,2})?$'
reason: {type: text, event: encounter, title: Motivo de consulta}
diagnosis_text: {type: text, event: encounter, title: Diagnóstico como se escribió}
death:
title: Defunción
key: []
events:
encounter: {date: death_date}
fields:
death_date: {type: date, event: encounter, title: Fecha de defunción, required: true}
+49
View File
@@ -0,0 +1,49 @@
# The code systems the platform's fields take their codes from. External systems are named by
# their canonical URI; only the codes a field allows are listed with the field.
bethesda:
url: https://isssteleon.org/fhir/CodeSystem/bethesda
title: Sistema Bethesda (citología cervical)
who-cervical-histology:
url: https://isssteleon.org/fhir/CodeSystem/who-cervical-histology
title: Clasificación OMS de lesiones cervicales (histología)
cervical-screening-history:
url: https://isssteleon.org/fhir/CodeSystem/cervical-screening-history
title: Antecedente de detección de cáncer de cérvix
cervix-exam:
url: https://isssteleon.org/fhir/CodeSystem/cervix-exam
title: Exploración del cuello uterino
bi-rads:
url: https://isssteleon.org/fhir/CodeSystem/bi-rads
title: BI-RADS
icd-10:
url: http://hl7.org/fhir/sid/icd-10
title: CIE-10
external: true
adequacy:
url: https://isssteleon.org/fhir/CodeSystem/adequacy
title: Calidad de la muestra
specialty:
url: https://isssteleon.org/fhir/CodeSystem/specialty
title: Especialidades
breast-histology:
url: https://isssteleon.org/fhir/CodeSystem/breast-histology
title: Histología de mama
ados2-module:
url: https://isssteleon.org/fhir/CodeSystem/ados2-module
title: Módulos del ADOS-2
icd-o-3:
url: http://terminology.hl7.org/CodeSystem/icd-o-3
title: CIE-O-3 (morfología)
external: true
nottingham-grade:
url: https://isssteleon.org/fhir/CodeSystem/nottingham-grade
title: Grado histológico de Nottingham
receptor-status:
url: https://isssteleon.org/fhir/CodeSystem/receptor-status
title: Estado de receptores hormonales y HER2
ajcc-stage:
url: https://isssteleon.org/fhir/CodeSystem/ajcc-stage
title: Estadio clínico AJCC (grupo)
breast-treatment:
url: https://isssteleon.org/fhir/CodeSystem/breast-treatment
title: Tratamientos de cáncer de mama
+60
View File
@@ -0,0 +1,60 @@
# 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}
-39
View File
@@ -1,39 +0,0 @@
# Catálogos de la plata (F1)
Un TOML por proyecto: estudio → resultado → valor.
El paso `catalogos` de `webapi.orchestration` los materializa en `cat_estudio`, `cat_resultado` y `cat_valor`
(`core/indicadores/catalogos.py`) antes de cargar. Un valor que sale del TOML pasa a `retirado`; nunca se borra.
```toml
[<estudio>]
etiqueta = "..."
codigos_hospital = ["..."] # cómo lo nombra el hospital (tipo de estudio de la orden, instrumento)
[<estudio>.resultados.<resultado>] # resultado_id = "<estudio>.<resultado>"
etiqueta = "..."
tipo_valor = "codigo" # codigo, booleano, numero, fecha, texto, externo
unidad = "min" # opcional (numero)
sistema = "CIE-10" # solo externo
valores = [ # solo codigo; el orden de la lista es el de presentación
{ valor = "NORMAL", etiqueta = "Normal" },
]
```
A result read from a document's text (a report's interpretation, a PDF's text layer, a note) also says how it's
printed. These keys don't reach any table; the silver load reads them (`webapi.orchestration.silver.extracted`):
```toml
[<estudio>.resultados.<resultado>]
etiquetas_fuente = ["Densidad mamaria", "Densidad"] # the captions it's printed under
buscar_en_texto = true # codigo only: also as a mention anywhere in the text
provisional = true # captions and spellings not yet confirmed with the hospital's documents
valores = [
{ valor = "C", etiqueta = "Heterogéneamente densa", alias = ["Tipo C", "ACR C"] }, # each spelling of the value
]
```
A spelling with no alias is stored as `valor_fuente` without `valor_id` and counted as out of catalog; adding it
as an alias and reloading turns it into the code. One spelling on two values of a result is rejected.
Los valores son los que llegan del hospital (los enums de Core). Las etiquetas y los colores de las figuras
siguen en `parametros.toml` del kit hasta F3; `indicadores_kit/tests/test_catalogos.py` exige que coincidan.
-145
View File
@@ -1,145 +0,0 @@
# Catálogo de CaCu (F1). Valores: los enums de Core (`core/cacu/*/enums.py`) y lo que guarda la carga.
[citologia]
etiqueta = "Citología cervical"
codigos_hospital = ["SOLICITUD_PAPANICOLAO_BASE_LIQUIDA", "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA"]
[citologia.resultados.calidad_muestra]
etiqueta = "Calidad de la muestra"
tipo_valor = "codigo"
valores = [
{ valor = "SATISFACTORIO", etiqueta = "Satisfactoria" },
{ valor = "INSATISFACTORIO", etiqueta = "Insatisfactoria" },
]
[citologia.resultados.bethesda]
etiqueta = "Células escamosas (Bethesda)"
tipo_valor = "codigo"
valores = [
{ valor = "NORMAL", etiqueta = "Normal" },
{ valor = "ASC-US", etiqueta = "ASC-US" },
{ valor = "LIEBG", etiqueta = "LIEBG" },
{ valor = "ASC-H", etiqueta = "ASC-H" },
{ valor = "LIEAG", etiqueta = "LIEAG" },
{ valor = "CIS", etiqueta = "Carcinoma in situ" },
]
[citologia.resultados.celulas_glandulares]
etiqueta = "Células glandulares"
tipo_valor = "texto"
[citologia.resultados.carcinoma_invasor]
etiqueta = "Carcinoma invasor"
tipo_valor = "texto"
[citologia.resultados.dx_lesion]
etiqueta = "Diagnóstico de la lesión"
tipo_valor = "texto"
[vph]
etiqueta = "Prueba de VPH"
[vph.resultados.resultado]
etiqueta = "VPH de alto riesgo"
tipo_valor = "codigo"
valores = [
{ valor = "NEGATIVO", etiqueta = "Negativo" },
{ valor = "POSITIVO", etiqueta = "Positivo" },
{ valor = "INDETERMINADO", etiqueta = "Indeterminado" },
]
[vph.resultados.genotipo_16_18]
etiqueta = "Genotipo 16 o 18"
tipo_valor = "booleano"
[vph.resultados.genotipo_16]
etiqueta = "Genotipo 16"
tipo_valor = "booleano"
[vph.resultados.genotipo_18]
etiqueta = "Genotipo 18"
tipo_valor = "booleano"
[biopsia]
etiqueta = "Biopsia cervical"
codigos_hospital = ["BIOPSIA_CHICA"]
[biopsia.resultados.grado]
etiqueta = "Grado histológico"
tipo_valor = "codigo"
valores = [
{ valor = "NORMAL", etiqueta = "Normal" },
{ valor = "LIEBG", etiqueta = "LIEBG (CIN 1)" },
{ valor = "LIEAG", etiqueta = "LIEAG (CIN 2 y 3)" },
{ valor = "CIS", etiqueta = "Carcinoma in situ" },
{ valor = "CARCINOMA", etiqueta = "Carcinoma invasor" },
{ valor = "DESCONOCIDO", etiqueta = "Desconocido" },
]
[biopsia.resultados.fecha_solicitud]
etiqueta = "Fecha de solicitud"
tipo_valor = "fecha"
[nota_medica]
etiqueta = "Nota médica"
[nota_medica.resultados.diagnostico]
etiqueta = "Diagnóstico"
tipo_valor = "externo"
sistema = "CIE-10"
# El motivo de consulta, tal como lo escribe el hospital (p. ej. «ACUDE A COLPOSCOPIA»). La plata no lo
# normaliza (I-K61): quien lo compare (el estatus de seguimiento, T-24c) lo normaliza con sus reglas.
[nota_medica.resultados.motivo]
etiqueta = "Motivo de consulta"
tipo_valor = "texto"
# El diagnóstico en texto, tal como lo escribe el hospital: la nota de colposcopia puede traer
# el CIE-10 como «S/C» y el diagnóstico solo aquí (p. ej. «VIRUS DEL PAPILOMA HUMANO»; usuario,
# 2026-10-22). Sin normalizar, como el motivo.
[nota_medica.resultados.diagnostico_texto]
etiqueta = "Diagnóstico (texto)"
tipo_valor = "texto"
[nota_medica.resultados.especialidad]
etiqueta = "Especialidad que la escribe"
tipo_valor = "codigo"
valores = [
{ valor = "MEDICINA_FAMILIAR", etiqueta = "Medicina familiar" },
{ valor = "CIRUGIA_ONCOLOGICA", etiqueta = "Cirugía oncológica" },
{ valor = "CLINICA_MUJER_COLPOSCOPIA", etiqueta = "Clínica de la mujer (colposcopia)" },
]
# Los datos de una orden (procedimiento con clase `orden`; su `estudio_id` es el estudio pedido, de
# `codigos_hospital`). ADR-MD-007.
[orden]
etiqueta = "Orden de estudio"
[orden.resultados.intencion]
etiqueta = "Intención (FHIR intent)"
tipo_valor = "texto"
[orden.resultados.fecha_solicitud]
etiqueta = "Fecha para la que se pidió"
tipo_valor = "fecha"
[orden.resultados.fecha_resultado]
etiqueta = "Fecha del resultado"
tipo_valor = "fecha"
[orden.resultados.estatus]
etiqueta = "Estatus de la orden"
tipo_valor = "texto"
[orden.resultados.diagnostico]
etiqueta = "Diagnóstico con que se pidió"
tipo_valor = "texto"
[orden.resultados.especialidad]
etiqueta = "Especialidad que la pidió"
tipo_valor = "codigo"
valores = [
{ valor = "MEDICINA_FAMILIAR", etiqueta = "Medicina familiar" },
{ valor = "CIRUGIA_ONCOLOGICA", etiqueta = "Cirugía oncológica" },
{ valor = "CLINICA_MUJER_COLPOSCOPIA", etiqueta = "Clínica de la mujer (colposcopia)" },
]
-219
View File
@@ -1,219 +0,0 @@
# Catálogo de CaMa (F1). Valores: los enums de Core (`core/cama/*/enums.py`) y lo que guarda la carga.
# BI-RADS: el hospital reporta 4A, 4B y 4C, normalizados (usuario, 2026-10-16); un 4 sin subcategoría
# también puede llegar (`cama.birads_gravedad` en parametros.toml).
[mastografia]
etiqueta = "Mastografía"
codigos_hospital = ["MASTOGRAFIA"]
[mastografia.resultados.calidad_imagen]
etiqueta = "Calidad de la imagen"
tipo_valor = "codigo"
valores = [
{ valor = "SATISFACTORIO", etiqueta = "Satisfactoria" },
{ valor = "INSATISFACTORIO", etiqueta = "Insatisfactoria" },
]
[mastografia.resultados.birads]
etiqueta = "BI-RADS"
tipo_valor = "codigo"
valores = [
{ valor = "B0", etiqueta = "BI-RADS 0" },
{ valor = "B1", etiqueta = "BI-RADS 1" },
{ valor = "B2", etiqueta = "BI-RADS 2" },
{ valor = "B3", etiqueta = "BI-RADS 3" },
{ valor = "B4", etiqueta = "BI-RADS 4 (sin subcategoría)" },
{ valor = "B4A", etiqueta = "BI-RADS 4A" },
{ valor = "B4B", etiqueta = "BI-RADS 4B" },
{ valor = "B4C", etiqueta = "BI-RADS 4C" },
{ valor = "B5", etiqueta = "BI-RADS 5" },
{ valor = "B6", etiqueta = "BI-RADS 6" },
]
# Read from the radiologist's interpretation (`mast_interpretacion`). Provisional: captions and spellings are
# assumptions until the hospital's reports are seen; adding one is a line in `etiquetas_fuente` or `alias`.
[mastografia.resultados.densidad]
etiqueta = "Densidad mamaria (ACR)"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Densidad mamaria", "Densidad", "Composición mamaria", "Patrón mamario"]
valores = [
{ valor = "A", etiqueta = "Predominantemente grasa", alias = ["Tipo A", "ACR A", "Categoría A", "(A)", "Grasa"] },
{ valor = "B", etiqueta = "Densidades fibroglandulares dispersas", alias = ["Tipo B", "ACR B", "Categoría B", "(B)", "Fibroglandular dispersa"] },
{ valor = "C", etiqueta = "Heterogéneamente densa", alias = ["Tipo C", "ACR C", "Categoría C", "(C)", "Heterogéneamente densas"] },
{ valor = "D", etiqueta = "Extremadamente densa", alias = ["Tipo D", "ACR D", "Categoría D", "(D)", "Extremadamente densas"] },
]
[mastografia.resultados.tamano_lesion_mm]
etiqueta = "Tamaño de la lesión"
tipo_valor = "numero"
unidad = "mm"
provisional = true
etiquetas_fuente = ["Tamaño de la lesión", "Tamaño del nódulo", "Diámetro mayor", "Mide"]
[biopsia]
etiqueta = "Biopsia de mama"
codigos_hospital = ["BIOPSIA_CHICA"]
[biopsia.resultados.grado]
etiqueta = "Grado histológico"
tipo_valor = "codigo"
valores = [
{ valor = "BENIGNO", etiqueta = "Benigno" },
{ valor = "CARCINOMA_IN_SITU", etiqueta = "Carcinoma in situ" },
{ valor = "CARCINOMA_INVASOR", etiqueta = "Carcinoma invasor" },
{ valor = "DESCONOCIDO", etiqueta = "Desconocido" },
]
[biopsia.resultados.fecha_solicitud]
etiqueta = "Fecha de solicitud"
tipo_valor = "fecha"
# Read from the pathology report's text layer (`bx_pdf_blob`). Provisional, as the mammography's.
[biopsia.resultados.tipo_histologico]
etiqueta = "Tipo histológico"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Tipo histológico", "Diagnóstico histopatológico", "Diagnóstico"]
buscar_en_texto = true
valores = [
{ valor = "DUCTAL_INFILTRANTE", etiqueta = "Carcinoma ductal infiltrante", alias = ["Ductal infiltrante", "Carcinoma ductal invasor", "Carcinoma infiltrante de tipo no especial", "CDI"] },
{ valor = "LOBULILLAR_INFILTRANTE", etiqueta = "Carcinoma lobulillar infiltrante", alias = ["Lobulillar infiltrante", "Carcinoma lobulillar invasor", "CLI"] },
{ valor = "DUCTAL_IN_SITU", etiqueta = "Carcinoma ductal in situ", alias = ["Ductal in situ", "CDIS"] },
{ valor = "OTRO", etiqueta = "Otro tipo histológico" },
]
[biopsia.resultados.grado_nottingham]
etiqueta = "Grado histológico (Nottingham)"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Grado histológico", "Grado de Nottingham", "Grado Scarff-Bloom-Richardson", "SBR"]
valores = [
{ valor = "G1", etiqueta = "Grado 1", alias = ["1", "I", "Grado I", "Bien diferenciado"] },
{ valor = "G2", etiqueta = "Grado 2", alias = ["2", "II", "Grado II", "Moderadamente diferenciado"] },
{ valor = "G3", etiqueta = "Grado 3", alias = ["3", "III", "Grado III", "Poco diferenciado"] },
]
[biopsia.resultados.receptor_estrogeno]
etiqueta = "Receptor de estrógeno"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Receptores de estrógeno", "Receptor de estrógenos", "Receptores estrogénicos", "RE", "ER"]
valores = [
{ valor = "POSITIVO", etiqueta = "Positivo", alias = ["Pos", "+"] },
{ valor = "NEGATIVO", etiqueta = "Negativo", alias = ["Neg", "-"] },
]
[biopsia.resultados.receptor_estrogeno_pct]
etiqueta = "Receptor de estrógeno, células teñidas"
tipo_valor = "numero"
unidad = "%"
provisional = true
etiquetas_fuente = ["Receptores de estrógeno", "Receptor de estrógenos", "Receptores estrogénicos", "RE", "ER"]
[biopsia.resultados.receptor_progesterona]
etiqueta = "Receptor de progesterona"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Receptores de progesterona", "Receptor de progesterona", "Receptores progestágenos", "RP", "PR"]
valores = [
{ valor = "POSITIVO", etiqueta = "Positivo", alias = ["Pos", "+"] },
{ valor = "NEGATIVO", etiqueta = "Negativo", alias = ["Neg", "-"] },
]
[biopsia.resultados.receptor_progesterona_pct]
etiqueta = "Receptor de progesterona, células teñidas"
tipo_valor = "numero"
unidad = "%"
provisional = true
etiquetas_fuente = ["Receptores de progesterona", "Receptor de progesterona", "Receptores progestágenos", "RP", "PR"]
# A bare "positivo" is left unmatched on purpose: it doesn't say whether it's 3+ or an amplified 2+.
[biopsia.resultados.her2]
etiqueta = "HER2 (inmunohistoquímica)"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["HER2", "HER-2", "HER2/neu", "C-erbB-2"]
valores = [
{ valor = "H0", etiqueta = "0", alias = ["0", "Negativo (0)", "Score 0"] },
{ valor = "H1", etiqueta = "1+", alias = ["1+", "Negativo (1+)", "Score 1+"] },
{ valor = "H2", etiqueta = "2+", alias = ["2+", "Equívoco", "Indeterminado", "Score 2+"] },
{ valor = "H3", etiqueta = "3+", alias = ["3+", "Positivo (3+)", "Score 3+"] },
]
[biopsia.resultados.ki67_pct]
etiqueta = "Ki-67"
tipo_valor = "numero"
unidad = "%"
provisional = true
etiquetas_fuente = ["Ki-67", "Ki67", "Índice de proliferación"]
[nota_medica]
etiqueta = "Nota médica"
[nota_medica.resultados.diagnostico]
etiqueta = "Diagnóstico"
tipo_valor = "externo"
sistema = "CIE-10"
# Read from the note's diagnosis and prognosis texts. Provisional; a stage mentioned without a caption counts too
# ("... estadio clínico IIA (T2N0M0)").
[nota_medica.resultados.estadio_clinico]
etiqueta = "Estadio clínico"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Estadio clínico", "Etapa clínica", "Estadio", "EC"]
buscar_en_texto = true
valores = [
{ valor = "E0", etiqueta = "Estadio 0", alias = ["EC 0", "Etapa 0", "In situ", "Estadio clínico 0", "Etapa clínica 0"] },
{ valor = "EI", etiqueta = "Estadio I", alias = ["I", "IA", "IB", "EC I", "EC IA", "EC IB", "Estadio IA", "Estadio IB", "Etapa I", "Estadio clínico I", "Etapa clínica I", "Estadio clínico IA", "Estadio clínico IB"] },
{ valor = "EIIA", etiqueta = "Estadio IIA", alias = ["IIA", "EC IIA", "Etapa IIA", "Estadio clínico IIA", "Etapa clínica IIA"] },
{ valor = "EIIB", etiqueta = "Estadio IIB", alias = ["IIB", "EC IIB", "Etapa IIB", "Estadio clínico IIB", "Etapa clínica IIB"] },
{ valor = "EIIIA", etiqueta = "Estadio IIIA", alias = ["IIIA", "EC IIIA", "Etapa IIIA", "Estadio clínico IIIA", "Etapa clínica IIIA"] },
{ valor = "EIIIB", etiqueta = "Estadio IIIB", alias = ["IIIB", "EC IIIB", "Etapa IIIB", "Estadio clínico IIIB", "Etapa clínica IIIB"] },
{ valor = "EIIIC", etiqueta = "Estadio IIIC", alias = ["IIIC", "EC IIIC", "Etapa IIIC", "Estadio clínico IIIC", "Etapa clínica IIIC"] },
{ valor = "EIV", etiqueta = "Estadio IV", alias = ["IV", "EC IV", "Etapa IV", "Metastásico", "Estadio clínico IV", "Etapa clínica IV"] },
]
[nota_medica.resultados.especialidad]
etiqueta = "Especialidad que la escribe"
tipo_valor = "codigo"
valores = [
{ valor = "MEDICINA_FAMILIAR", etiqueta = "Medicina familiar" },
{ valor = "CIRUGIA_ONCOLOGICA", etiqueta = "Cirugía oncológica" },
{ valor = "CLINICA_MUJER_COLPOSCOPIA", etiqueta = "Clínica de la mujer (colposcopia)" },
]
# Los datos de una orden (procedimiento con clase `orden`; su `estudio_id` es el estudio pedido, de
# `codigos_hospital`). ADR-MD-007.
[orden]
etiqueta = "Orden de estudio"
[orden.resultados.intencion]
etiqueta = "Intención (FHIR intent)"
tipo_valor = "texto"
[orden.resultados.fecha_solicitud]
etiqueta = "Fecha para la que se pidió"
tipo_valor = "fecha"
[orden.resultados.fecha_resultado]
etiqueta = "Fecha del resultado"
tipo_valor = "fecha"
[orden.resultados.estatus]
etiqueta = "Estatus de la orden"
tipo_valor = "texto"
[orden.resultados.diagnostico]
etiqueta = "Diagnóstico con que se pidió"
tipo_valor = "texto"
[orden.resultados.especialidad]
etiqueta = "Especialidad que la pidió"
tipo_valor = "codigo"
valores = [
{ valor = "MEDICINA_FAMILIAR", etiqueta = "Medicina familiar" },
{ valor = "CIRUGIA_ONCOLOGICA", etiqueta = "Cirugía oncológica" },
{ valor = "CLINICA_MUJER_COLPOSCOPIA", etiqueta = "Clínica de la mujer (colposcopia)" },
]
-276
View File
@@ -1,276 +0,0 @@
# TEA's catalog: the studies of the screening (M-CHAT, ADOS-2, neuropediatrics note, EEG) and their results.
# Values are Core's enums (`core/tea/enums.py`). `codigos_hospital` are the codes of `ord_tipo_estudio`: an order's
# `estudio_id` is the study it asks for.
[mchat]
etiqueta = "M-CHAT-R/F"
[mchat.resultados.puntaje]
etiqueta = "Puntaje total"
tipo_valor = "numero"
unidad = "puntos"
# The ADOS-2: module, algorithm, classification, CSS and the algorithm items. An item's domain is its prefix:
# `sa_` social affect, `rrb_` restricted and repetitive behaviour. Labels of the items without a published short name
# wait for the hospital's manuals.
[ados2]
etiqueta = "Evaluación psicológica (ADOS-2)"
codigos_hospital = ["ADOS2"]
[ados2.resultados.modulo]
etiqueta = "Módulo"
tipo_valor = "codigo"
valores = [
{ valor = "TODDLER", etiqueta = "Módulo T (niños pequeños)" },
{ valor = "MODULO_1", etiqueta = "Módulo 1" },
{ valor = "MODULO_2", etiqueta = "Módulo 2" },
{ valor = "MODULO_3", etiqueta = "Módulo 3" },
]
[ados2.resultados.algoritmo]
etiqueta = "Algoritmo"
tipo_valor = "texto"
[ados2.resultados.clasificacion]
etiqueta = "Clasificación"
tipo_valor = "codigo"
valores = [
{ valor = "NO_ESPECTRO", etiqueta = "No espectro" },
{ valor = "ESPECTRO_AUTISTA", etiqueta = "Espectro autista" },
{ valor = "AUTISMO", etiqueta = "Autismo" },
{ valor = "PREOCUPACION_LEVE_MODERADA", etiqueta = "Preocupación leve a moderada" },
{ valor = "PREOCUPACION_SEVERA", etiqueta = "Preocupación moderada a severa" },
]
[ados2.resultados.css]
etiqueta = "Puntaje de severidad (CSS)"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_a2]
etiqueta = "Frecuencia de la vocalización espontánea dirigida a otros"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_a6]
etiqueta = "Uso del cuerpo de otra persona para comunicarse"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_a7]
etiqueta = "Señalar"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_a8]
etiqueta = "Gestos"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b1]
etiqueta = "Contacto visual inusual"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b2]
etiqueta = "Sonrisa social en respuesta"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b3]
etiqueta = "Expresiones faciales dirigidas a otros"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b4]
etiqueta = "Integración de la mirada y otras conductas en las iniciaciones sociales"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b5]
etiqueta = "Placer compartido durante la interacción"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b6]
etiqueta = "Respuesta al nombre"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b7]
etiqueta = "Pedir"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b8]
etiqueta = "Dar"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b9]
etiqueta = "Mostrar"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b10]
etiqueta = "Iniciación espontánea de la atención conjunta"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b11]
etiqueta = "Respuesta a la atención conjunta"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b12]
etiqueta = "Calidad de los acercamientos sociales"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b13]
etiqueta = "Reactivo B13"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b14]
etiqueta = "Reactivo B14"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b15]
etiqueta = "Reactivo B15"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b16b]
etiqueta = "Reactivo B16b"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b18]
etiqueta = "Reactivo B18"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.rrb_a3]
etiqueta = "Entonación de las vocalizaciones o verbalizaciones"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.rrb_a4]
etiqueta = "Ecolalia inmediata"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.rrb_a5]
etiqueta = "Uso estereotipado o idiosincrásico de palabras o frases"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.rrb_d1]
etiqueta = "Interés sensorial inusual en los materiales de juego o en las personas"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.rrb_d2]
etiqueta = "Manierismos de manos, dedos y otros manierismos complejos"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.rrb_d4]
etiqueta = "Intereses inusualmente repetitivos o conductas estereotipadas"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.rrb_d5]
etiqueta = "Reactivo D5"
tipo_valor = "numero"
unidad = "puntos"
[evaluacion_neuropediatrica]
etiqueta = "Evaluación neuropediátrica"
codigos_hospital = ["NEUROPEDIATRIA"]
[evaluacion_neuropediatrica.resultados.diagnostico]
etiqueta = "Diagnóstico"
tipo_valor = "externo"
sistema = "CIE-10"
# The EEG: what its analysis writes. On the recording (`toma`), the sleep, channels, duration, the five quality
# criteria and each metric's measured value; on each electrode (`parte`, `codigo_fuente` the electrode), the metric's
# z-score there, under the same result.
[eeg]
etiqueta = "Electroencefalograma"
codigos_hospital = ["EEG"]
[eeg.resultados.con_sueno]
etiqueta = "Registro con sueño"
tipo_valor = "booleano"
[eeg.resultados.canales]
etiqueta = "Canales"
tipo_valor = "numero"
unidad = "canales"
[eeg.resultados.duracion_min]
etiqueta = "Duración del registro"
tipo_valor = "numero"
unidad = "min"
[eeg.resultados.calidad_amplitud]
etiqueta = "Canales con amplitud extrema"
tipo_valor = "numero"
unidad = "canales"
[eeg.resultados.calidad_alta_frecuencia]
etiqueta = "Ruido de alta frecuencia"
tipo_valor = "numero"
unidad = "canales"
[eeg.resultados.calidad_correlacion]
etiqueta = "Baja correlación entre canales"
tipo_valor = "numero"
unidad = "canales"
[eeg.resultados.calidad_sin_senal]
etiqueta = "Canales planos o sin señal"
tipo_valor = "numero"
unidad = "canales"
[eeg.resultados.calidad_linea]
etiqueta = "Ruido de la línea eléctrica"
tipo_valor = "numero"
unidad = "dB"
[eeg.resultados.ritmo_posterior]
etiqueta = "Ritmo posterior"
tipo_valor = "numero"
unidad = "Hz"
[eeg.resultados.husos_sueno_n2]
etiqueta = "Husos de sueño N2"
tipo_valor = "numero"
unidad = "husos/min"
[eeg.resultados.husos_sueno_n3]
etiqueta = "Husos de sueño N3"
tipo_valor = "numero"
unidad = "husos/min"
[eeg.resultados.picos_paroxisticos]
etiqueta = "Picos paroxísticos"
tipo_valor = "numero"
unidad = "picos/min"
[eeg.resultados.gradiente_anteroposterior]
etiqueta = "Gradiente anteroposterior"
tipo_valor = "numero"
unidad = "razón posterior/anterior"
# An order (procedure of class `orden`): its `estudio_id` is the study it asks for, from `codigos_hospital`.
[orden]
etiqueta = "Orden de estudio"
[orden.resultados.intencion]
etiqueta = "Intención (FHIR intent)"
tipo_valor = "texto"
-12
View File
@@ -1,12 +0,0 @@
"""Column types and sizes shared across domains, so the storage schema and
the import validation in WebApi use the same limits."""
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# Hospital patient identifiers are indexed in CaCu/CaMa, and MySQL can't
# index an unbounded TEXT column (error 1170), so they are a bounded VARCHAR.
HOSPITAL_ID_LENGTH = 64
# Stored files (PDF reports, DICOM, EDF). Plain LargeBinary is a 64 KB BLOB
# on MySQL/MariaDB; LONGBLOB holds up to 4 GB.
FileBlob = sa.LargeBinary().with_variant(mysql.LONGBLOB(), "mysql", "mariadb")
+88
View File
@@ -0,0 +1,88 @@
"""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
@@ -0,0 +1,30 @@
"""The platform's domains. A domain is a package `core.<domain>` holding its parameters
(`__init__`: what dbt reads through `dbt_vars()`), and when it has them, its measures
(`measures.MEASURES`) and its follow-up list (`follow_up`)."""
import importlib
from enum import StrEnum
from types import ModuleType
class Domain(StrEnum):
CACU = "cacu"
CAMA = "cama"
TEA = "tea"
def part(domain: Domain, name: str = "") -> ModuleType | None:
"""The domain's module `name` (its package without one), or None while it has none."""
path = f"core.{domain.value}" + (f".{name}" if name else "")
try:
return importlib.import_module(path)
except ModuleNotFoundError as e:
if e.name is not None and path.startswith(e.name):
return None
raise
def measures(domain: Domain) -> dict:
"""The domain's measures by id (none for a domain without them yet)."""
found = part(domain, "measures")
return found.MEASURES if found else {}
+470
View File
@@ -0,0 +1,470 @@
"""Platform rows as FHIR R4B resources (pure, no IO), and the conformance resources that
declare what ours are: the local code systems, our extensions and our search parameters.
Every mapper builds a `fhir.resources.R4B` model, so a resource that breaks FHIR's structure
fails here, before it is served. Clinical resources other than Patient are found by search
only; their ids are stable (a UUID of their natural key), not addresses.
"""
import uuid
from collections.abc import Iterable
from datetime import UTC, date, datetime
from fhir.resources.R4B.codesystem import CodeSystem
from fhir.resources.R4B.condition import Condition
from fhir.resources.R4B.diagnosticreport import DiagnosticReport
from fhir.resources.R4B.encounter import Encounter
from fhir.resources.R4B.measure import Measure
from fhir.resources.R4B.observation import Observation
from fhir.resources.R4B.patient import Patient
from fhir.resources.R4B.procedure import Procedure
from fhir.resources.R4B.resource import Resource
from fhir.resources.R4B.riskassessment import RiskAssessment
from fhir.resources.R4B.searchparameter import SearchParameter
from fhir.resources.R4B.structuredefinition import StructureDefinition
from core import catalog
FHIR_VERSION = "4.3.0"
BASE = "https://isssteleon.org/fhir"
EXTENSION = f"{BASE}/StructureDefinition/"
CODES = f"{BASE}/CodeSystem/"
ICD10 = "http://hl7.org/fhir/sid/icd-10"
UCUM = "http://unitsofmeasure.org"
_IDS = uuid.uuid5(uuid.NAMESPACE_URL, BASE)
# Local code systems: code -> display (Spanish, as the screens show them).
CODE_SYSTEMS: dict[str, tuple[str, dict[str, str]]] = {
"cacu-procedure": ("Procedimientos de CaCu", {
"colposcopy": "Colposcopia", "treatment": "Tratamiento",
}),
"cacu-follow-up-status": ("Estatus de seguimiento", {
"case": "Caso (cáncer)", "pre_colposcopy": "Pre colposcopia",
"post_colposcopy": "Post colposcopia", "post_treatment": "Post tratamiento",
}),
"cama-follow-up-status": ("Estatus de seguimiento", {
"cancer": "Diagnóstico confirmado", "pending_biopsy": "Pendiente de biopsia",
"biopsy_no_result": "Biopsia sin resultado", "benign_biopsy": "Biopsia benigna",
}),
"follow-up-priority": ("Prioridad de seguimiento", {
"high": "Alta", "medium": "Media", "low": "Baja",
}),
"measure-stratifier": ("Estratos de indicadores", {
"category": "Categoría", "age_group": "Grupo de edad",
"follow_up_status": "Estatus de seguimiento", "result": "Citología de alto grado",
"diagnosis_code": "Diagnóstico CIE-10",
"birads": "BI-RADS de la mastografía",
"referral_cytology": "Citología previa", "histology_level": "Histología",
"screening_round": "Tamizaje inicial o subsecuente",
"result_initial": "Resultado en tamizaje inicial",
"result_subsequent": "Resultado en tamizaje subsecuente",
"referral_hpv": "VPH de la citología previa", "hpv_16": "VPH 16", "hpv_18": "VPH 18",
"hpv_initial": "VPH en tamizaje inicial",
"hpv_subsequent": "VPH en tamizaje subsecuente",
}),
"risk-model": ("Modelos de riesgo", {}), # open: a model's name is its code
} # fmt: skip
def _catalog_systems() -> dict[str, tuple[str, dict[str, str]]]:
"""The catalog's own code systems, with every code some field allows."""
found: dict[str, tuple[str, dict[str, str]]] = {}
for name, system in catalog.systems().items():
if not system.external:
codes = {c: d for s in catalog.studies().values() for f in s.fields.values()
if f.system == name for c, d in f.codes.items()} # fmt: skip
found[name] = (system.title, codes)
return found
CODE_SYSTEMS |= _catalog_systems()
# What the catalog names: its studies, and every field as `<study>.<field>`.
CODE_SYSTEMS["study"] = ("Estudios", {n: s.title for n, s in catalog.studies().items()})
CODE_SYSTEMS["catalog-field"] = ("Campos de los estudios", {
f"{n}.{f}": d.title for n, s in catalog.studies().items() for f, d in s.fields.items()
}) # fmt: skip
# Our extensions: name -> (value type, the elements they extend).
EXTENSIONS: dict[str, tuple[str, list[str]]] = {
"ic-bajo": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
"ic-alto": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
"q1": ("decimal", ["MeasureReport.group.measureScore"]),
"q3": ("decimal", ["MeasureReport.group.measureScore"]),
"corte-conocimiento": ("dateTime", ["MeasureReport"]),
"period-type": ("code", ["Measure"]),
"follow-up-status": ("Coding", ["Patient"]),
"follow-up-priority": ("Coding", ["Patient"]),
"report-date": ("date", ["DiagnosticReport"]),
"days-to-diagnosis": ("integer", ["DiagnosticReport"]),
"stage-colposcopy-state": ("code", ["DiagnosticReport"]),
"stage-colposcopy-date": ("date", ["DiagnosticReport"]),
"stage-biopsy-state": ("code", ["DiagnosticReport"]),
"stage-biopsy-date": ("date", ["DiagnosticReport"]),
"stage-diagnosis-state": ("code", ["DiagnosticReport"]),
"stage-diagnosis-date": ("date", ["DiagnosticReport"]),
} # fmt: skip
def _name(code: str) -> str:
"""A conformance resource's computable name (CamelCase)."""
return "".join(part.capitalize() for part in code.replace("_", "-").split("-"))
def _id(*key) -> str:
return str(uuid.uuid5(_IDS, "|".join(str(k) for k in key)))
def _day(value) -> str | None:
if value is None:
return None
return value.isoformat()[:10] if isinstance(value, date) else str(value)[:10]
def _instant(value) -> str | None:
"""A stored moment as an instant; one stored without an offset is UTC."""
if value is None:
return None
found = value if isinstance(value, datetime) else datetime.fromisoformat(str(value))
return (found if found.tzinfo else found.replace(tzinfo=UTC)).isoformat()
def coding(system: str, code: str) -> dict:
display = CODE_SYSTEMS[system][1].get(code) if system in CODE_SYSTEMS else None
return {"system": CODES + system, "code": code, **({"display": display} if display else {})}
def concept(system: str, code: str) -> dict:
found = coding(system, code)
return {"coding": [found], "text": found.get("display", code)}
def ext(name: str, value_type: str, value) -> dict:
return {"url": EXTENSION + name, f"value{value_type[0].upper()}{value_type[1:]}": value}
def subject(person_id: str) -> dict:
return {"reference": f"Patient/{person_id}"}
# --- clinical resources ----------------------------------------------------------------
def patient(row: dict, status_system: str | None = None) -> Patient:
"""A person: what her records agree on, her names and identifiers, the ids she
replaced; on a follow-up list, her status there (`status_system`) and priority."""
found: dict = {"resourceType": "Patient", "id": row["person_id"]}
if row.get("sex"):
found["gender"] = row["sex"]
if row.get("birth_date"):
found["birthDate"] = _day(row["birth_date"])
if row.get("death_date"):
found["deceasedDateTime"] = _day(row["death_date"])
if row.get("status") and status_system:
found["extension"] = [ext("follow-up-status", "Coding",
coding(status_system, row["status"]))] # fmt: skip
if row.get("priority"):
priority = coding("follow-up-priority", row["priority"])
found["extension"].append(ext("follow-up-priority", "Coding", priority))
if row.get("names"):
found["name"] = [{"text": n} for n in row["names"]]
if row.get("identifiers"):
found["identifier"] = [{"system": s, "value": v} for s, v in row["identifiers"]]
if row.get("replaces"):
found["link"] = [{"other": {"reference": f"Patient/{old}"}, "type": "replaces"}
for old in row["replaces"]] # fmt: skip
return Patient.model_validate(found)
def replaced_patient(person_id: str, replaced_by: str) -> Patient:
"""A person a review merged into another: no longer active, pointing at who replaced
her, so her id keeps resolving."""
return Patient.model_validate({
"resourceType": "Patient", "id": person_id, "active": False,
"link": [{"other": {"reference": f"Patient/{replaced_by}"}, "type": "replaced-by"}],
}) # fmt: skip
def _value(f: catalog.FieldDef, value) -> dict:
"""A field's value as the Observation value of its type."""
if f.type == "code":
system = catalog.systems()[f.system]
if system.external:
return {"valueCodeableConcept": {"coding": [{"system": system.url, "code": value}],
"text": value}} # fmt: skip
return {"valueCodeableConcept": concept(f.system, value)}
if f.type == "boolean":
return {"valueBoolean": bool(value)}
if f.type == "number":
return {"valueQuantity": {"value": value, **({"unit": f.unit} if f.unit else {})}}
if f.type == "date":
return {"valueDateTime": _day(value)}
return {"valueString": str(value)}
def known(study: str, row: dict, cutoff) -> dict:
"""A study instance as the platform knew it by the end of `cutoff`: the fields of an
event that has no date yet, or a later one, are not known."""
spec = catalog.studies()[study]
out = dict(row)
for cls, event in spec.events.items():
day = _day(row.get(event.date))
if event.parent is not None and (day is None or day > _day(cutoff)):
for name, f in spec.fields.items():
if f.event == cls:
out[name] = None
return out
def instance(study: str, row: dict, report_extensions: Iterable[dict] = ()) -> list[Resource]:
"""One study instance (a row of `silver.<study>`) as FHIR, from the catalog: an
Observation per field that is not an event's date, and, when the study has a report,
the DiagnosticReport that gathers them."""
spec = catalog.studies()[study]
person = row["person_id"]
key = [_day(row[k]) if spec.fields[k].type == "date" else row[k] for k in spec.key]
dates = {e.date for e in spec.events.values()}
root = next(e for e in spec.events.values() if e.parent is None)
effective = _day(row.get(root.date))
container = _id(study, person, *key) # its report, or the encounter its notes are of
visit = "report" not in spec.events
observations = []
for name, f in spec.fields.items():
if name in dates or row.get(name) is None or f.type == "file":
continue
observations.append(Observation.model_validate({
"resourceType": "Observation",
"id": _id(study, name, person, *key),
"status": "final",
"code": concept("catalog-field", f"{study}.{name}"),
"subject": subject(person),
**({"encounter": {"reference": f"Encounter/{container}"}} if visit else {}),
**({"effectiveDateTime": effective} if effective else {}),
**_value(f, row[name]),
})) # fmt: skip
if visit: # a study without a report (a consultation): the encounter its values are of
if not observations:
return []
encounter = Encounter.model_validate({
"resourceType": "Encounter", "id": container, "status": "finished",
"class": {"system": "http://terminology.hl7.org/CodeSystem/v3-ActCode",
"code": "AMB"},
"type": [concept("study", study)],
"subject": subject(person),
**({"period": {"start": effective}} if effective else {}),
}) # fmt: skip
return [encounter, *observations]
reported = _day(row.get(spec.events["report"].date))
extensions = ([ext("report-date", "date", reported)] if reported else []) + list(
report_extensions
)
report = DiagnosticReport.model_validate({
"resourceType": "DiagnosticReport",
"id": container,
"status": "final" if reported else "registered",
"code": concept("study", study),
"subject": subject(person),
**({"effectiveDateTime": effective} if effective else {}),
**({"extension": extensions} if extensions else {}),
"result": [{"reference": f"Observation/{o.id}"} for o in observations] or None,
}) # fmt: skip
return [report, *observations]
def condition(row: dict) -> Condition:
"""What a clinical note diagnosed (`silver.clinical_note`), by ICD-10 or as written."""
person, day = row["person_id"], _day(row["note_date"])
code: dict = {"text": row.get("diagnosis_text") or row.get("icd10")}
if row.get("icd10"):
code["coding"] = [{"system": ICD10, "code": row["icd10"]}]
found: dict = {
"resourceType": "Condition",
"id": _id("condition", person, day, row.get("specialty")),
"category": [{"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/condition-category",
"code": "encounter-diagnosis"}]}],
"code": code,
"subject": subject(person),
"recordedDate": day,
} # fmt: skip
if row.get("reason"):
found["note"] = [{"text": row["reason"]}]
return Condition.model_validate(found)
def procedure(row: dict) -> Procedure:
"""A procedure the timeline inferred (`gold.cacu_events`: colposcopy, treatment)."""
person, day = row["person_id"], _day(row["date"])
return Procedure.model_validate({
"resourceType": "Procedure",
"id": _id("procedure", row["type"], person, day),
"status": "completed",
"code": concept("cacu-procedure", row["type"]),
"subject": subject(person),
"performedDateTime": day,
}) # fmt: skip
def risk_assessment(row: dict, horizons: Iterable[dict]) -> RiskAssessment:
"""A model's risk for one person at her index date (`gold.cacu_risk`): one prediction
per horizon, in years, with its 95% interval."""
predictions = []
for h in sorted(horizons, key=lambda h: h["horizon_years"]):
bounds = (("ic-bajo", "ci_low"), ("ic-alto", "ci_high"))
interval = [ext(name, "decimal", h[key]) for name, key in bounds
if h.get(key) is not None] # fmt: skip
predictions.append({
"probabilityDecimal": h["probability"],
"whenRange": {"high": {"value": h["horizon_years"], "unit": "a", "system": UCUM,
"code": "a"}},
**({"extension": interval} if interval else {}),
}) # fmt: skip
model = row["model"]
return RiskAssessment.model_validate({
"resourceType": "RiskAssessment",
"id": _id("risk", model, row["version"], row["person_id"], _day(row["index_date"])),
"meta": {"lastUpdated": _instant(row["scored_at"])},
"status": "final",
"method": {"coding": [{"system": CODES + "risk-model", "code": model}],
"text": f"{model} v{row['version']}"},
"subject": subject(row["person_id"]),
"occurrenceDateTime": _day(row["index_date"]),
"prediction": predictions,
}) # fmt: skip
SCORING = {"proportion": "proportion", "continuous-variable": "continuous-variable",
"composition": "cohort"} # fmt: skip
def measure_id(code: str) -> str:
"""A measure's FHIR id (ids allow no underscore)."""
return code.lower().replace("_", "-")
def measure_url(code: str) -> str:
return f"{BASE}/Measure/{code}"
# The populations each kind of measure counts (core.measures emits exactly these).
POPULATIONS = {"proportion": ["initial-population", "denominator", "numerator"],
"continuous-variable": ["initial-population", "measure-observation"],
"composition": ["initial-population", "measure-observation"]} # fmt: skip
POPULATION = "http://terminology.hl7.org/CodeSystem/measure-population"
def stratifiers(m) -> list[str]:
"""A measure's strata: a composition's categories first, then its declared strata."""
first = ["category"] if m.rule.kind == "composition" else []
return first + [name for name, _ in getattr(m.rule, "strata", ())]
def stratifier_code(name: str) -> dict:
return concept("measure-stratifier", name)
def measure(m, domain: str) -> Measure:
"""A measure definition (`core.measures.Measure`): how it is computed is Core's code,
which `criteria` points to."""
criteria = {"language": "text/x-python",
"expression": f"core.{domain}.measures.MEASURES['{m.id}']"} # fmt: skip
group: dict = {
"id": m.group,
"population": [{"code": {"coding": [{"system": POPULATION, "code": c}]},
"criteria": criteria} for c in POPULATIONS[m.rule.kind]],
} # fmt: skip
if strata := stratifiers(m):
group["stratifier"] = [{"id": s, "code": stratifier_code(s), "criteria": criteria}
for s in strata] # fmt: skip
found: dict = {
"resourceType": "Measure",
"id": measure_id(m.id),
"url": measure_url(m.id),
"version": m.version,
"name": m.id,
"title": m.title,
"status": "active",
"scoring": {"coding": [{"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": SCORING[m.rule.kind]}]},
"extension": [ext("period-type", "code", p) for p in m.periods],
"group": [group],
} # fmt: skip
if m.improvement:
found["improvementNotation"] = {"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": m.improvement}]} # fmt: skip
if m.description:
found["description"] = m.description
return Measure.model_validate(found)
# --- conformance: what our resources declare ---------------------------------------------
def code_systems() -> list[CodeSystem]:
return [CodeSystem.model_validate({
"resourceType": "CodeSystem", "id": name, "url": CODES + name,
"name": _name(name),
"title": title, "status": "active", "caseSensitive": True,
"content": "complete" if concepts else "not-present",
"concept": [{"code": c, "display": d} for c, d in concepts.items()],
}) for name, (title, concepts) in CODE_SYSTEMS.items()] # fmt: skip
def extensions() -> list[StructureDefinition]:
found = []
for name, (value_type, contexts) in EXTENSIONS.items():
url = EXTENSION + name
found.append(StructureDefinition.model_validate({
"resourceType": "StructureDefinition", "id": name, "url": url,
"name": _name(name), "status": "active", "fhirVersion": FHIR_VERSION,
"kind": "complex-type", "abstract": False, "type": "Extension",
"context": [{"type": "element", "expression": c} for c in contexts],
"baseDefinition": "http://hl7.org/fhir/StructureDefinition/Extension",
"derivation": "constraint",
"differential": {"element": [
{"id": "Extension", "path": "Extension", "max": "*" if name == "period-type"
else "1"},
{"id": "Extension.extension", "path": "Extension.extension", "max": "0"},
{"id": "Extension.url", "path": "Extension.url", "fixedUri": url},
{"id": "Extension.value[x]", "path": "Extension.value[x]", "min": 1,
"type": [{"code": value_type}]},
]},
})) # fmt: skip
return found
# Our search parameters: code -> (resource, type, description).
SEARCH_PARAMETERS: dict[str, tuple[str, str, str]] = {
"stage-cutoff": ("DiagnosticReport", "date", "Cutoff for sample-linked stages"),
"follow-up-age-min": ("Patient", "number", "Minimum completed age at the cutoff"),
"follow-up-age-max": ("Patient", "number", "Maximum completed age at the cutoff"),
"follow-up-search": ("Patient", "string", "Partial name or identifier"),
"follow-up-status": ("Patient", "token", "Follow-up status at the cut-off"),
"follow-up-cutoff": ("Patient", "date", "The day the follow-up list is taken at"),
"follow-up-window": ("Patient", "number",
"Months before the cut-off a cytology puts a patient on the list"),
"recent": ("Patient", "date", "Her latest cytology in the window (sort only)"),
"risk-cin2": ("Patient", "number", "Her current CIN2+ risk (sort only)"),
"risk-cancer": ("Patient", "number", "Her current cancer risk (sort only)"),
"risk-horizon": ("Patient", "number", "The horizon, in years, risks are sorted at"),
"reporting-period": ("MeasureReport", "token",
"A semester (2025-S1) or a month (2025-03) the report covers"),
"as-of": ("MeasureReport", "date", "Count only what the platform knew by then"),
"event-cutoff": ("MeasureReport", "date", "Durations count to this day"),
} # fmt: skip
def search_parameters() -> list[SearchParameter]:
return [SearchParameter.model_validate({
"resourceType": "SearchParameter", "id": code,
"url": f"{BASE}/SearchParameter/{code}", "name": _name(code),
"status": "active", "description": description, "code": code, "base": [base],
"type": kind,
}) for code, (base, kind, description) in SEARCH_PARAMETERS.items()] # fmt: skip
def conformance() -> list[Resource]:
"""Everything our resources declare: what the validator loads, and what the
CapabilityStatement points to."""
return [*code_systems(), *extensions(), *search_parameters()]
+157
View File
@@ -0,0 +1,157 @@
"""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
@@ -0,0 +1,26 @@
"""What every domain's follow-up list shares (pure). A domain with a list has a module
`core.<domain>.follow_up` with:
- `WINDOWS`: the windows (months) the list can be asked for; `SORTS` and `DEFAULT_HORIZON`
(years, for orders by risk; None without one);
- `STATUS_SYSTEM`: the code system of a patient's status on the list;
- `listed(rows, start, cutoff)`: who is on the list in reading order (most recent first),
each with her `status` (and `priority`, when the domain ranks them), from the rows of its
`follow_up` read (persistance.fhir);
- `status(row, cutoff)`: a person's status at the cut-off from her person row, or None;
- `ordered(rows, sort, risks, horizon)`: the list in another sort;
- `PROCEDURES`: the timeline's inferred procedures served as FHIR Procedures;
- `REPORT_FACTS`: facts gold adds to a study's report, by study.
"""
import calendar
from datetime import date
def window_start(cutoff: date, months: int) -> date:
"""The first day of the window: `months` before the cut-off (the month's last day when
shorter), plus one day."""
total = cutoff.year * 12 + cutoff.month - 1 - months
year, month = divmod(total, 12)
day = min(cutoff.day, calendar.monthrange(year, month + 1)[1])
return date.fromordinal(date(year, month + 1, day).toordinal() + 1)
View File
-16
View File
@@ -1,16 +0,0 @@
import sqlalchemy.orm as orm
from sqlmodel import SQLModel
registry = orm.registry()
class GovernanceModel(SQLModel, registry=registry):
"""Base class for the governance domain: the OCR extraction log and stored
predictions (VAR, EL and MLD requirements). Model versions and artifacts
live in MLflow; cohorts for models are the indicator kit's builds
(`cohorte_armado`) in each domain's database.
Governance is its own database. Rows refer to CaCu/CaMa/TEA patients and
episodes by natural key (`pac_id_hospital`, `episodio_id`) because foreign
keys can't cross databases.
"""
-28
View File
@@ -1,28 +0,0 @@
from enum import Enum
class Environment(str, Enum):
"""ML-02: development versions are tagged separately from production."""
DEV = "DEV"
PROD = "PROD"
class ArtifactKind(str, Enum):
"""ML-01a: kinds of artifacts saved from the routines around training,
in addition to the final model."""
MUESTREO = "MUESTREO"
DATOS_FALTANTES = "DATOS_FALTANTES"
METODO_ANALITICO = "METODO_ANALITICO"
BALANCE_CLASES = "BALANCE_CLASES"
CONFIANZA_SALIDA = "CONFIANZA_SALIDA"
OTRO = "OTRO"
class EstatusExtraccion(str, Enum):
"""VAR-07/VAR-09: status of an extraction run."""
EN_PROGRESO = "EN_PROGRESO"
COMPLETADA = "COMPLETADA"
FALLIDA = "FALLIDA"
@@ -1,70 +0,0 @@
from datetime import datetime, timezone
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.governance.base import GovernanceModel
class ExtractionRun(GovernanceModel, table=True):
"""VAR-07/VAR-08/VAR-09: log of each extraction run (OCR or other).
Records the data source and date range (VAR-08), the transformation and
quality check applied (VAR-07), and serves as an idempotency log (VAR-09):
callers check for a `COMPLETADA` run on the same `(domain, entity,
entity_pk)` before extracting again. The extracted value itself lives in
the source row's `*_ocr_*` columns.
"""
extraction_run_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
domain: str = Field(
sa_column=sa.Column(sa.String(16), nullable=False, index=True),
description="cacu | cama | tea",
)
entity: str = Field(
sa_column=sa.Column(sa.String(64), nullable=False, index=True),
description="nombre de la tabla/entidad de Core sobre la que corrió la extracción",
)
entity_pk: str = Field(
sa_column=sa.Column(sa.String(64), nullable=False, index=True),
description="valor de la llave primaria de la fila extraída, como texto",
)
column_extracted: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="columna destino que esta corrida pobló (p.ej. cit_vph_resultado)",
)
source_description: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="VAR-08: fuente de los datos crudos",
)
source_started_at: Optional[datetime] = Field(
default=None,
sa_column=sa.Column(sa.DateTime),
description="VAR-08: inicio del periodo que cubren los datos crudos cargados",
)
source_ended_at: Optional[datetime] = Field(
default=None,
sa_column=sa.Column(sa.DateTime),
)
transform_description: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="VAR-07: descripción de la transformación de datos crudos aplicada",
)
quality_validation: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="VAR-07: resultado de la validación de calidad de los datos, texto libre o JSON serializado",
)
estatus: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="valor de core.governance.enums.EstatusExtraccion guardado como texto",
)
executed_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_column=sa.Column(sa.DateTime, nullable=False),
)
@@ -1,83 +0,0 @@
from datetime import datetime, timezone
from typing import Optional
import sqlalchemy as sa
from core.columns import HOSPITAL_ID_LENGTH
from sqlmodel import Field
from core.governance.base import GovernanceModel
class ModelPrediction(GovernanceModel, table=True):
"""MLD-4/MLD-5: a persisted prediction, linked to the MLflow model
version that produced it.
Model training, versioning and promotion live in MLflow, not here
(`models.io.registry`); this row only carries the keys to find that version
again (`mlflow_run_id`, `modelo_nombre`, `modelo_version`), the same
reference-only pattern `core.indicadores.cohortes.EvaluacionRiesgoLoteBase`
already uses for its own risk evaluations.
`interpretability` stores the MLD-03 fields (OR, HR, cumulative
probability) with the estimate. `applicability_passed` is False when the
input failed the EL-04b applicability check; the prediction is kept for
traceability but should not be used clinically.
"""
model_prediction_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
mlflow_run_id: str = Field(
sa_column=sa.Column(sa.String(64), nullable=False, index=True),
description="la corrida de MLflow que entrenó el modelo",
)
modelo_nombre: str = Field(
sa_column=sa.Column(sa.String(128), nullable=False, index=True),
description="nombre del modelo registrado en MLflow",
)
modelo_version: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="versión del modelo registrado en MLflow",
)
domain: str = Field(
sa_column=sa.Column(sa.String(16), nullable=False, index=True),
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
)
episodio_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
input_hash: str = Field(
sa_column=sa.Column(sa.String(128), nullable=False, index=True),
description="sha256 del vector de entrada, para detectar predicciones duplicadas",
)
output: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="JSON serializado: salida cruda del modelo",
)
prediccion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="etiqueta/puntaje principal, en texto, para filtrar sin deserializar `output`",
)
confianza: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
description="0..1, nivel de confianza casuístico de esta estimación (MLD-01)",
)
interpretability: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description='JSON serializado (MLD-03): {"odds_ratio":, "hazard_ratio":, "probabilidad_acumulada":}',
)
applicability_passed: bool = Field(
sa_column=sa.Column(sa.Boolean, nullable=False),
description="EL-04b: resultado de evaluar los criterios de aplicabilidad de producción contra esta fila",
)
created_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_column=sa.Column(sa.DateTime, nullable=False),
)
-7
View File
@@ -1,7 +0,0 @@
from core.governance.extraction_run.model import ExtractionRun
from core.governance.model_prediction.model import ModelPrediction
__all__ = [
"ExtractionRun",
"ModelPrediction",
]

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