Compare commits

..

104 Commits

Author SHA1 Message Date
Angel Capetillo Zavala b77c22168c Resolve submodule URLs relative to integrator remote 2026-12-01 12:29:33 -06:00
Angel Capetillo Zavala d3a02178d1 CaMa: pin integration branches for review 2026-12-01 12:28:18 -06:00
Angel Capetillo Zavala 72cd19219a CaMa: add provisional mammogram to biopsy duration 2026-12-01 12:27:28 -06:00
Angel Capetillo Zavala de58f0db59 CaMa: preserve synthetic mammogram biopsy link 2026-12-01 12:27:17 -06:00
Roberto Treviño 2fe5301fd1 CaCu: procedures with their cytology and histology, seven measures, the cytology form's fields
ci / python (push) Successful in 51m44s
ci / web (push) Successful in 16m59s
2026-11-30 23:32:01 -06:00
Roberto Treviño 4ddbabd90c README: numbered installation and data loading; .env.ejemplo filled in
ci / python (push) Successful in 52m41s
ci / web (push) Successful in 10m36s
2026-11-30 08:12:44 -06:00
Roberto Treviño 0cf969c48e CI retries package downloads
ci / python (push) Successful in 1h19m14s
ci / web (push) Successful in 11m14s
2026-11-30 07:42:38 -06:00
Roberto Treviño 31ff84c89c A report as of a plain date answers instead of failing
ci / python (push) Failing after 11m29s
ci / web (push) Successful in 19m28s
2026-11-30 07:11:04 -06:00
Roberto Treviño 70cde6d98b Conectar's database dialog does not freeze
ci / python (push) Successful in 58m53s
ci / web (push) Successful in 19m39s
2026-11-30 05:17:14 -06:00
Roberto Treviño 04f31d2adb Reviewers' answers outlive merges; CI has pg_dump and fixed synthetic patients
ci / python (push) Successful in 53m29s
ci / web (push) Failing after 11m10s
2026-11-30 02:14:18 -06:00
Roberto Treviño 606a2efc89 Large Bundles do not kill an API worker; the EEG metrics' dependency is code, not a comment
ci / python (push) Failing after 45m23s
ci / web (push) Failing after 12m19s
2026-11-29 23:48:05 -06:00
Roberto Treviño d16d5ce7c5 repo.sh sorts in one locale
ci / python (push) Failing after 46m19s
ci / web (push) Failing after 12m1s
2026-11-29 21:31:31 -06:00
Roberto Treviño 8e4e080a11 repo.sh refuses to leave a product file out; its ignore rules only match the root
ci / python (push) Failing after 1h3m36s
ci / web (push) Failing after 12m14s
2026-11-29 21:30:55 -06:00
Roberto Treviño 2ff634c687 The generated API client matches the API
ci / python (push) Failing after 1h19m14s
ci / web (push) Failing after 20m7s
2026-11-29 21:15:26 -06:00
Roberto Treviño 50289a5b36 Training takes every model; recurrence is skipped when too few recurred
ci / python (push) Failing after 1h8m14s
ci / web (push) Failing after 3m53s
2026-11-29 21:12:38 -06:00
Roberto Treviño d5b466a77f load_site.py can resume the Synthea step and waits longer for a large Bundle 2026-11-29 20:47:45 -06:00
Roberto Treviño e1d3887e6c isssteleon.sh installs from source too; repo.sh adds each version as a commit on main
ci / python (push) Failing after 1h14m2s
ci / web (push) Failing after 3m44s
2026-11-29 20:19:53 -06:00
Roberto Treviño 8a7974a016 The cervical module gives the synthetic site more invasive cancers and recurrences after treatment
ci / python (push) Failing after 1h8m1s
ci / web (push) Failing after 3m20s
2026-11-29 18:05:32 -06:00
Roberto Treviño 4d788bf38c The delivery leaves Ruff's cache out
ci / python (push) Failing after 1h24m45s
ci / web (push) Failing after 3m20s
2026-11-29 16:58:46 -06:00
Roberto Treviño 7ed60a6ca1 tools/delivery/repo.sh: the product as a repository of its own, one commit on main 2026-11-29 16:58:22 -06:00
Roberto Treviño 0ef7f95c4d restaurar runs the restore with the application image alone 2026-11-29 16:41:40 -06:00
Roberto Treviño 12ec776548 The delivery keeps TypeScript's compiler directives 2026-11-29 15:54:03 -06:00
Roberto Treviño 1e160a7340 The delivery's README: install, operate, update, pages and build, in brief 2026-11-29 15:45:25 -06:00
Roberto Treviño 817aa33c22 The delivery ships the product only: no tests, tools or synthetic site, no docstrings, comments or documents but one short Spanish README 2026-11-29 15:42:19 -06:00
Roberto Treviño 9ffafdd3c9 Conectar guided editing and wording in the web app
ci / python (push) Failing after 1h18m57s
ci / web (push) Failing after 9m22s
2026-11-29 15:24:26 -06:00
Roberto Treviño 82423962f9 Pipeline fixtures name every node in Spanish 2026-11-29 15:24:26 -06:00
Roberto Treviño 0680a4ea18 A hand-drawn source that a catalog type makes is read as that type; database sources can pick columns 2026-11-29 15:24:26 -06:00
Roberto Treviño 2bd39e0de4 deploy: each installation names its Docker project 2026-11-29 12:57:57 -06:00
Roberto Treviño c7384dddd9 Phase 4.6 fixes and Phase 5 release and backups in the submodules
ci / python (push) Failing after 1h7m49s
ci / web (push) Failing after 21m36s
2026-11-29 12:39:14 -06:00
Roberto Treviño d7fe3bcf73 tools/load_site.py loads a deployment with the synthetic site through its API 2026-11-29 12:39:14 -06:00
Roberto Treviño 2efc73087c entregar.sh builds an offline delivery; deploy/ installs and operates it 2026-11-29 12:39:14 -06:00
Roberto Treviño b4a241d9d3 Patient search matching tested 2026-11-29 12:39:14 -06:00
Roberto Treviño 46c7dc3910 Erick's pipeline reads the reception date past an OCR dash 2026-11-29 12:39:14 -06:00
Roberto Treviño fe4e7b2fa0 Backups of the data folder: online SQLite copies, pg_dump, a checked manifest, restore that sets aside what was there 2026-11-29 12:39:14 -06:00
Roberto Treviño f9695b11f9 The FHIR door reads only what arrived since the last run 2026-11-29 12:39:14 -06:00
Roberto Treviño 7e1d298224 CaMa mammograms carry their days to diagnosis 2026-11-29 12:39:14 -06:00
Roberto Treviño 5e41274c3d Entity schemas carry the catalog's Spanish field titles 2026-11-29 12:39:14 -06:00
Roberto Treviño c115b70ff5 Models have Spanish titles; RiskAssessment names its model by it 2026-11-29 12:39:14 -06:00
Roberto Treviño 0aef356fd4 Record history shows only ICD-10 codes beside a diagnosis
ci / python (push) Successful in 1h3m25s
ci / web (push) Failing after 17m10s
2026-11-29 07:13:59 -06:00
Roberto Treviño 3435279f37 TEA scoring works again with every model scored
ci / python (push) Successful in 43m4s
ci / web (push) Failing after 14m51s
2026-11-29 07:03:09 -06:00
Roberto Treviño f2605c5f4e WebApp's OpenAPI spec is current
ci / python (push) Successful in 48m48s
ci / web (push) Failing after 11m16s
2026-11-29 06:58:39 -06:00
Roberto Treviño a176b5a19a Records list CaMa treatments and recurrences and draw their clinical scenarios
ci / python (push) Successful in 43m53s
ci / web (push) Failing after 2m47s
2026-11-29 06:43:17 -06:00
Roberto Treviño 944f92e5d3 Measures index rows by month instead of scanning them per period
ci / python (push) Failing after 1h3m38s
ci / web (push) Failing after 5m32s
2026-11-29 06:23:13 -06:00
Roberto Treviño 2190c2a006 Erick's site writes recurrence notes and positive nodes; his pipeline reads them
ci / python (push) Successful in 54m47s
ci / web (push) Failing after 9m2s
2026-11-29 01:50:23 -06:00
Roberto Treviño 7757b4fd5a Promotion docs name the configured reports
ci / python (push) Failing after 22s
ci / web (push) Failing after 1m53s
2026-11-29 01:41:03 -06:00
Roberto Treviño c488630eea Promotion requires the reports the site configures
ci / python (push) Failing after 34s
ci / web (push) Failing after 43s
2026-11-29 01:40:53 -06:00
Roberto Treviño ef5d4a238a The API runs several workers
ci / python (push) Failing after 36s
ci / web (push) Failing after 43s
2026-11-29 01:32:11 -06:00
Roberto Treviño a371e43055 The recurrence report names the site's own cohort
ci / python (push) Successful in 1h19m2s
ci / web (push) Failing after 19m9s
2026-11-29 01:20:41 -06:00
Roberto Treviño b969f9cab4 Recurrences named in Revisión; door test counts timeline recurrences
ci / python (push) Failing after 13m14s
ci / web (push) Failing after 35m10s
2026-11-29 01:06:43 -06:00
Roberto Treviño ee532b1f90 Site recurrence scenarios find their patients
ci / python (push) Failing after 1h16m46s
ci / web (push) Failing after 7m8s
2026-11-29 00:41:25 -06:00
Roberto Treviño 498656adf6 The CaMa FHIR door keeps breast recurrences
ci / python (push) Failing after 52m45s
ci / web (push) Failing after 2m33s
2026-11-28 23:05:31 -06:00
Roberto Treviño d3276220df Recurrence scenarios leave Gobernanza
ci / python (push) Failing after 57m59s
ci / web (push) Failing after 2m58s
2026-11-28 21:30:01 -06:00
Roberto Treviño ed7c6d5a3b Sort the TEA gate's imports
ci / python (push) Failing after 58m7s
ci / web (push) Failing after 9m50s
2026-11-28 21:28:56 -06:00
Roberto Treviño 0cdb3ac862 Train every model on the site's data: recurrences and nodes in silver and Synthea, age-matched EEGs, association with the ADOS-2
ci / python (push) Failing after 3m37s
ci / web (push) Failing after 3m33s
2026-11-28 21:28:45 -06:00
Roberto Treviño 6f417bae80 Trazabilidad, definitions and risk lists as the old app
ci / python (push) Failing after 2m48s
ci / web (push) Failing after 11m26s
2026-11-28 17:24:30 -06:00
Roberto Treviño d15b468d56 Format the EEG study test; governance spec follows the scenarios to the record
ci / python (push) Failing after 2m48s
ci / web (push) Successful in 9m52s
2026-11-28 17:16:26 -06:00
Roberto Treviño b5f5762281 TEA record shows the zones most affected by each EEG alteration
ci / python (push) Failing after 2m38s
ci / web (push) Failing after 2m26s
2026-11-28 17:15:46 -06:00
Roberto Treviño 243902cb9b Test client drops idle connections before uvicorn does; wizard test waits for the dialog to close
ci / python (push) Failing after 2m40s
ci / web (push) Successful in 10m27s
2026-11-28 16:05:25 -06:00
Roberto Treviño c84c0eba54 compose: the web app's first administrator, sign-in app registrations and source folders from .env
ci / python (push) Failing after 1h11m38s
ci / web (push) Failing after 14m26s
2026-11-28 13:31:30 -06:00
Roberto Treviño 331720c839 gold.cama_risk reads the scenarios column only where the risk batch has it
ci / python (push) Successful in 1h17m29s
ci / web (push) Failing after 13m53s
2026-11-28 13:31:07 -06:00
Roberto Treviño 7dffd97282 TEA record summary; EEG age bands; CI fixes for crossed strata and the session test
ci / python (push) Failing after 1h18m0s
ci / web (push) Failing after 18m30s
2026-11-28 13:29:39 -06:00
Roberto Treviño 66199b2a89 TEA follow-up list: route stage, case, study EEG and its alterations against the age curves, scores; served as the list's Patient extensions
ci / python (push) Failing after 50m42s
ci / web (push) Failing after 14m8s
2026-11-28 10:47:31 -06:00
Roberto Treviño ea46861ff5 TEA Indicadores as the old page; the in-process fixture in the root conftest
ci / python (push) Failing after 30s
ci / web (push) Failing after 16m15s
2026-11-28 10:26:28 -06:00
Roberto Treviño 6eaa1dbafa The old TEA pages as rendered; captures keep patients' records by size only
ci / python (push) Failing after 11m14s
ci / web (push) Failing after 10m46s
2026-11-28 10:22:23 -06:00
Roberto Treviño d9f9e9f931 WebApp: CaMa Indicadores as the old page
ci / python (push) Failing after 5m50s
ci / web (push) Failing after 10m17s
2026-11-28 10:09:33 -06:00
Roberto Treviño 9866d81f75 Composition measures cross each stratum with the category; test administrator at a valid domain
ci / python (push) Failing after 6m1s
ci / web (push) Failing after 13m9s
2026-11-28 10:03:32 -06:00
Roberto Treviño 3527b395de The old CaCu and CaMa pages as rendered: headings, cards, plots, their data, loading indicators and screenshots
ci / python (push) Failing after 5m52s
ci / web (push) Failing after 9m56s
2026-11-28 09:48:49 -06:00
Roberto Treviño 5eda1dffe2 Phase 4.6 part 1: source types as a catalog with guided dialogs, files on any fsspec filesystem, web sign-in, clinical scenarios in CaMa risks, old pages captured for the Indicadores
ci / python (push) Failing after 5m53s
ci / web (push) Failing after 11m13s
2026-11-28 09:30:01 -06:00
Roberto Treviño 6cf3faa2a9 Link each distinct identity once, not every pair of a patient's records
ci / python (push) Failing after 7m11s
ci / web (push) Failing after 3m13s
2026-11-28 01:17:40 -06:00
Roberto Treviño 1ac9142397 Files spooled to disk and stored straight into their table, not through dlt; Erick's source read in chunks 2026-11-27 22:29:26 -06:00
Roberto Treviño cf9bc8b913 The site writes its table a few rows or one recording per insert 2026-11-27 20:23:28 -06:00
Roberto Treviño 32969947e1 Erick's site staples some HPV reports to their cytology form and holds papers no study reads; review lists them 2026-11-27 19:17:50 -06:00
Roberto Treviño 0316d50cd1 TEA at Erick's site: Synthea TEA module, M-CHAT, ADOS-2, neurology notes, EEG reports with their anonymised recordings; optional Dask and a worker image 2026-11-27 16:25:02 -06:00
Roberto Treviño 2d6d604e3e Erick's site as he holds it now: one table, sample dated by reception, his wording and employee numbers; a date read as a record number is held
ci / python (push) Successful in 49m9s
ci / web (push) Successful in 11m54s
2026-11-27 14:02:09 -06:00
Roberto Treviño 0724b04e69 models: outcomes per split in the CaCu metrics 2026-11-27 11:05:28 -06:00
Roberto Treviño ecf37e1f8c Synthetic CaCu with colposcopy clinic, treatment, co-test follow-up, cancers and deaths; Erick's site prints notes and death notes 2026-11-27 08:46:09 -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
468 changed files with 375141 additions and 15606 deletions
+7 -13
View File
@@ -1,13 +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/
**/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
+111
View File
@@ -0,0 +1,111 @@
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: |
echo 'Acquire::Retries "5";' > /etc/apt/apt.conf.d/80-retries # mirrors drop connections
apt-get update --error-on=any
apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-spa ghostscript \
default-jre-headless postgresql-common
# pg_dump of the server's version (backups), as in the product's image.
/usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y
apt-get install -y --no-install-recommends postgresql-client-17
- 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: |
echo 'Acquire::Retries "5";' > /etc/apt/apt.conf.d/80-retries # mirrors drop connections
apt-get update --error-on=any
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 -15
View File
@@ -1,16 +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
+8 -9
View File
@@ -1,13 +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
url = ../WebApi.git
branch = rebuild
[submodule "WebApp"]
path = WebApp
url = ../WebApp.git
branch = rebuild
[submodule "models"]
path = models
url = ssh://git@10.0.10.41:2222/ISSSTELEON/models.git
[submodule "indicadores_kit"]
path = indicadores_kit
url = ssh://git@10.0.10.41:2222/ISSSTELEON/indicadores_kit.git
branch = dev
url = ../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
+91
View File
@@ -0,0 +1,91 @@
"""CaCu clinical parameters: the one place they are set. dbt reads them as vars, the models
import them. Codes are the platform's (core.schema)."""
# Biopsy grades that count as CIN2+ (the outcome) and as invasive cancer.
CIN2_PLUS = ["HSIL", "CIS", "carcinoma"]
CANCER = ["carcinoma"]
CASE = ["CIS", "carcinoma"] # a biopsy this grade makes her a case: she has cancer
# The follow-up list: patients with a cytology sampled within the window before the cut-off.
FOLLOW_UP_WINDOWS = [1, 3, 6, 12] # months
FOLLOW_UP_WINDOW = 3
# Index cytology in the six KPNC categories, least to most severe.
KPNC = {
"NILM": ["NILM"],
"ASC-US": ["ASC-US"],
"LSIL": ["LSIL"],
"ASC-H": ["ASC-H"],
"AGC": ["AGC"],
"HSIL+": ["HSIL", "CIS", "adenocarcinoma"],
}
# The three categories used after colposcopy and after treatment.
KPNC_3 = {
"NILM": ["NILM"],
"ASC-US/LSIL": ["ASC-US", "LSIL"],
"High Grade": ["ASC-H", "AGC", "HSIL", "CIS", "adenocarcinoma"],
}
# Results that show a patient free of CIN2+ at a visit: a negative co-test (both within
# INDEX_SAMPLE_DAYS of each other), or a biopsy below the outcome grades.
KNOWN_NEGATIVE = {"bethesda": ["NILM", "ASC-US"], "hpv": ["negative"]}
INDEX_SAMPLE_DAYS = 30 # results this many days after the index sample still describe it
PREVALENT_WINDOW_DAYS = 6 * 365.25 / 12 # an outcome this soon was there at the index
DAYS_PER_YEAR = 365.25
# Recruitment windows (start inclusive, end exclusive).
RECRUITMENT = ("2018-01-01", "2027-01-01")
POST_TREATMENT_RECRUITMENT = ("2024-01-01", "2027-01-01")
POST_TREATMENT_INDEX_AFTER_DAYS = 90 # the index cytology comes this long after treatment
POST_TREATMENT_LOOKBACK_DAYS = 365 # a biopsy result this long before treatment is required
POST_COLPOSCOPY_VISIT = 1 # index: the k-th surveillance cytology after the colposcopy result
REFERRAL_LOOKBACK_DAYS = 365 # results this long before colposcopy are why she was referred
CYTOLOGY_BEFORE_DAYS = 365 # a procedure's cytology was reported this long before at most
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
# The PPVs of a procedure: groups of its cytology (each holds the more severe squamous ones)
# and of its histology; the first histology group is the score's.
PROCEDURE_CYTOLOGY = {
"ascus_plus": ["ASC-US", "LSIL", "ASC-H", "HSIL", "CIS"],
"lsil_plus": ["LSIL", "ASC-H", "HSIL", "CIS"],
"hsil_plus": ["HSIL", "CIS"],
}
PROCEDURE_HISTOLOGY = {
"cin1_plus": ["LSIL", *CIN2_PLUS], "cin2_plus": CIN2_PLUS, "carcinoma": CANCER,
} # fmt: skip
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": "route"} # what followed the sample
def status(row: dict, cutoff: date) -> str:
"""Her follow-up status by the end of the cut-off day."""
return follow_up_status(row, cutoff, through=True)
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
"""The rows (whoever had a cytology sampled in the window, most recent first), each with
her status."""
return [{**r, "status": status(r, cutoff)} for r in rows]
def current_risk(risks: Iterable[dict], outcome: str, horizon: float) -> float | None:
"""Her current risk of an outcome at a horizon (years): from the latest index date any
of the outcome's models scored her at; the highest when several did."""
prefix = OUTCOMES[outcome]
mine = [r for r in risks if r["model"].startswith(prefix) and r["horizon_years"] == horizon]
if not mine:
return None
latest = max(str(r["index_date"]) for r in mine)
return max(r["probability"] for r in mine if str(r["index_date"]) == latest)
def ordered(rows: list[dict], sort: str, risks: dict[str, list[dict]],
horizon: float) -> list[dict]: # fmt: skip
"""The list in reading order. `rows` come most recent first; by risk, highest first,
unscored patients last, ties kept most recent first."""
if sort == "-recent":
return rows
outcome = sort.removeprefix("-risk-")
def key(row: dict):
found = current_risk(risks.get(row["person_id"], []), outcome, horizon)
return (found is None, -(found or 0.0))
return sorted(rows, key=key)
-200
View File
@@ -1,200 +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,
CatResultadoBase,
CatValorBase,
estado_de_valor_conocido,
tipo_de_valor_conocido,
)
from core.indicadores.plata import (
ObservacionClinicaBase,
ProcedimientoClinicoBase,
clase_conocida,
indice_de_observacion,
indice_de_procedimiento,
observacion_en_catalogo,
llave_de_observacion,
llave_de_procedimiento,
)
from core.indicadores.comunes import CargaBase, PeriodoObservacionBase, PersonaDerechohabienteBase
from core.indicadores.registro import (
DefParametroBase,
DimFechaBase,
DimGrupoEdadBase,
DimPeriodoBase,
)
from core.indicadores.publicacion import (
CatEstratoBase,
CatEstratoValorBase,
CatMeasureBase,
CatMeasureEstratoBase,
CatMeasureGrupoBase,
CatMeasureResultadoBase,
CatMeasureValorBase,
MeasureReportUnidadBase,
MeasureReportUnidadEstratoBase,
contrato_y_unidad_conocidos,
origen_conocido,
poblacion_conocida,
una_poblacion_por_indicador,
unidad_de_estrato_conocida,
valor_de_estrato_en_catalogo,
)
from core.indicadores.reportes import (
MeasureReportBase,
)
class Persona(CaCuModel, PersonaDerechohabienteBase, table=True):
__tablename__ = "persona"
class PeriodoObservacion(CaCuModel, PeriodoObservacionBase, table=True):
__tablename__ = "periodo_observacion"
class Carga(CaCuModel, CargaBase, table=True):
__tablename__ = "carga"
class DefParametro(CaCuModel, DefParametroBase, table=True):
__tablename__ = "def_parametro"
class DimPeriodo(CaCuModel, DimPeriodoBase, table=True):
__tablename__ = "dim_periodo"
class DimFecha(CaCuModel, DimFechaBase, table=True):
__tablename__ = "dim_fecha"
class DimGrupoEdad(CaCuModel, DimGrupoEdadBase, table=True):
__tablename__ = "dim_grupo_edad"
class MeasureReport(CaCuModel, MeasureReportBase, table=True):
__tablename__ = "measure_report"
# --- El oro por unidad y su catálogo (§6f, MD-19) ---
class CatMeasure(CaCuModel, CatMeasureBase, table=True):
__tablename__ = "cat_measure"
__table_args__ = contrato_y_unidad_conocidos()
class CatMeasureResultado(CaCuModel, CatMeasureResultadoBase, table=True):
__tablename__ = "cat_measure_resultado"
__table_args__ = (poblacion_conocida(), una_poblacion_por_indicador())
class CatMeasureValor(CaCuModel, CatMeasureValorBase, table=True):
__tablename__ = "cat_measure_valor"
__table_args__ = (origen_conocido(),)
class CatMeasureGrupo(CaCuModel, CatMeasureGrupoBase, table=True):
__tablename__ = "cat_measure_grupo"
class CatEstrato(CaCuModel, CatEstratoBase, table=True):
__tablename__ = "cat_estrato"
__table_args__ = (unidad_de_estrato_conocida(),)
class CatEstratoValor(CaCuModel, CatEstratoValorBase, table=True):
__tablename__ = "cat_estrato_valor"
class CatMeasureEstrato(CaCuModel, CatMeasureEstratoBase, table=True):
__tablename__ = "cat_measure_estrato"
class MeasureReportUnidad(CaCuModel, MeasureReportUnidadBase, table=True):
__tablename__ = "measure_report_unidad"
class MeasureReportUnidadEstrato(CaCuModel, MeasureReportUnidadEstratoBase, table=True):
__tablename__ = "measure_report_unidad_estrato"
__table_args__ = (valor_de_estrato_en_catalogo(),)
# --- Catálogos de la plata (F1): estudio -> resultado -> valor, de core/catalogos/cacu.toml ---
class CatEstudio(CaCuModel, CatEstudioBase, table=True):
__tablename__ = "cat_estudio"
class CatResultado(CaCuModel, CatResultadoBase, table=True):
__tablename__ = "cat_resultado"
__table_args__ = (tipo_de_valor_conocido(),)
class CatValor(CaCuModel, CatValorBase, table=True):
__tablename__ = "cat_valor"
__table_args__ = (estado_de_valor_conocido(),)
# --- La plata de dos tablas (F5, ADR-MD-007) ---
class Procedimiento(CaCuModel, ProcedimientoClinicoBase, table=True):
__tablename__ = "procedimiento"
__table_args__ = (clase_conocida(), llave_de_procedimiento(), indice_de_procedimiento())
class Observacion(CaCuModel, ObservacionClinicaBase, table=True):
__tablename__ = "observacion_clinica" # `observacion` choca con la CTE `observacion` del motor (T-18r)
__table_args__ = (*observacion_en_catalogo(), llave_de_observacion(), indice_de_observacion())
# --- Cohortes para modelos y estimaciones de riesgo (oro restringido, ADR-MD-003) ---
class CohorteArmado(CaCuModel, CohorteArmadoBase, table=True):
__tablename__ = "cohorte_armado"
__table_args__ = (armado_unico(),)
class CohorteMiembro(CaCuModel, CohorteMiembroBase, table=True):
__tablename__ = "cohorte_miembro"
class CohorteExclusion(CaCuModel, CohorteExclusionBase, table=True):
__tablename__ = "cohorte_exclusion"
class CohorteVariable(CaCuModel, CohorteVariableBase, table=True):
__tablename__ = "cohorte_variable"
__table_args__ = (variable_con_un_valor(),)
class EvaluacionRiesgoLote(CaCuModel, EvaluacionRiesgoLoteBase, table=True):
__tablename__ = "evaluacion_riesgo_lote"
class EvaluacionRiesgo(CaCuModel, EvaluacionRiesgoBase, table=True):
__tablename__ = "evaluacion_riesgo"
__table_args__ = (evaluacion_unica(),)
+233
View File
@@ -0,0 +1,233 @@
"""CaCu's measures (`core.measures` evaluates them) and the follow-up status they stratify by."""
from datetime import date
from core import cacu
from core.measures import (
NO_BIOPSY,
NO_DATA,
Composition,
Duration,
Measure,
Proportion,
RiskBand,
age_group,
as_day,
desc,
)
def follow_up_status(row: dict, at: date, through: bool = False) -> str:
"""Where the patient was in her follow-up just before `at` (`through`: by the end of
`at`), from the first day of each step (`gold.cacu_follow_up`). A case already has
cancer; what follows her is survival."""
def by(first: str) -> bool:
day = as_day(row.get(first))
return day is not None and (day <= at if through else day < at)
for first, status in (("first_case", "case"), ("first_treatment", "post_treatment"),
("first_colposcopy", "post_colposcopy")): # fmt: skip
if by(first):
return status
return "pre_colposcopy"
def valid(row: dict) -> bool:
"""A cytology with a result, reported, of satisfactory (or unknown) adequacy."""
return row["result_date"] is not None and row.get("adequacy") != "unsatisfactory"
def latest(row: dict) -> tuple:
"""A patient's latest valid sample ranks highest."""
return valid(row), as_day(row["sample_date"]), row["sample_id"]
def latest_most_severe_biopsy(row: dict) -> tuple:
"""Her latest valid sample, then its most severe reported biopsy, the latest first."""
reported = row.get("biopsy_report_date") is not None
return (*latest(row), reported, row.get("severity") or 0,
desc(as_day(row.get("biopsy_report_date"))), desc(row.get("biopsy_id"))) # fmt: skip
def result(row: dict) -> str:
return row["result"] if valid(row) else NO_DATA
def histology(row: dict) -> str:
"""The chosen biopsy's histology (NO_BIOPSY without one reported)."""
if not valid(row):
return NO_DATA
if row.get("biopsy_report_date") is None:
return NO_BIOPSY
return row.get("histology") or NO_DATA
def case_before(row: dict) -> bool:
"""Whether she was a case already: at the procedure's cytology, or at it without one."""
return follow_up_status(row, as_day(row["sample_date"] or row["date"])) == "case"
def earliest(row: dict) -> tuple:
return -as_day(row["date"]).toordinal(), row["procedure_id"]
def groups_by_cytology(row: dict, p=None) -> list[str]:
if row["result"] is None:
return [NO_DATA]
return [g for g, results in cacu.PROCEDURE_CYTOLOGY.items() if row["result"] in results]
SIGN = {True: "positive", False: "negative"} # SQLite answers booleans as 1 and 0: the same keys
def groups_by_hpv(row: dict, p=None) -> list[str]:
"""Her HPV result and, apart, each genotype found (they overlap)."""
said = [SIGN[row["hpv"]]] if row["hpv"] in SIGN else []
return [*said, *(g for g in ("hpv_16", "hpv_18") if row[g])] or [NO_DATA]
def round_of(row: dict, p=None) -> str:
"""Subsequent: screened before, as her form says, or past colposcopy or treatment at the
sample. Initial: the first screening of her life."""
if row["sample_date"] is None:
return NO_DATA
if follow_up_status(row, as_day(row["sample_date"])) in ("post_colposcopy", "post_treatment"):
return "subsequent"
history = row["screening_history"]
return NO_DATA if history is None else "initial" if history == "never" else "subsequent"
def hpv_genotype(row: dict) -> str:
"""What an HPV report says, a null never read as a negative."""
hpv, found = row["hpv"], [g for g in ("16", "18") if row[f"hpv_{g}"]]
if not hpv:
return "inconsistent" if found else "no_result" if hpv is None else "negative"
if row["hpv_16"] is None or row["hpv_18"] is None:
return "positive_incomplete"
return "positive_" + ("_".join(found) or "other")
def biopsy_answer(row: dict) -> str:
"""What became of a biopsy requested, by its report."""
if row["report_date"] is None:
return "pending"
if as_day(row["report_date"]) < as_day(row["date"]):
return "inconsistent"
if row["histology"] is None:
return "no_grade"
return "high_grade" if row["histology"] in cacu.CIN2_PLUS else "below_high_grade"
def ppv(id: str, title: str, procedure: str, counted) -> Measure:
"""Of the patients with the procedure in the period (her first), those whose histology is
LIEBG or more; those already cases are left out."""
levels = tuple((name, lambda r, grades=grades: r["histology"] in grades)
for name, grades in cacu.PROCEDURE_HISTOLOGY.items()) # fmt: skip
return Measure(
id, title, "procedures",
Proportion(levels[0][1], denominator=lambda r: counted(r) and not case_before(r),
order=earliest, levels=levels, date="date",
strata=(("cytology", groups_by_cytology), ("hpv", groups_by_hpv),
("round", round_of))),
params={"type": procedure},
facts={"report_known_at": ("histology", "report_date"),
"cytology_known_at": ("result", "hpv", "hpv_16", "hpv_18")},
dated={"report_date": ("histology",)},
) # fmt: skip
H = cacu.HORIZONS
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no cervical cancer note before
AGE = ("age_group", lambda row, p: age_group(row.get("birth_date"), p.start, cacu.AGE_GROUPS))
STATUS = ("follow_up_status", lambda row, p: follow_up_status(row, p.start))
RESULT = ("result", lambda row, p: row["result"])
MEASURES = {m.id: m for m in [
Measure("IND1", "Pacientes con citología anormal", "samples",
Proportion(lambda r: r["result"] in cacu.ABNORMAL), "decrease", group="principal"),
Measure("CACU_EU13", "Tasa de detección histopatológica", "sample_biopsies",
Proportion(lambda r: r.get("histology") in cacu.DETECTION
and r.get("biopsy_report_date") is not None,
strata=(AGE, STATUS)), group="principal"),
Measure("CACU_EU7", "Pacientes evaluadas por resultado de citología", "samples",
Composition(latest, result, strata=(AGE, STATUS, ("round", round_of)))),
Measure("CACU_VPH", "Pacientes evaluadas por resultado de VPH", "samples",
Composition(lambda r: (as_day(r["sample_date"]), r["sample_id"]),
lambda r: SIGN[r["hpv"]],
where=lambda r: r["hpv"] is not None,
strata=(AGE, STATUS, ("round", round_of),
*((g, lambda r, p, g=g: SIGN.get(r[g], []))
for g in ("hpv_16", "hpv_18")))),
facts={"report_known_at": ("hpv", "hpv_16", "hpv_18")}),
Measure("CACU_VPH_GENOTIPO", "Resultados de VPH por genotipo", "samples",
Composition(lambda r: (), hpv_genotype, unit="sample_id",
where=lambda r: r["report_date"] is not None and any(
r[c] is not None for c in ("hpv", "hpv_16", "hpv_18"))),
facts={"report_known_at": ("hpv", "hpv_16", "hpv_18", "report_date")},
description="Reportes de VPH, por fecha de toma."),
Measure("CACU_BIOPSIA_RESULTADOS", "Resultados de biopsia cervical", "procedures",
Composition(lambda r: (), lambda r: r["histology"] or NO_DATA,
unit="procedure_id", date="report_date",
where=lambda r: r["report_date"] is not None),
params={"type": "biopsy"}, known="report_known_at",
description="Reportes de biopsia, por fecha de reporte."),
Measure("CACU_BIOPSIA_SOLICITUD_CONFIRMACION",
"Confirmación por solicitudes de biopsia", "procedures",
Composition(lambda r: (), biopsy_answer, unit="procedure_id", date="date"),
params={"type": "biopsy"},
facts={"report_known_at": ("histology", "report_date")},
dated={"report_date": ("histology",)},
description="Solicitudes de biopsia registradas, por fecha de solicitud."),
ppv("CACU_VPP_COLPOSCOPIA", "Valor predictivo positivo de la colposcopía", "colposcopy",
lambda r: True),
ppv("CACU_VPP_BIOPSIA", "Valor predictivo positivo de la biopsia", "biopsy",
lambda r: r["histology"] is not None and r["report_date"] is not None),
Measure("CACU_TIEMPO_DIAGNOSTICO_CIE10", "Tiempo de tamizaje a diagnóstico por CIE-10",
"samples",
Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=NO_HISTORY,
strata=(("diagnosis_code",
lambda r, p: r["diagnosis_code"] or NO_DATA),)), "decrease"),
Measure("CACU_CONFIRMACION_CITOLOGIA", "Confirmación histopatológica", "sample_biopsies",
Composition(latest_most_severe_biopsy, histology,
admit=lambda r: valid(r) and r["result"] in cacu.HIGH_GRADE,
strata=(RESULT,))),
Measure("CACU_EU_TIEMPO_REPORTE", "Tiempo de toma a resultado de citología", "samples",
Duration("days_sample_result", "result_date", "sample_date", H["sample_to_report"],
ended="report_date"), "decrease"),
Measure("CACU_DIAS_TOMA_DIAGNOSTICO", "Tiempo de tamizaje a diagnóstico", "samples",
Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_TOMA_TRATAMIENTO", "Tiempo de tamizaje a tratamiento", "samples",
Duration("days_sample_treatment", "treatment_date", "sample_date",
H["sample_to_treatment"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_DIAGNOSTICO_TRATAMIENTO", "Tiempo de diagnóstico a tratamiento", "samples",
Duration("days_diagnosis_treatment", "diagnosis_treatment_date", "diagnosis_date",
H["diagnosis_to_treatment"],
units=lambda r: r["history"] == 0 and r["diagnosis_date"] is not None),
"decrease"),
Measure("CACU_DIAS_TOMA_COLPOSCOPIA", "Tiempo de toma de muestra a colposcopía", "samples",
Duration("days_sample_colposcopy", "colposcopy_date", "sample_date",
H["sample_to_colposcopy"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_TOMA_BIOPSIA", "Tiempo de toma de muestra a resultado de biopsia", "samples",
Duration("days_sample_biopsy", "biopsy_date", "sample_date",
H["sample_to_biopsy"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_RESULTADO_COLPOSCOPIA", "Tiempo de resultado a colposcopía", "samples",
Duration("days_result_colposcopy", "result_colposcopy_date", "result_date",
H["result_to_colposcopy"],
units=lambda r: r["history"] == 0 and r["result_date"] is not None),
"decrease"),
Measure("CACU_DIAS_COLPOSCOPIA_BIOPSIA", "Tiempo de colposcopía a biopsia", "samples",
Duration("days_colposcopy_biopsy", "biopsy_date", "result_colposcopy_date",
H["colposcopy_to_biopsy"],
units=lambda r: r["history"] == 0
and r["result_colposcopy_date"] is not None), "decrease"),
Measure("CACU_DIAS_BIOPSIA_DIAGNOSTICO", "Tiempo de biopsia a diagnóstico", "samples",
Duration("days_biopsy_diagnosis", "biopsy_diagnosis_date", "biopsy_date",
H["biopsy_to_diagnosis"],
units=lambda r: r["history"] == 0 and r["biopsy_date"] is not None),
"decrease"),
Measure("CACU_RIESGO_BANDA", "Banda de riesgo de CIN2+ en vigilancia", "risk",
RiskBand(tuple(cacu.RISK_BANDS)),
periods=("semester",), params={"model": cacu.RISK_BAND_MODEL}),
]} # fmt: skip
-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",
)
+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 = ("treatment",) # by kind (persistance.fhir: CaMa's procedure read)
REPORT_FACTS = {"mammography": "diagnosis_days"} # days from the mammogram to its diagnosis
URGENT = ["5", "6"] # BI-RADS whose pending biopsy is high priority
def _ranked(row: dict) -> tuple:
return as_day(row["exam_date"]), as_day(row["report_date"]), row["birads_rank"] or 0
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
"""From each reported mammogram and the biopsies it led to (`gold.cama_mammogram_biopsies`),
who is on the list, most recent mammogram first."""
latest: dict[str, dict] = {}
biopsies: dict[str, list[dict]] = {}
for row in rows:
exam, report = as_day(row["exam_date"]), as_day(row["report_date"])
if row["birads"] is None or report is None or not exam <= report <= cutoff:
continue
person = row["person_id"]
if person not in latest or _ranked(row) > _ranked(latest[person]):
latest[person] = row
found = as_day(row["biopsy_report_date"])
if found is not None and exam <= found <= cutoff:
biopsies.setdefault(row["mammogram_id"], []).append(row)
out = []
for person, row in latest.items():
if row["birads"] not in cama.BIRADS_4_TO_6 or not start <= as_day(row["exam_date"]):
continue
mine = biopsies.get(row["mammogram_id"], [])
shown = max(mine, key=lambda b: (as_day(b["biopsy_report_date"]), b["biopsy_id"]),
default=None) # fmt: skip
cancers = [as_day(b["biopsy_report_date"]) for b in mine if b["histology"] in cama.CANCER]
if cancers:
status, priority = "cancer", "high"
elif shown is None:
status = "pending_biopsy"
priority = "high" if row["birads"] in URGENT else "medium"
elif shown["histology"] is None:
status, priority = "biopsy_no_result", "medium"
else:
status, priority = "benign_biopsy", "low"
out.append({
"person_id": person, "birth_date": row["birth_date"], "status": status,
"priority": priority, "recent": as_day(row["exam_date"]),
"first_cancer": min(cancers, default=None),
}) # fmt: skip
return sorted(out, key=lambda r: (-r["recent"].toordinal(), r["person_id"]))
def status(row: dict, cutoff: date) -> None:
"""A patient's status exists only on the list."""
return None
def ordered(rows: list[dict], sort: str, risks: dict, horizon) -> list[dict]:
return rows
-200
View File
@@ -1,200 +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,
CatResultadoBase,
CatValorBase,
estado_de_valor_conocido,
tipo_de_valor_conocido,
)
from core.indicadores.plata import (
ObservacionClinicaBase,
ProcedimientoClinicoBase,
clase_conocida,
indice_de_observacion,
indice_de_procedimiento,
observacion_en_catalogo,
llave_de_observacion,
llave_de_procedimiento,
)
from core.indicadores.comunes import CargaBase, PeriodoObservacionBase, PersonaDerechohabienteBase
from core.indicadores.registro import (
DefParametroBase,
DimFechaBase,
DimGrupoEdadBase,
DimPeriodoBase,
)
from core.indicadores.publicacion import (
CatEstratoBase,
CatEstratoValorBase,
CatMeasureBase,
CatMeasureEstratoBase,
CatMeasureGrupoBase,
CatMeasureResultadoBase,
CatMeasureValorBase,
MeasureReportUnidadBase,
MeasureReportUnidadEstratoBase,
contrato_y_unidad_conocidos,
origen_conocido,
poblacion_conocida,
una_poblacion_por_indicador,
unidad_de_estrato_conocida,
valor_de_estrato_en_catalogo,
)
from core.indicadores.reportes import (
MeasureReportBase,
)
class Persona(CaMaModel, PersonaDerechohabienteBase, table=True):
__tablename__ = "persona"
class PeriodoObservacion(CaMaModel, PeriodoObservacionBase, table=True):
__tablename__ = "periodo_observacion"
class Carga(CaMaModel, CargaBase, table=True):
__tablename__ = "carga"
class DefParametro(CaMaModel, DefParametroBase, table=True):
__tablename__ = "def_parametro"
class DimPeriodo(CaMaModel, DimPeriodoBase, table=True):
__tablename__ = "dim_periodo"
class DimFecha(CaMaModel, DimFechaBase, table=True):
__tablename__ = "dim_fecha"
class DimGrupoEdad(CaMaModel, DimGrupoEdadBase, table=True):
__tablename__ = "dim_grupo_edad"
class MeasureReport(CaMaModel, MeasureReportBase, table=True):
__tablename__ = "measure_report"
# --- El oro por unidad y su catálogo (§6f, MD-19) ---
class CatMeasure(CaMaModel, CatMeasureBase, table=True):
__tablename__ = "cat_measure"
__table_args__ = contrato_y_unidad_conocidos()
class CatMeasureResultado(CaMaModel, CatMeasureResultadoBase, table=True):
__tablename__ = "cat_measure_resultado"
__table_args__ = (poblacion_conocida(), una_poblacion_por_indicador())
class CatMeasureValor(CaMaModel, CatMeasureValorBase, table=True):
__tablename__ = "cat_measure_valor"
__table_args__ = (origen_conocido(),)
class CatMeasureGrupo(CaMaModel, CatMeasureGrupoBase, table=True):
__tablename__ = "cat_measure_grupo"
class CatEstrato(CaMaModel, CatEstratoBase, table=True):
__tablename__ = "cat_estrato"
__table_args__ = (unidad_de_estrato_conocida(),)
class CatEstratoValor(CaMaModel, CatEstratoValorBase, table=True):
__tablename__ = "cat_estrato_valor"
class CatMeasureEstrato(CaMaModel, CatMeasureEstratoBase, table=True):
__tablename__ = "cat_measure_estrato"
class MeasureReportUnidad(CaMaModel, MeasureReportUnidadBase, table=True):
__tablename__ = "measure_report_unidad"
class MeasureReportUnidadEstrato(CaMaModel, MeasureReportUnidadEstratoBase, table=True):
__tablename__ = "measure_report_unidad_estrato"
__table_args__ = (valor_de_estrato_en_catalogo(),)
# --- Catálogos de la plata (F1): estudio -> resultado -> valor, de core/catalogos/cama.toml ---
class CatEstudio(CaMaModel, CatEstudioBase, table=True):
__tablename__ = "cat_estudio"
class CatResultado(CaMaModel, CatResultadoBase, table=True):
__tablename__ = "cat_resultado"
__table_args__ = (tipo_de_valor_conocido(),)
class CatValor(CaMaModel, CatValorBase, table=True):
__tablename__ = "cat_valor"
__table_args__ = (estado_de_valor_conocido(),)
# --- La plata de dos tablas (F5, ADR-MD-007) ---
class Procedimiento(CaMaModel, ProcedimientoClinicoBase, table=True):
__tablename__ = "procedimiento"
__table_args__ = (clase_conocida(), llave_de_procedimiento(), indice_de_procedimiento())
class Observacion(CaMaModel, ObservacionClinicaBase, table=True):
__tablename__ = "observacion_clinica" # `observacion` choca con la CTE `observacion` del motor (T-18r)
__table_args__ = (*observacion_en_catalogo(), llave_de_observacion(), indice_de_observacion())
# --- Cohortes para modelos y estimaciones de riesgo (oro restringido, ADR-MD-003; CaMa desde MD-12) ---
class CohorteArmado(CaMaModel, CohorteArmadoBase, table=True):
__tablename__ = "cohorte_armado"
__table_args__ = (armado_unico(),)
class CohorteMiembro(CaMaModel, CohorteMiembroBase, table=True):
__tablename__ = "cohorte_miembro"
class CohorteExclusion(CaMaModel, CohorteExclusionBase, table=True):
__tablename__ = "cohorte_exclusion"
class CohorteVariable(CaMaModel, CohorteVariableBase, table=True):
__tablename__ = "cohorte_variable"
__table_args__ = (variable_con_un_valor(),)
class EvaluacionRiesgoLote(CaMaModel, EvaluacionRiesgoLoteBase, table=True):
__tablename__ = "evaluacion_riesgo_lote"
class EvaluacionRiesgo(CaMaModel, EvaluacionRiesgoBase, table=True):
__tablename__ = "evaluacion_riesgo"
__table_args__ = (evaluacion_unica(),)
-18
View File
@@ -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",
)
+136
View File
@@ -0,0 +1,136 @@
"""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 should_be_biopsied(row: dict) -> bool:
"""A reported mammogram whose BI-RADS asks for a biopsy (the confirmation's denominator)."""
return reported(row) and row["birads"] in cama.SUSPICIOUS
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"),
# Pending the analysts' validation (LOTE-3-CAMA-REBUILD.md): the biopsy is the one whose
# request names the mammogram, the first reported if several; the horizon is the
# diagnosis's, as no other is set.
Measure("CAMA_DIAS_RESULTADO_BIOPSIA",
"Tiempo de resultado de mastografía a resultado de biopsia", "mammogram_first_biopsy",
Duration("days_report_biopsy", "biopsy_report_date", "report_date", H["to_diagnosis"],
units=should_be_biopsied, unit="mammogram_id", date="report_date"),
"decrease", facts=REPORT | {"biopsy_known_at": ("biopsy_report_date",
"days_report_biopsy")},
description=(
"PROVISIONAL, pendiente de validación metodológica de los analistas. Días del "
"reporte de la mastografía (BI-RADS 4, 4A, 4B, 4C o 5) al reporte de la primera "
"biopsia reportada cuya solicitud nombra esa mastografía; sin vínculo explícito "
"no hay medición. Horizonte de 180 días reutilizado del tramo a diagnóstico "
"(no hay uno propio). Por decidir: fuente real del vínculo, cohorte, selección "
"con varias biopsias, horizonte, historia de cáncer y fechas inconsistentes."
)),
]} # 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 (indicadores_kit cama)
BIOPSIA_CHICA = "BIOPSIA_CHICA"
SOLICITUD_PAPANICOLAO_BASE_LIQUIDA = "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA"
TIPO_ESTUDIO_ALIAS: dict[str, str] = {
"BIOPSIA CHICA": "BIOPSIA_CHICA",
"SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
"Solicitud de Papanicolao en Base Liquida": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
}
-77
View File
@@ -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",
)
+188
View File
@@ -0,0 +1,188 @@
"""The platform's clinical catalog: every study, the events it is made of, its fields, and the
code systems their values come from. It is data (the YAML files beside this module) and
changes only by a reviewed commit; nothing ships that it doesn't name.
Everything that validates, stores or serves a clinical value reads it: the pydantic model of
each study (what a pipeline's target checks rows against), the long silver tables and their
wide views (dbt), and the FHIR conformance resources the API serves.
"""
from datetime import date
from functools import cache
from pathlib import Path
from typing import Annotated, Any, ClassVar, Literal
import yaml
from pydantic import BaseModel, ConfigDict, Field, create_model, model_validator
HERE = Path(__file__).parent
EventClass = Literal["order", "encounter", "sample", "report", "part"]
# `file`: a document or signal kept whole (an EEG); silver holds its content hash, the
# platform keeps the content once (persistance.files).
ValueType = Literal["code", "boolean", "number", "date", "text", "file"]
class System(BaseModel):
model_config = ConfigDict(extra="forbid")
url: str
title: str
external: bool = False # a standard system we name but don't publish
class Event(BaseModel):
model_config = ConfigDict(extra="forbid")
date: str # the field that dates it
parent: EventClass | None = None
class FieldDef(BaseModel):
model_config = ConfigDict(extra="forbid")
type: ValueType
event: EventClass
title: str
system: str | None = None
codes: dict[str, str] = {} # allowed code -> display; empty: any code of `system`
pattern: str | None = None
unit: str | None = None
required: bool = False
@model_validator(mode="after")
def _codes_have_a_system(self):
if self.type == "code" and self.system is None:
raise ValueError("a code field names its system")
if self.type != "code" and (self.codes or self.system):
raise ValueError("only code fields take a system and codes")
return self
class Study(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str
key: list[str] # fields that, with the person, identify one study instance
events: dict[EventClass, Event]
fields: dict[str, FieldDef]
@model_validator(mode="after")
def _consistent(self):
for name in self.key:
if name not in self.fields:
raise ValueError(f"key field {name} is not a field")
for cls, event in self.events.items():
if self.fields.get(event.date, None) is None or self.fields[event.date].type != "date":
raise ValueError(f"{cls}: its date {event.date} is not a date field")
if event.parent and event.parent not in self.events:
raise ValueError(f"{cls}: parent {event.parent} is not an event")
for name, f in self.fields.items():
if f.event not in self.events:
raise ValueError(f"{name}: event {f.event} is not one of the study's")
return self
def _load(name: str) -> dict:
return yaml.safe_load((HERE / f"{name}.yaml").read_text(encoding="utf-8"))
@cache
def systems() -> dict[str, System]:
return {k: System.model_validate(v) for k, v in _load("systems").items()}
@cache
def files() -> dict[str, list[str]]:
"""Each catalog file (a domain, or `common` to all) and the studies it defines."""
return {
path.stem: list(_load(path.stem))
for path in sorted(HERE.glob("*.yaml"))
if path.stem != "systems"
}
def of_domain(domain: str) -> list[str]:
"""The studies a domain serves: its own and the common ones."""
return [*files().get(domain, []), *files().get("common", [])]
@cache
def studies() -> dict[str, Study]:
"""Every study of every catalog file, by name (names are unique across files)."""
found: dict[str, Study] = {}
for path in sorted(HERE.glob("*.yaml")):
if path.stem == "systems":
continue
for name, spec in _load(path.stem).items():
if name in found:
raise ValueError(f"study {name} is defined twice")
study = Study.model_validate(spec)
unknown = {f.system for f in study.fields.values() if f.system} - set(systems())
if unknown:
raise ValueError(f"{name}: unknown systems {sorted(unknown)}")
found[name] = study
return found
class Record(BaseModel):
"""One row of a study, as a pipeline's target receives it."""
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
key: ClassVar[tuple[str, ...]] = ()
study: ClassVar[str] = ""
_TYPES: dict[str, Any] = {
"boolean": bool,
"number": float,
"date": date,
"text": str,
"file": str,
} # fmt: skip (a file field holds its content hash)
def _annotation(f: FieldDef) -> Any:
if f.type == "code" and f.codes:
kind: Any = Literal[tuple(f.codes)] # type: ignore[valid-type]
elif f.type == "code":
kind = Annotated[str, Field(pattern=f.pattern)] if f.pattern else str
else:
kind = _TYPES[f.type]
return kind if f.required else kind | None
@cache
def model(study: str) -> type[Record]:
"""The pydantic model a row of this study is checked against."""
spec = studies()[study]
fields = { # titled as the catalog names them (forms and review show the titles)
name: (_annotation(f), Field(... if f.required else None, title=f.title))
for name, f in spec.fields.items()
}
found = create_model(study, __base__=Record, **fields) # type: ignore[call-overload]
found.key = tuple(spec.key)
found.study = study
return found
def value_column(f: FieldDef) -> str:
"""The typed column of the long observation table a field's value is stored in."""
return {"boolean": "value_bool", "number": "value_num", "date": "value_date"}.get(
f.type, "value_text"
)
def dbt_vars() -> dict:
"""What dbt reads (`var('catalog')`): each study's key, events and typed fields."""
return {
name: {
"key": s.key,
"events": {c: e.model_dump() for c, e in s.events.items()},
"fields": {
f: {
"type": d.type,
"event": d.event,
"column": value_column(d),
"codes": list(d.codes),
}
for f, d in s.fields.items()
},
}
for name, s in studies().items()
}
+125
View File
@@ -0,0 +1,125 @@
# 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:
never: Primera vez en la vida
within_1_year: Un año o menos
2_years: Dos años
3_or_more_years: Tres o más años
gynecologic_condition:
type: code
event: sample
title: Condición ginecoobstétrica a la detección
system: gynecologic-condition
codes:
postpartum: Puerperio posparto o posaborto
pregnant: Embarazo actual
iud: DIU in situ
hormonal_treatment: Tratamiento hormonal
other_treatment: Otro tratamiento ginecológico
postmenopausal: Posmenopausia
hysterectomy: Histerectomía
not_applicable: No aplica
presenting_symptom:
type: code
event: sample
title: Actualmente presenta
system: presenting-symptom
codes:
discharge: Flujo
vulvar_itching: Prurito o ardor vulvar
abnormal_bleeding: Sangrado anormal
none: Ninguno
cervix_appearance:
type: code
event: sample
title: A la exploración se observa
system: cervix-appearance
codes:
healthy: Cuello sano
lesion: Cuello anormal con lesión
not_seen: 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}
# What the cytologist adds in words. A finding is true when stated, otherwise unknown.
findings: {type: text, event: report, title: Hallazgos adicionales}
finding_inflammation: {type: boolean, event: report, title: "Hallazgo: inflamación"}
finding_reactive: {type: boolean, event: report, title: "Hallazgo: cambios reactivos"}
finding_vaginosis: {type: boolean, event: report, title: "Hallazgo: cambio en la flora sugestiva de vaginosis bacteriana"}
finding_candida: {type: boolean, event: report, title: "Hallazgo: microorganismos micóticos morfológicamente compatibles con Candida sp"}
finding_bacillary_cytolysis: {type: boolean, event: report, title: "Hallazgo: aumento de la flora bacilar con citólisis de las células intermedias"}
finding_cytolysis: {type: boolean, event: report, title: "Hallazgo: citólisis de las células intermedias"}
finding_trichomonas: {type: boolean, event: report, title: "Hallazgo: trichomonas vaginalis"}
finding_leptothrix: {type: boolean, event: report, title: "Hallazgo: microorganismos bacterianos morfológicamente compatibles con Leptothrix"}
finding_actinomyces: {type: boolean, event: report, title: "Hallazgo: microorganismos morfológicamente compatibles con Actinomyces sp"}
finding_actinomyces_changes: {type: boolean, event: report, title: "Hallazgo: cambios celulares compatibles con Actinomyces sp"}
finding_herpes_changes: {type: boolean, event: report, title: "Hallazgo: cambios celulares compatibles con virus herpes simple"}
finding_tubular_metaplasia: {type: boolean, event: report, title: "Hallazgo: metaplasia escamosa tubular"}
finding_keratotic: {type: boolean, event: report, title: "Hallazgo: cambios queratósicos"}
finding_pregnancy: {type: boolean, event: report, title: "Hallazgo: cambios asociados al embarazo"}
finding_atrophy: {type: boolean, event: report, title: "Hallazgo: atrofia"}
finding_hypoestrogenism: {type: boolean, event: report, title: "Hallazgo: hipoestrogenismo"}
finding_radiotherapy: {type: boolean, event: report, title: "Hallazgo: efecto de radioterapia"}
finding_iud_changes: {type: boolean, event: report, title: "Hallazgo: cambios compatibles con presencia de dispositivo intrauterino"}
finding_glandular_cells: {type: boolean, event: report, title: "Hallazgo: células glandulares post-histerectomía"}
finding_bacteria: {type: boolean, event: report, title: "Hallazgo: bacterias"}
finding_herpes_image: {type: boolean, event: report, title: "Hallazgo: imagen del virus del herpes"}
finding_fungi: {type: boolean, event: report, title: "Hallazgo: hongos"}
finding_radiation: {type: boolean, event: report, title: "Hallazgo: radiación"}
finding_repair: {type: boolean, event: report, title: "Hallazgo: reparación"}
finding_iud_effect: {type: boolean, event: report, title: "Hallazgo: efecto del DIU"}
finding_endometrial_cells: {type: boolean, event: report, title: "Hallazgo: presencia de células endometriales en pacientes de 40 años o más"}
finding_none: {type: boolean, event: report, title: "Hallazgo: ninguno"}
cervical_biopsy:
title: Biopsia cervical
key: [request_date]
events:
order: {date: request_date}
report: {date: report_date, parent: order}
fields:
request_date: {type: date, event: order, title: Fecha de solicitud, required: true}
cytology_sample_date: {type: date, event: order, title: Toma de la citología que la originó}
report_date: {type: date, event: report, title: Fecha de reporte}
histology:
type: code
event: report
title: Histología
system: who-cervical-histology
codes:
normal: Sin lesión
LSIL: Lesión intraepitelial escamosa de bajo grado (CIN 1)
HSIL: Lesión intraepitelial escamosa de alto grado (CIN 2-3)
CIS: Carcinoma in situ
carcinoma: Carcinoma invasor
+134
View File
@@ -0,0 +1,134 @@
# Breast cancer screening.
mammography:
title: Mastografía
key: [exam_date]
events:
sample: {date: exam_date}
report: {date: report_date, parent: sample}
fields:
exam_date: {type: date, event: sample, title: Fecha del estudio, required: true}
report_date: {type: date, event: report, title: Fecha de reporte}
adequacy:
type: code
event: report
title: Calidad de la imagen
system: adequacy
codes: {satisfactory: Satisfactoria, unsatisfactory: Insatisfactoria}
birads:
type: code
event: report
title: BI-RADS
system: bi-rads
codes:
'0': Incompleta, requiere estudios adicionales
'1': Negativa
'2': Hallazgos benignos
'3': Probablemente benigna
'4': Sospechosa
4A: Sospecha baja de malignidad
4B: Sospecha moderada de malignidad
4C: Sospecha alta de malignidad
'5': Altamente sugestiva de malignidad
'6': Malignidad confirmada por biopsia
breast_biopsy:
title: Biopsia de mama
key: [request_date, mammogram_exam_date]
events:
order: {date: request_date}
report: {date: report_date, parent: order}
fields:
request_date: {type: date, event: order, title: Fecha de solicitud, required: true}
mammogram_exam_date: {type: date, event: order, title: Mastografía que la originó}
report_date: {type: date, event: report, title: Fecha de reporte}
histology:
type: code
event: report
title: Histología
system: breast-histology
codes: {benign: Benigno, in_situ: In situ, invasive: Invasor}
histologic_type:
type: code
event: report
title: Tipo histológico (CIE-O-3)
system: icd-o-3
grade:
type: code
event: report
title: Grado histológico (Nottingham)
system: nottingham-grade
codes: {'1': Grado 1, '2': Grado 2, '3': Grado 3}
er:
type: code
event: report
title: Receptor de estrógeno
system: receptor-status
codes: &receptor {positive: Positivo, negative: Negativo}
pr:
type: code
event: report
title: Receptor de progesterona
system: receptor-status
codes: *receptor
her2:
type: code
event: report
title: HER2
system: receptor-status
codes: *receptor
ki67_pct: {type: number, event: report, title: Ki-67, unit: '%'}
size_mm: {type: number, event: report, title: Tamaño del tumor, unit: mm}
positive_nodes: {type: number, event: report, title: Ganglios linfáticos positivos}
stage:
type: code
event: report
title: Estadio clínico (AJCC)
system: ajcc-stage
codes:
'0': Estadio 0
I: Estadio I (sin subgrupo)
II: Estadio II (sin subgrupo)
III: Estadio III (sin subgrupo)
IA: Estadio IA
IB: Estadio IB
IIA: Estadio IIA
IIB: Estadio IIB
IIIA: Estadio IIIA
IIIB: Estadio IIIB
IIIC: Estadio IIIC
IV: Estadio IV
breast_treatment:
title: Tratamiento de cáncer de mama
key: [start_date, kind]
events:
encounter: {date: start_date}
fields:
start_date: {type: date, event: encounter, title: Fecha de inicio, required: true}
kind:
type: code
event: encounter
title: Tratamiento
system: breast-treatment
required: true
codes:
breast_conserving_surgery: Cirugía conservadora
mastectomy: Mastectomía
chemotherapy: Quimioterapia
radiotherapy: Radioterapia
hormone_therapy: Hormonoterapia
anti_her2: Terapia anti-HER2
breast_recurrence:
title: Recurrencia de cáncer de mama
key: [diagnosis_date]
events:
encounter: {date: diagnosis_date}
fields:
diagnosis_date: {type: date, event: encounter, title: Fecha de diagnóstico, required: true}
site:
type: code
event: encounter
title: Sitio de la recurrencia
system: breast-recurrence-site
codes: {local: Local, regional: Regional, distant: A distancia}
+36
View File
@@ -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}
+58
View File
@@ -0,0 +1,58 @@
# 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: Detección de cáncer de cérvix
gynecologic-condition:
url: https://isssteleon.org/fhir/CodeSystem/gynecologic-condition
title: Condición ginecoobstétrica a la detección
presenting-symptom:
url: https://isssteleon.org/fhir/CodeSystem/presenting-symptom
title: Actualmente presenta
cervix-appearance:
url: https://isssteleon.org/fhir/CodeSystem/cervix-appearance
title: A la exploración se observa
bi-rads:
url: https://isssteleon.org/fhir/CodeSystem/bi-rads
title: BI-RADS
icd-10:
url: http://hl7.org/fhir/sid/icd-10
title: CIE-10
external: true
adequacy:
url: https://isssteleon.org/fhir/CodeSystem/adequacy
title: Calidad de la muestra
specialty:
url: https://isssteleon.org/fhir/CodeSystem/specialty
title: Especialidades
breast-histology:
url: https://isssteleon.org/fhir/CodeSystem/breast-histology
title: Histología de mama
ados2-module:
url: https://isssteleon.org/fhir/CodeSystem/ados2-module
title: Módulos del ADOS-2
icd-o-3:
url: http://terminology.hl7.org/CodeSystem/icd-o-3
title: CIE-O-3 (morfología)
external: true
nottingham-grade:
url: https://isssteleon.org/fhir/CodeSystem/nottingham-grade
title: Grado histológico de Nottingham
receptor-status:
url: https://isssteleon.org/fhir/CodeSystem/receptor-status
title: Estado de receptores hormonales y HER2
ajcc-stage:
url: https://isssteleon.org/fhir/CodeSystem/ajcc-stage
title: Estadio clínico AJCC (grupo)
breast-treatment:
url: https://isssteleon.org/fhir/CodeSystem/breast-treatment
title: Tratamientos de cáncer de mama
breast-recurrence-site:
url: https://isssteleon.org/fhir/CodeSystem/breast-recurrence-site
title: Sitio de la recurrencia de cáncer de mama
+60
View File
@@ -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}
-23
View File
@@ -1,23 +0,0 @@
# Catálogos de la plata (F1)
Un TOML por proyecto: estudio → resultado → valor.
El paso `catalogos` de `webapi.orquestacion` los materializa en `cat_estudio`, `cat_resultado` y `cat_valor`
(`core/indicadores/catalogos.py`) antes de cargar. Un valor que sale del TOML pasa a `retirado`; nunca se borra.
```toml
[<estudio>]
etiqueta = "..."
codigos_hospital = ["..."] # cómo lo nombra el hospital (tipo de estudio de la orden, instrumento)
[<estudio>.resultados.<resultado>] # resultado_id = "<estudio>.<resultado>"
etiqueta = "..."
tipo_valor = "codigo" # codigo, booleano, numero, fecha, texto, externo
unidad = "min" # opcional (numero)
sistema = "CIE-10" # solo externo
valores = [ # solo codigo; el orden de la lista es el de presentación
{ valor = "NORMAL", etiqueta = "Normal" },
]
```
Los valores son los que llegan del hospital (los enums de Core). Las etiquetas y los colores de las figuras
siguen en `parametros.toml` del kit hasta F3; `indicadores_kit/tests/test_catalogos.py` exige que coincidan.
-145
View File
@@ -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)" },
]
-100
View File
@@ -1,100 +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" },
]
[biopsia]
etiqueta = "Biopsia de mama"
codigos_hospital = ["BIOPSIA_CHICA"]
[biopsia.resultados.grado]
etiqueta = "Grado histológico"
tipo_valor = "codigo"
valores = [
{ valor = "BENIGNO", etiqueta = "Benigno" },
{ valor = "CARCINOMA_IN_SITU", etiqueta = "Carcinoma in situ" },
{ valor = "CARCINOMA_INVASOR", etiqueta = "Carcinoma invasor" },
{ valor = "DESCONOCIDO", etiqueta = "Desconocido" },
]
[biopsia.resultados.fecha_solicitud]
etiqueta = "Fecha de solicitud"
tipo_valor = "fecha"
[nota_medica]
etiqueta = "Nota médica"
[nota_medica.resultados.diagnostico]
etiqueta = "Diagnóstico"
tipo_valor = "externo"
sistema = "CIE-10"
[nota_medica.resultados.especialidad]
etiqueta = "Especialidad que la escribe"
tipo_valor = "codigo"
valores = [
{ valor = "MEDICINA_FAMILIAR", etiqueta = "Medicina familiar" },
{ valor = "CIRUGIA_ONCOLOGICA", etiqueta = "Cirugía oncológica" },
{ valor = "CLINICA_MUJER_COLPOSCOPIA", etiqueta = "Clínica de la mujer (colposcopia)" },
]
# Los datos de una orden (procedimiento con clase `orden`; su `estudio_id` es el estudio pedido, de
# `codigos_hospital`). ADR-MD-007.
[orden]
etiqueta = "Orden de estudio"
[orden.resultados.intencion]
etiqueta = "Intención (FHIR intent)"
tipo_valor = "texto"
[orden.resultados.fecha_solicitud]
etiqueta = "Fecha para la que se pidió"
tipo_valor = "fecha"
[orden.resultados.fecha_resultado]
etiqueta = "Fecha del resultado"
tipo_valor = "fecha"
[orden.resultados.estatus]
etiqueta = "Estatus de la orden"
tipo_valor = "texto"
[orden.resultados.diagnostico]
etiqueta = "Diagnóstico con que se pidió"
tipo_valor = "texto"
[orden.resultados.especialidad]
etiqueta = "Especialidad que la pidió"
tipo_valor = "codigo"
valores = [
{ valor = "MEDICINA_FAMILIAR", etiqueta = "Medicina familiar" },
{ valor = "CIRUGIA_ONCOLOGICA", etiqueta = "Cirugía oncológica" },
{ valor = "CLINICA_MUJER_COLPOSCOPIA", etiqueta = "Clínica de la mujer (colposcopia)" },
]
-267
View File
@@ -1,267 +0,0 @@
# Catálogo de TEA (F1). Valores: los enums de Core (`core/tea/enums.py`) y lo que guarda la carga.
# Los instrumentos aplicados (M-CHAT-R/F, Ramos) son un estudio cada uno: una aplicación por informante y área.
[evaluacion_psicologica]
etiqueta = "Evaluación psicológica"
codigos_hospital = ["EVALUACION_PSICOLOGICA_TEA"]
[evaluacion_psicologica.resultados.instrumento_tamizaje]
etiqueta = "Instrumento de tamizaje"
tipo_valor = "codigo"
valores = [
{ valor = "M_CHAT_R", etiqueta = "M-CHAT-R" },
{ valor = "M_CHAT_RF", etiqueta = "M-CHAT-R/F" },
{ valor = "OTRO", etiqueta = "Otro" },
{ valor = "NO_REGISTRADO", etiqueta = "No registrado" },
]
[evaluacion_psicologica.resultados.edad_meses]
etiqueta = "Edad del niño"
tipo_valor = "numero"
unidad = "meses"
[evaluacion_psicologica.resultados.fecha_evaluacion]
etiqueta = "Fecha de la evaluación"
tipo_valor = "fecha"
[evaluacion_psicologica.resultados.fecha_entrevista_inicial]
etiqueta = "Fecha de la entrevista inicial"
tipo_valor = "fecha"
[ados2]
etiqueta = "ADOS-2"
[ados2.resultados.css]
etiqueta = "Puntaje de severidad (CSS)"
tipo_valor = "numero"
unidad = "puntos"
[mchat]
etiqueta = "M-CHAT-R/F aplicado"
codigos_hospital = ["M_CHAT_R_F"]
[mchat.resultados.informante]
etiqueta = "Informante"
tipo_valor = "codigo"
valores = [
{ valor = "MADRE", etiqueta = "Madre" },
{ valor = "PADRE", etiqueta = "Padre" },
{ valor = "OTRO_CUIDADOR", etiqueta = "Otro cuidador" },
{ valor = "MAESTRO", etiqueta = "Maestro" },
{ valor = "OBSERVACION_CLINICA", etiqueta = "Observación clínica" },
{ valor = "NO_REGISTRADO", etiqueta = "No registrado" },
]
[mchat.resultados.area]
etiqueta = "Área"
tipo_valor = "codigo"
valores = [
{ valor = "TOTAL", etiqueta = "Total" },
]
[mchat.resultados.interpretacion]
etiqueta = "Interpretación"
tipo_valor = "codigo"
valores = [
{ valor = "RIESGO_BAJO", etiqueta = "Riesgo bajo" },
{ valor = "RIESGO_MEDIO", etiqueta = "Riesgo medio" },
{ valor = "RIESGO_ALTO", etiqueta = "Riesgo alto" },
]
[ramos]
etiqueta = "Escala de Ramos aplicada"
codigos_hospital = ["RAMOS"]
[ramos.resultados.informante]
etiqueta = "Informante"
tipo_valor = "codigo"
valores = [
{ valor = "MADRE", etiqueta = "Madre" },
{ valor = "PADRE", etiqueta = "Padre" },
{ valor = "OTRO_CUIDADOR", etiqueta = "Otro cuidador" },
{ valor = "MAESTRO", etiqueta = "Maestro" },
{ valor = "OBSERVACION_CLINICA", etiqueta = "Observación clínica" },
{ valor = "NO_REGISTRADO", etiqueta = "No registrado" },
]
[ramos.resultados.area]
etiqueta = "Área"
tipo_valor = "codigo"
valores = [
{ valor = "ADAPTATIVO", etiqueta = "Adaptativo" },
{ valor = "COGNOSCITIVO", etiqueta = "Cognoscitivo" },
{ valor = "FISICO", etiqueta = "Físico" },
{ valor = "LINGUISTICO", etiqueta = "Lingüístico" },
{ valor = "SOCIOEMOCIONAL", etiqueta = "Socioemocional" },
{ valor = "TOTAL", etiqueta = "Total" },
]
[ramos.resultados.interpretacion]
etiqueta = "Interpretación"
tipo_valor = "codigo"
valores = [
{ valor = "DESARROLLO_ADECUADO", etiqueta = "Desarrollo adecuado" },
{ valor = "MONITOREO", etiqueta = "Monitoreo" },
{ valor = "RETRASO", etiqueta = "Retraso" },
]
[eeg]
etiqueta = "Electroencefalograma"
codigos_hospital = ["ELECTROENCEFALOGRAMA"]
[eeg.resultados.duracion_min]
etiqueta = "Duración"
tipo_valor = "numero"
unidad = "min"
[eeg.resultados.utilizable]
etiqueta = "Utilizable"
tipo_valor = "booleano"
[eeg.resultados.fecha_nacimiento_archivo]
etiqueta = "Fecha de nacimiento en el archivo del equipo"
tipo_valor = "fecha"
# Un segmento es una parte del EEG (procedimiento con clase `parte`).
[eeg.resultados.estado_segmento]
etiqueta = "Estado del segmento"
tipo_valor = "codigo"
valores = [
{ valor = "NO_MARCADO", etiqueta = "No marcado" },
{ valor = "OJOS_CERRADOS", etiqueta = "Ojos cerrados" },
{ valor = "FOTOESTIMULACION", etiqueta = "Fotoestimulación" },
{ valor = "SUENO", etiqueta = "Sueño" },
]
[eeg.resultados.duracion_segmento]
etiqueta = "Duración del segmento"
tipo_valor = "numero"
unidad = "s"
[pea]
etiqueta = "Potenciales evocados auditivos"
codigos_hospital = ["POTENCIALES_EVOCADOS_AUDITIVOS", "POTENCIALES_EVOCADOS"] # el segundo, como llega (responsable de TEA, 2026-10-21)
[pea.resultados.grado_hipoacusia]
etiqueta = "Grado de hipoacusia"
tipo_valor = "codigo"
valores = [
{ valor = "NORMAL", etiqueta = "Normal" },
{ valor = "LEVE", etiqueta = "Leve" },
{ valor = "MODERADA", etiqueta = "Moderada" },
{ valor = "SEVERA", etiqueta = "Severa" },
{ valor = "PROFUNDA", etiqueta = "Profunda" },
{ valor = "NO_CONCLUYENTE", etiqueta = "No concluyente" },
]
[parto]
etiqueta = "Parto"
[parto.resultados.apgar_5min]
etiqueta = "APGAR a los 5 minutos"
tipo_valor = "numero"
unidad = "puntos"
[parto.resultados.ingreso_ucin]
etiqueta = "Ingreso a UCIN"
tipo_valor = "booleano"
[historia_perinatal]
etiqueta = "Antecedentes maternos de la gestación"
[historia_perinatal.resultados.antecedente_aborto]
etiqueta = "Antecedente de aborto"
tipo_valor = "booleano"
[historia_perinatal.resultados.asma]
etiqueta = "Asma"
tipo_valor = "booleano"
[historia_perinatal.resultados.crisis_convulsivas]
etiqueta = "Crisis convulsivas"
tipo_valor = "booleano"
[historia_perinatal.resultados.diabetes_gestacional]
etiqueta = "Diabetes gestacional"
tipo_valor = "booleano"
[historia_perinatal.resultados.embarazo_multiple]
etiqueta = "Embarazo múltiple"
tipo_valor = "booleano"
[historia_perinatal.resultados.enfermedad_autoinmune]
etiqueta = "Enfermedad autoinmune"
tipo_valor = "booleano"
[historia_perinatal.resultados.estres_agudo]
etiqueta = "Estrés agudo"
tipo_valor = "booleano"
[historia_perinatal.resultados.farmaco_riesgo_neurodesarrollo]
etiqueta = "Fármaco de riesgo para el neurodesarrollo"
tipo_valor = "booleano"
[historia_perinatal.resultados.hipertension_preeclampsia]
etiqueta = "Hipertensión o preeclampsia"
tipo_valor = "booleano"
[historia_perinatal.resultados.hipertiroidismo]
etiqueta = "Hipertiroidismo"
tipo_valor = "booleano"
[historia_perinatal.resultados.hipotiroidismo]
etiqueta = "Hipotiroidismo"
tipo_valor = "booleano"
[historia_perinatal.resultados.hipoxia_materna]
etiqueta = "Hipoxia materna"
tipo_valor = "booleano"
[historia_perinatal.resultados.incompatibilidad_rh]
etiqueta = "Incompatibilidad Rh"
tipo_valor = "booleano"
[historia_perinatal.resultados.infeccion_gestacion]
etiqueta = "Infección en la gestación"
tipo_valor = "booleano"
[historia_perinatal.resultados.liquido_amniotico]
etiqueta = "Alteración del líquido amniótico"
tipo_valor = "booleano"
[historia_perinatal.resultados.migrana]
etiqueta = "Migraña"
tipo_valor = "booleano"
[historia_perinatal.resultados.proceso_proinflamatorio]
etiqueta = "Proceso proinflamatorio"
tipo_valor = "booleano"
[historia_perinatal.resultados.tabaquismo_gestacion]
etiqueta = "Tabaquismo en la gestación"
tipo_valor = "booleano"
[historia_perinatal.resultados.trastorno_neurologico]
etiqueta = "Trastorno neurológico"
tipo_valor = "booleano"
[nota_medica]
etiqueta = "Nota médica"
[nota_medica.resultados.diagnostico]
etiqueta = "Diagnóstico"
tipo_valor = "externo"
sistema = "CIE-10"
# Los datos de una orden (procedimiento con clase `orden`; su `estudio_id` es el estudio pedido, de
# `codigos_hospital`). ADR-MD-007.
[orden]
etiqueta = "Orden de estudio"
[orden.resultados.intencion]
etiqueta = "Intención (FHIR intent)"
tipo_valor = "texto"
[orden.resultados.fecha_realizacion]
etiqueta = "Fecha de realización"
tipo_valor = "fecha"
-12
View File
@@ -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 {}
+544
View File
@@ -0,0 +1,544 @@
"""Platform rows as FHIR R4B resources (pure, no IO), and the conformance resources that
declare what ours are: the local code systems, our extensions and our search parameters.
Every mapper builds a `fhir.resources.R4B` model, so a resource that breaks FHIR's structure
fails here, before it is served. Clinical resources other than Patient are found by search
only; their ids are stable (a UUID of their natural key), not addresses.
"""
import uuid
from collections.abc import Iterable
from datetime import UTC, date, datetime
from fhir.resources.R4B.codesystem import CodeSystem
from fhir.resources.R4B.condition import Condition
from fhir.resources.R4B.diagnosticreport import DiagnosticReport
from fhir.resources.R4B.encounter import Encounter
from fhir.resources.R4B.measure import Measure
from fhir.resources.R4B.observation import Observation
from fhir.resources.R4B.patient import Patient
from fhir.resources.R4B.procedure import Procedure
from fhir.resources.R4B.resource import Resource
from fhir.resources.R4B.riskassessment import RiskAssessment
from fhir.resources.R4B.searchparameter import SearchParameter
from fhir.resources.R4B.structuredefinition import StructureDefinition
from core import catalog, models
FHIR_VERSION = "4.3.0"
BASE = "https://isssteleon.org/fhir"
EXTENSION = f"{BASE}/StructureDefinition/"
CODES = f"{BASE}/CodeSystem/"
ICD10 = "http://hl7.org/fhir/sid/icd-10"
UCUM = "http://unitsofmeasure.org"
_IDS = uuid.uuid5(uuid.NAMESPACE_URL, BASE)
# Local code systems: code -> display (Spanish, as the screens show them).
CODE_SYSTEMS: dict[str, tuple[str, dict[str, str]]] = {
"cacu-procedure": ("Procedimientos de CaCu", {
"colposcopy": "Colposcopia", "treatment": "Tratamiento",
}),
"cacu-follow-up-status": ("Estatus de seguimiento", {
"case": "Caso (cáncer)", "pre_colposcopy": "Pre colposcopia",
"post_colposcopy": "Post colposcopia", "post_treatment": "Post tratamiento",
}),
"cama-follow-up-status": ("Estatus de seguimiento", {
"cancer": "Diagnóstico confirmado", "pending_biopsy": "Pendiente de biopsia",
"biopsy_no_result": "Biopsia sin resultado", "benign_biopsy": "Biopsia benigna",
}),
"tea-follow-up-status": ("Estatus de seguimiento", {
"mchat_only": "Solo M-CHAT", "psychology": "Hasta evaluación psicológica",
"neuropediatrics": "Hasta evaluación neuropediátrica", "eeg": "Con EEG",
}),
"tea-case": ("Estado del caso", {
"confirmed": "Diagnóstico confirmado", "in_process": "En proceso",
"not_confirmed": "Sin TEA",
}),
"tea-eeg-status": ("Estatus de EEG", {
"normal": "Normal", "abnormal": "Anormal", "no_valid_eeg": "Sin EEG válido",
}),
# an EEG metric outside its age band: `<metric>:above` or `<metric>:below`
"tea-eeg-alteration": ("Alteración del EEG", {}),
"follow-up-priority": ("Prioridad de seguimiento", {
"high": "Alta", "medium": "Media", "low": "Baja",
}),
"measure-stratifier": ("Estratos de indicadores", {
"category": "Categoría", "age_group": "Grupo de edad",
"follow_up_status": "Estatus de seguimiento", "result": "Citología de alto grado",
"birads": "BI-RADS de la mastografía", "diagnosis_code": "Diagnóstico CIE-10",
"cytology": "Citología previa", "hpv": "VPH de la citología previa",
"level": "Histología confirmada", "round": "Tamizaje inicial o subsecuente",
"hpv_16": "VPH 16", "hpv_18": "VPH 18",
}),
"risk-model": ("Modelos de riesgo", {}), # open: a model's name is its code
} # fmt: skip
def _catalog_systems() -> dict[str, tuple[str, dict[str, str]]]:
"""The catalog's own code systems, with every code some field allows."""
found: dict[str, tuple[str, dict[str, str]]] = {}
for name, system in catalog.systems().items():
if not system.external:
codes = {c: d for s in catalog.studies().values() for f in s.fields.values()
if f.system == name for c, d in f.codes.items()} # fmt: skip
found[name] = (system.title, codes)
return found
CODE_SYSTEMS |= _catalog_systems()
CODE_SYSTEMS["cama-procedure"] = ("Procedimientos de CaMa", CODE_SYSTEMS["breast-treatment"][1])
# What the catalog names: its studies, and every field as `<study>.<field>`.
CODE_SYSTEMS["study"] = ("Estudios", {n: s.title for n, s in catalog.studies().items()})
CODE_SYSTEMS["catalog-field"] = ("Campos de los estudios", {
f"{n}.{f}": d.title for n, s in catalog.studies().items() for f, d in s.fields.items()
}) # fmt: skip
# Where a duration is scored: the whole, and each stratum with a score of its own.
DURATIONS = ["MeasureReport.group.measureScore",
"MeasureReport.group.stratifier.stratum.measureScore"] # 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", DURATIONS),
"q3": ("decimal", DURATIONS),
"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"]),
# what followed a cytology: colposcopy and diagnosis are inferred; `biopsy-link` says
# whether the biopsy's record names the cytology (recorded) or its dates do (inferred)
"colposcopy-date": ("date", ["DiagnosticReport"]),
"biopsy-request-date": ("date", ["DiagnosticReport"]),
"biopsy-date": ("date", ["DiagnosticReport"]),
"biopsy-link": ("code", ["DiagnosticReport"]),
"diagnosis-date": ("date", ["DiagnosticReport"]),
# a clinical scenario of the model's report the person falls in (its curves)
"escenario-clinico": ("string", ["RiskAssessment"]),
# a child on TEA's list: her age group, case, EEG and scores
"tea-age-group": ("string", ["Patient"]),
"tea-case": ("Coding", ["Patient"]),
"tea-eeg-status": ("Coding", ["Patient"]),
"tea-eeg-alteration": ("Coding", ["Patient"]),
"tea-last-eeg": ("date", ["Patient"]),
"mchat-score": ("integer", ["Patient"]),
"ados2-css": ("integer", ["Patient"]),
} # fmt: skip
def _name(code: str) -> str:
"""A conformance resource's computable name (CamelCase)."""
return "".join(part.capitalize() for part in code.replace("_", "-").split("-"))
def _id(*key) -> str:
return str(uuid.uuid5(_IDS, "|".join(str(k) for k in key)))
def _day(value) -> str | None:
if value is None:
return None
return value.isoformat()[:10] if isinstance(value, date) else str(value)[:10]
def _instant(value) -> str | None:
"""A stored moment as an instant; one stored without an offset is UTC."""
if value is None:
return None
found = value if isinstance(value, datetime) else datetime.fromisoformat(str(value))
return (found if found.tzinfo else found.replace(tzinfo=UTC)).isoformat()
def coding(system: str, code: str) -> dict:
display = CODE_SYSTEMS[system][1].get(code) if system in CODE_SYSTEMS else None
return {"system": CODES + system, "code": code, **({"display": display} if display else {})}
def concept(system: str, code: str) -> dict:
found = coding(system, code)
return {"coding": [found], "text": found.get("display", code)}
def ext(name: str, value_type: str, value) -> dict:
return {"url": EXTENSION + name, f"value{value_type[0].upper()}{value_type[1:]}": value}
# A report's facts (a domain's `REPORT_FACTS` read): their column -> the extension.
_REPORT_FACTS = {"days": "days-to-diagnosis", "colposcopy": "colposcopy-date",
"requested": "biopsy-request-date", "biopsy": "biopsy-date",
"link": "biopsy-link", "diagnosis": "diagnosis-date"} # fmt: skip
def report_facts(row: dict) -> list[dict]:
found = []
for column, name in _REPORT_FACTS.items():
if (value := row.get(column)) is not None:
kind = EXTENSIONS[name][0]
found.append(ext(name, kind, {"integer": int, "date": _day}.get(kind, str)(value)))
return found
def subject(person_id: str) -> dict:
return {"reference": f"Patient/{person_id}"}
# --- clinical resources ----------------------------------------------------------------
def patient(row: dict, status_system: str | None = None) -> Patient:
"""A person: what her records agree on, her names and identifiers, the ids she
replaced; on a follow-up list, her status there (`status_system`) and priority."""
found: dict = {"resourceType": "Patient", "id": row["person_id"]}
if row.get("sex"):
found["gender"] = row["sex"]
if row.get("birth_date"):
found["birthDate"] = _day(row["birth_date"])
if row.get("death_date"):
found["deceasedDateTime"] = _day(row["death_date"])
if row.get("status") and status_system:
found["extension"] = [ext("follow-up-status", "Coding",
coding(status_system, row["status"]))] # fmt: skip
if row.get("priority"):
priority = coding("follow-up-priority", row["priority"])
found["extension"].append(ext("follow-up-priority", "Coding", priority))
found.setdefault("extension", []).extend(_tea_listed(row))
if not found["extension"]:
del found["extension"]
if row.get("names"):
found["name"] = [{"text": n} for n in row["names"]]
if row.get("identifiers"):
found["identifier"] = [{"system": s, "value": v} for s, v in row["identifiers"]]
if row.get("replaces"):
found["link"] = [{"other": {"reference": f"Patient/{old}"}, "type": "replaces"}
for old in row["replaces"]] # fmt: skip
return Patient.model_validate(found)
def _tea_listed(row: dict) -> list[dict]:
"""What TEA's list shows of a child, when she is on it (core.tea.follow_up)."""
found = []
if row.get("age_group"):
found.append(ext("tea-age-group", "string", row["age_group"]))
for key, system in (("case", "tea-case"), ("eeg_status", "tea-eeg-status")):
if row.get(key):
found.append(ext(system, "Coding", coding(system, row[key])))
for altered in row.get("alterations") or []:
found.append(ext("tea-eeg-alteration", "Coding", coding("tea-eeg-alteration", altered)))
if row.get("last_eeg"):
found.append(ext("tea-last-eeg", "date", _day(row["last_eeg"])))
for key, name in (("mchat_score", "mchat-score"), ("ados2_css", "ados2-css")):
if row.get(key) is not None:
found.append(ext(name, "integer", int(row[key])))
return found
def replaced_patient(person_id: str, replaced_by: str) -> Patient:
"""A person a review merged into another: no longer active, pointing at who replaced
her, so her id keeps resolving."""
return Patient.model_validate({
"resourceType": "Patient", "id": person_id, "active": False,
"link": [{"other": {"reference": f"Patient/{replaced_by}"}, "type": "replaced-by"}],
}) # fmt: skip
def _value(f: catalog.FieldDef, value) -> dict:
"""A field's value as the Observation value of its type."""
if f.type == "code":
system = catalog.systems()[f.system]
if system.external:
return {"valueCodeableConcept": {"coding": [{"system": system.url, "code": value}],
"text": value}} # fmt: skip
return {"valueCodeableConcept": concept(f.system, value)}
if f.type == "boolean":
return {"valueBoolean": bool(value)}
if f.type == "number":
return {"valueQuantity": {"value": value, **({"unit": f.unit} if f.unit else {})}}
if f.type == "date":
return {"valueDateTime": _day(value)}
return {"valueString": str(value)}
def known(study: str, row: dict, cutoff) -> dict:
"""A study instance as the platform knew it by the end of `cutoff`: the fields of an
event that has no date yet, or a later one, are not known."""
spec = catalog.studies()[study]
out = dict(row)
for cls, event in spec.events.items():
day = _day(row.get(event.date))
if event.parent is not None and (day is None or day > _day(cutoff)):
for name, f in spec.fields.items():
if f.event == cls:
out[name] = None
return out
def instance(study: str, row: dict, report_extensions: Iterable[dict] = ()) -> list[Resource]:
"""One study instance (a row of `silver.<study>`) as FHIR, from the catalog: an
Observation per field that is not an event's date, and, when the study has a report,
the DiagnosticReport that gathers them."""
spec = catalog.studies()[study]
person = row["person_id"]
key = [_day(row[k]) if spec.fields[k].type == "date" else row[k] for k in spec.key]
dates = {e.date for e in spec.events.values()}
root = next(e for e in spec.events.values() if e.parent is None)
effective = _day(row.get(root.date))
container = _id(study, person, *key) # its report, or the encounter its notes are of
visit = "report" not in spec.events
observations = []
for name, f in spec.fields.items():
if name in dates or row.get(name) is None or f.type == "file":
continue
observations.append(Observation.model_validate({
"resourceType": "Observation",
"id": _id(study, name, person, *key),
"status": "final",
"code": concept("catalog-field", f"{study}.{name}"),
"subject": subject(person),
**({"encounter": {"reference": f"Encounter/{container}"}} if visit else {}),
**({"effectiveDateTime": effective} if effective else {}),
**_value(f, row[name]),
})) # fmt: skip
if visit: # a study without a report (a consultation): the encounter its values are of
if not observations:
return []
encounter = Encounter.model_validate({
"resourceType": "Encounter", "id": container, "status": "finished",
"class": {"system": "http://terminology.hl7.org/CodeSystem/v3-ActCode",
"code": "AMB"},
"type": [concept("study", study)],
"subject": subject(person),
**({"period": {"start": effective}} if effective else {}),
}) # fmt: skip
return [encounter, *observations]
reported = _day(row.get(spec.events["report"].date))
extensions = ([ext("report-date", "date", reported)] if reported else []) + list(
report_extensions
)
report = DiagnosticReport.model_validate({
"resourceType": "DiagnosticReport",
"id": container,
"status": "final" if reported else "registered",
"code": concept("study", study),
"subject": subject(person),
**({"effectiveDateTime": effective} if effective else {}),
**({"extension": extensions} if extensions else {}),
"result": [{"reference": f"Observation/{o.id}"} for o in observations] or None,
}) # fmt: skip
return [report, *observations]
def condition(row: dict) -> Condition:
"""What a clinical note diagnosed (`silver.clinical_note`), by ICD-10 or as written; or
a study of the catalog that is a diagnosis (`study`: a breast recurrence), by its name
and its coded field (`code`: where it recurred)."""
person, day = row["person_id"], _day(row["note_date"])
code: dict = {"text": row.get("diagnosis_text") or row.get("icd10")}
if row.get("icd10"):
code["coding"] = [{"system": ICD10, "code": row["icd10"]}]
if study := row.get("study"):
code = concept("study", study)
system = next((f.system for f in catalog.studies()[study].fields.values()
if f.type == "code"), None) # fmt: skip
if system and row.get("code"):
where = coding(system, row["code"])
code["coding"].append(where)
code["text"] += f" ({where.get('display', row['code']).lower()})"
found: dict = {
"resourceType": "Condition",
"id": _id("condition", person, day, row.get("specialty") or study),
"category": [{"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/condition-category",
"code": "encounter-diagnosis"}]}],
"code": code,
"subject": subject(person),
"recordedDate": day,
} # fmt: skip
if row.get("reason"):
found["note"] = [{"text": row["reason"]}]
return Condition.model_validate(found)
def procedure(row: dict, domain: str = "cacu") -> Procedure:
"""A procedure the timeline inferred (`gold.<domain>_events`; CaCu: colposcopy,
treatment; CaMa: each treatment by its kind), coded in `<domain>-procedure`."""
person, day = row["person_id"], _day(row["date"])
return Procedure.model_validate({
"resourceType": "Procedure",
"id": _id("procedure", row["type"], person, day),
"status": "completed",
"code": concept(f"{domain}-procedure", row["type"]),
"subject": subject(person),
"performedDateTime": day,
}) # fmt: skip
SCENARIO_SEPARATOR = " | " # as models.survival joins them
def risk_assessment(row: dict, horizons: Iterable[dict]) -> RiskAssessment:
"""A model's risk for one person at her index date (`gold.cacu_risk`): one prediction
per horizon, in years, with its 95% interval; and the clinical scenarios of the model's
report she falls in (an extension each), for her record to draw their curves."""
predictions = []
for h in sorted(horizons, key=lambda h: h["horizon_years"]):
bounds = (("ic-bajo", "ci_low"), ("ic-alto", "ci_high"))
interval = [ext(name, "decimal", h[key]) for name, key in bounds
if h.get(key) is not None] # fmt: skip
predictions.append({
"probabilityDecimal": h["probability"],
"whenRange": {"high": {"value": h["horizon_years"], "unit": "a", "system": UCUM,
"code": "a"}},
**({"extension": interval} if interval else {}),
}) # fmt: skip
model = row["model"]
return RiskAssessment.model_validate({
"resourceType": "RiskAssessment",
"id": _id("risk", model, row["version"], row["person_id"], _day(row["index_date"])),
"meta": {"lastUpdated": _instant(row["scored_at"])},
"status": "final",
"method": {"coding": [{"system": CODES + "risk-model", "code": model,
"display": models.title(model)}],
"text": f"{models.title(model)} v{row['version']}"},
"subject": subject(row["person_id"]),
"occurrenceDateTime": _day(row["index_date"]),
"prediction": predictions,
**({"extension": [ext("escenario-clinico", "string", name) for name in scenarios]}
if (scenarios := [n for n in (row.get("scenarios") or "").split(SCENARIO_SEPARATOR)
if n]) else {}),
}) # fmt: skip
SCORING = {"proportion": "proportion", "continuous-variable": "continuous-variable",
"composition": "cohort"} # fmt: skip
def measure_id(code: str) -> str:
"""A measure's FHIR id (ids allow no underscore)."""
return code.lower().replace("_", "-")
def measure_url(code: str) -> str:
return f"{BASE}/Measure/{code}"
# The populations each kind of measure counts (core.measures emits exactly these).
POPULATIONS = {"proportion": ["initial-population", "denominator", "numerator"],
"continuous-variable": ["initial-population", "measure-observation"],
"composition": ["initial-population", "measure-observation"]} # fmt: skip
POPULATION = "http://terminology.hl7.org/CodeSystem/measure-population"
def stratifiers(m) -> list[str]:
"""A measure's strata: a composition's categories first, then its declared strata."""
first = ["category"] if m.rule.kind == "composition" else []
return first + [name for name, _ in getattr(m.rule, "strata", ())]
def stratifier_code(name: str) -> dict:
return concept("measure-stratifier", name)
def measure(m, domain: str) -> Measure:
"""A measure definition (`core.measures.Measure`): how it is computed is Core's code,
which `criteria` points to."""
criteria = {"language": "text/x-python",
"expression": f"core.{domain}.measures.MEASURES['{m.id}']"} # fmt: skip
group: dict = {
"id": m.group,
"population": [{"code": {"coding": [{"system": POPULATION, "code": c}]},
"criteria": criteria} for c in POPULATIONS[m.rule.kind]],
} # fmt: skip
if strata := stratifiers(m):
group["stratifier"] = [{"id": s, "code": stratifier_code(s), "criteria": criteria}
for s in strata] # fmt: skip
found: dict = {
"resourceType": "Measure",
"id": measure_id(m.id),
"url": measure_url(m.id),
"version": m.version,
"name": m.id,
"title": m.title,
"status": "active",
"scoring": {"coding": [{"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": SCORING[m.rule.kind]}]},
"extension": [ext("period-type", "code", p) for p in m.periods],
"group": [group],
} # fmt: skip
if m.description:
found["description"] = m.description
if m.improvement:
found["improvementNotation"] = {"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": m.improvement}]} # fmt: skip
return Measure.model_validate(found)
# --- conformance: what our resources declare ---------------------------------------------
def code_systems() -> list[CodeSystem]:
return [CodeSystem.model_validate({
"resourceType": "CodeSystem", "id": name, "url": CODES + name,
"name": _name(name),
"title": title, "status": "active", "caseSensitive": True,
"content": "complete" if concepts else "not-present",
"concept": [{"code": c, "display": d} for c, d in concepts.items()],
}) for name, (title, concepts) in CODE_SYSTEMS.items()] # fmt: skip
def extensions() -> list[StructureDefinition]:
found = []
for name, (value_type, contexts) in EXTENSIONS.items():
url = EXTENSION + name
found.append(StructureDefinition.model_validate({
"resourceType": "StructureDefinition", "id": name, "url": url,
"name": _name(name), "status": "active", "fhirVersion": FHIR_VERSION,
"kind": "complex-type", "abstract": False, "type": "Extension",
"context": [{"type": "element", "expression": c} for c in contexts],
"baseDefinition": "http://hl7.org/fhir/StructureDefinition/Extension",
"derivation": "constraint",
"differential": {"element": [
{"id": "Extension", "path": "Extension", "max": "*" if name == "period-type"
else "1"},
{"id": "Extension.extension", "path": "Extension.extension", "max": "0"},
{"id": "Extension.url", "path": "Extension.url", "fixedUri": url},
{"id": "Extension.value[x]", "path": "Extension.value[x]", "min": 1,
"type": [{"code": value_type}]},
]},
})) # fmt: skip
return found
# Our search parameters: code -> (resource, type, description).
SEARCH_PARAMETERS: dict[str, tuple[str, str, str]] = {
"follow-up-status": ("Patient", "token", "Follow-up status at the cut-off"),
"follow-up-cutoff": ("Patient", "date", "The day the follow-up list is taken at"),
"follow-up-window": ("Patient", "number",
"Months before the cut-off a cytology puts a patient on the list"),
"recent": ("Patient", "date", "Her latest cytology in the window (sort only)"),
"risk-cin2": ("Patient", "number", "Her current CIN2+ risk (sort only)"),
"risk-cancer": ("Patient", "number", "Her current cancer risk (sort only)"),
"risk-horizon": ("Patient", "number", "The horizon, in years, risks are sorted at"),
"reporting-period": ("MeasureReport", "token",
"A semester (2025-S1) or a month (2025-03) the report covers"),
"as-of": ("MeasureReport", "date", "Count only what the platform knew by then"),
"event-cutoff": ("MeasureReport", "date", "Durations count to this day"),
} # fmt: skip
def search_parameters() -> list[SearchParameter]:
return [SearchParameter.model_validate({
"resourceType": "SearchParameter", "id": code,
"url": f"{BASE}/SearchParameter/{code}", "name": _name(code),
"status": "active", "description": description, "code": code, "base": [base],
"type": kind,
}) for code, (base, kind, description) in SEARCH_PARAMETERS.items()] # fmt: skip
def conformance() -> list[Resource]:
"""Everything our resources declare: what the validator loads, and what the
CapabilityStatement points to."""
return [*code_systems(), *extensions(), *search_parameters()]
+157
View File
@@ -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.
"""
-29
View File
@@ -1,29 +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"
ONNX_CHECKPOINT = "ONNX_CHECKPOINT"
OTRO = "OTRO"
class EstatusExtraccion(str, Enum):
"""VAR-07/VAR-09: status of an extraction run."""
EN_PROGRESO = "EN_PROGRESO"
COMPLETADA = "COMPLETADA"
FALLIDA = "FALLIDA"
@@ -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",
]
View File

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