Compare commits

...

264 Commits

Author SHA1 Message Date
Angel Capetillo Zavala cfd90fe3a5 Fija segundo punto de recuperación CaCu 2026-11-26 14:05:58 -06:00
Angel Capetillo Zavala 013cd3d99b Fija WebApi y WebApp para actualización CaCu 2026-11-26 12:50:09 -06:00
Angel Capetillo Zavala 0b69165c31 Agrega distribución de VPH por genotipo en CaCu 2026-11-26 12:48:31 -06:00
ulises 0b514feca8 Submodule URLs relative to this repository's remote 2026-11-23 20:02:09 -06:00
alberto 1c41e21e03 Merge pull request 'WebApi and WebApp pointers: results of one EDF and its ADOS-2 report without storing them' (#26) from feature/tea-eeg-analysis into dev 2026-11-23 12:28:07 -06:00
ulises 1c3947e2f5 WebApi and WebApp pointers: the results of one EDF and its ADOS-2 report without storing them 2026-11-23 12:27:19 -06:00
alberto b01adbb75f Merge pull request 'TEA EEG in Gobernanza: settings, manual and pointers' (#25) from feature/tea-eeg-analysis into dev 2026-11-23 09:38:37 -06:00
ulises 26ac614c9c TEA EEG in Gobernanza: dist settings and manual; WebApi, WebApp and models pointers 2026-11-23 09:34:18 -06:00
edgar c66d9207e2 Merge pull request 'CaCu: recruitment window from 2018, every patient's current risks at once, and the submodule pointers' (#24) from integration/cacu-197-conciliacion into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/24
2026-11-23 01:09:29 -06:00
edgar 1e06f93ec6 CaCu: the recruitment window starts in 2018, as CaMa's
Survival fits one model per interval of 12, 36 and 60 months and needs patients followed that long. From 2024 nobody
reaches 36 months of follow-up before the cut-off, so the last two intervals have no patients and the fit fails.
From 2018 there are 85, 40 and 15 patients at risk in the three intervals.
2026-11-23 00:53:41 -06:00
edgar 914b5147c2 Merge dev into the CaCu integration branch 2026-11-23 00:45:12 -06:00
Roberto Treviño Cervantes 3743ea694e Update models and WebApi pins: the cycle no longer batch-scores CaMa recurrence 2026-11-23 00:14:16 -06:00
Roberto Treviño Cervantes 320b7f972b Update WebApp pin: CaMa labels from dev with the optional adjusted Kaplan-Meier 2026-11-23 00:10:04 -06:00
Roberto Treviño Cervantes 7422d48c84 Update models, WebApi and WebApp pins: CaMa survival points all from the pipeline's survival stage; measures answered after each cycle 2026-11-23 00:09:49 -06:00
edgar c56111d440 Submodule pointers: CaCu risk intervals, follow-up status and patient record
models, WebApi and WebApp at the merge of their CaCu pull requests.
2026-11-22 23:32:05 -06:00
edgar 134244d2d0 Merge dev into the CaCu integration branch 2026-11-22 23:31:54 -06:00
Roberto Treviño Cervantes 6dc6a97ae4 Merge dev into the CaMa consolidation branch 2026-11-22 23:31:42 -06:00
Roberto Treviño Cervantes 60f550c6b2 Update models and WebApi pins: CaMa survival points recomputed by the indicators cycle 2026-11-22 23:22:31 -06:00
Roberto Treviño Cervantes 162ad66716 Update models and WebApi pins: CaMa survival figure from the pipeline's subgroup results 2026-11-22 22:59:48 -06:00
Roberto Treviño Cervantes 17fb0f8bb2 Update WebApi pin: CaMa follow-up cohort cached by revision 2026-11-22 22:20:13 -06:00
alberto 07f1afedca Merge pull request 'Submodule pointers: TEA ADOS-2 scoring and indicators tabs' (#23) from feature/tea-eeg-analysis into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/23
2026-11-22 22:12:57 -06:00
ulises 995435da89 WebApp pointer: merge of the TEA labels and sections branch 2026-11-22 22:11:40 -06:00
Roberto Treviño Cervantes 4debce6892 Update WebApi pin: live models load from the cycle's file 2026-11-22 22:02:04 -06:00
ulises 5f18e7d05a Submodule pointers: ADOS-2 scoring in the cycle and models, TEA indicators tabs 2026-11-22 22:01:54 -06:00
ulises b789f70a84 Extraction: score tables, the ADOS-2 table found by its heading and item coverage, the module inferred from its items, totals checked; WebApi pointer 2026-11-22 21:47:23 -06:00
ulises ec7b6de4e7 TEA: eeg_metrica_zona, the ADOS-2 item map in dbt, the relation view and the submodules for the ADOS-2 association 2026-11-22 21:47:22 -06:00
Roberto Treviño Cervantes 28534c5290 Update WebApi and WebApp pins: CaMa patient header and survival scenario from her data 2026-11-22 21:38:43 -06:00
Roberto Treviño Cervantes ce467e87e3 Update models and WebApi pins: CaMa recurrence reads the database 2026-11-22 19:51:21 -06:00
Roberto Treviño Cervantes 839bfcc781 Update WebApp pin for the Seguimiento tab 2026-11-22 18:10:48 -06:00
Roberto Treviño Cervantes 1f1d32aa57 CaMa window to the end of the year; pins for the recurrence and survival changes 2026-11-22 18:04:58 -06:00
Roberto Treviño Cervantes 18b8b0a395 Update models and WebApp pins: CaMa survival reads stage and treatments, one survival panel 2026-11-22 16:22:06 -06:00
edgar 49b6725a02 Persistance: every patient's current risks at once
`CohortRepository.current_risks_by_patient` gives, per outcome and patient, the horizons of the newest confirmed batch
that scored her, the same as `current_risks` one by one, for lists of many patients where a query per patient is too
slow.
2026-11-22 15:03:55 -06:00
edgar fc1fdf64d2 Merge pull request 'CaCu: diagnosis and treatment windows, per-outcome current risks, submodule pointers' (#22) from integration/cacu-197-conciliacion into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/22
2026-11-22 13:47:36 -06:00
Roberto Treviño Cervantes 6a652466f2 CaMa clinical scenario: a treatment encounter after the malignant diagnosis is post-treatment evidence 2026-11-22 10:16:34 -06:00
edgar a0fe4fc51c Submodule pointers: CaCu cancer PIM, one risk per outcome on the patient's record, single risk-batch decisions 2026-11-22 09:35:12 -06:00
edgar 0e88a11db8 Persistance: a patient's current batch of each outcome, and the domain's
`CohortRepository.current_risks` gives the patient's current batch of each outcome (`desenlace`), newest first, so a
CIN2+ and a cancer model are both current; `current_risk` is its first. `current_batches` gives the domain's current
batch of each outcome whoever it scored, which tells a patient a model of that outcome exists although it didn't
score her.
2026-11-22 09:35:12 -06:00
Roberto Treviño Cervantes 7c74978f38 Update WebApp pin for the CaMa SEER survival panel 2026-11-22 09:22:15 -06:00
Roberto Treviño Cervantes 67cbb3ff31 Merge the CaMa survival and recurrence work into dev, with the CaMa migration heads joined 2026-11-22 09:19:49 -06:00
ulises 0e2a5d92cf CaMa recurrence: bronze variables, follow-up table, catalog, timeline and submodule pointers
The patient carries the menopausal state, molecular and clinical subtype, integrative cluster, cellularity, mutation load,
Ki-67 category and source of the record; `seguimientomama` holds the recurrence and the last contact; hormone and anti-HER2
therapy are treatments, with an explicit "no treatment" value. One alembic revision on survival's chain, the catalog
studies and the timeline entries. Includes the survival bronze and total-cohort work this builds on.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 08:47:00 -06:00
edgar 101f14479f Submodule pointers: CaCu PIM risk intervals, estimand and latest-cytology index; pipeline drawings 2026-11-22 07:58:35 -06:00
edgar 7dad5d0862 CaCu: the sample-to-diagnosis window is 120 days and the sample-to-treatment one 180
The steps of the route are chained, so the times from the sample take longer than each step's own 60 days.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 04:37:22 -06:00
edgar 57d06b34f2 Merge pull request 'CaCu indicators integration: survival, times along the screening route and submodule pointers' (#21) from integration/cacu-indicadores into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/21
2026-11-22 01:01:50 -06:00
edgar ab3163c21c Pin models, WebApi and WebApp to the CaCu indicators integration
The survival reports and the notebooks kept in the code, the times along the screening route, the interval of a
proportion's score and the route chart.
2026-11-22 00:28:43 -06:00
edgar d7a2af15a6 feat(cacu): add the times along the screening route
A model with one row per cytology follows the route: the first colposcopy after the sample, the first biopsy report
the sample led to, and the three steps between consecutive events (cytology result to colposcopy, colposcopy to
biopsy report, biopsy report to diagnosis). Five measures publish them with their windows, 60 days, provisional.
2026-11-22 00:23:42 -06:00
edgar 4a04f411c0 feat(cacu): add the times from sample and from diagnosis to treatment
A macro finds the first event of a kind after each start, for the same patient, within a horizon. The diagnosis
lookup of cacu_tomas_citologia uses it with the same result, and two more calls give the days from the sample to
the first treatment and from its diagnosis to it. Both horizons are 60 days, provisional.
2026-11-22 00:23:42 -06:00
edgar a381d6dc7f CaCu timeline: birth and death from persona; the total cohort's index leaves them out
cacu_linea_de_tiempo emits `nacimiento` and `defuncion` from silver's persona, as CaMa's timeline does: the age and
the outcome of the CaCu survival scenario (models: cacu-survival/integration). `persona.fecha_defuncion` came with
migration c3d8f5a20b47.

They are not clinical events, so cacu_total_index_date indexes at the first event whose source isn't `persona`, as
cama_total_index_date does; otherwise every patient's birth would be her index. Its unit test adds an earlier birth
that must not set it. Every other CaCu reader of the timeline filters by type. On the same test database, dbt build of
cacu passes (18/18) and, against dev, only the timeline changes (one row per birth and per death): the total,
surveillance and post-colposcopy cohorts and every gold model are identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-22 00:23:42 -06:00
angel 1a3ee4a06c Merge pull request 'CaMa integration: total cohort in dbt, joined migration heads, submodule pointers' (#18) from feature/cama-roundtrip into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/18
2026-11-21 15:03:54 -06:00
rockdrigo 0989e6f063 Submodule pointers: recurrence only after treatment 2026-11-21 14:57:31 -06:00
rockdrigo b9e73d5a5a Submodule pointers: CaMa record layout 2026-11-21 14:43:46 -06:00
rockdrigo 06bd9cfc2e TEA: the heads of the TEA migration chain joined 2026-11-21 14:05:52 -06:00
rockdrigo 86177fa45e Merge origin/dev 2026-11-21 14:01:11 -06:00
rockdrigo dc0c493af4 Submodule pointers: WebApp follows dev 2026-11-21 13:53:49 -06:00
rockdrigo 8313623c63 Submodule pointers: recurrence CLI fix 2026-11-21 13:43:19 -06:00
rockdrigo 152aa3cca3 Submodule pointers: recurrence test 2026-11-21 13:41:16 -06:00
rockdrigo 6b39935d8e Submodule pointers: lock 2026-11-21 13:35:23 -06:00
rockdrigo e928eeae57 Submodule pointers: CaMa recurrence 2026-11-21 13:34:56 -06:00
rockdrigo 321552224d Submodule pointers: scenario figures in the patient record 2026-11-21 13:14:06 -06:00
rockdrigo 3f1deada2e Submodule pointers: scenarios and patient figure 2026-11-21 13:03:19 -06:00
angel 8166dd2ee8 Merge pull request 'Integration/tea eeg analysis into dev' (#17) from integration/tea-eeg-analysis-into-dev into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/17
2026-11-21 12:36:10 -06:00
Angel Capetillo Zavala 360d2f7ab0 Merge feature/tea-eeg-analysis into dev (TEA age norm and ADOS-2 relation) 2026-11-21 12:23:54 -06:00
rockdrigo 9689c60168 Submodule pointers: rehydrated production model 2026-11-21 12:15:23 -06:00
rockdrigo be9ab7c8df Submodule pointers: live survival figure in the patient record 2026-11-21 12:07:21 -06:00
alberto cf1213e280 chore: WebApi and WebApp follow the TEA patient view's age norm and ADOS-2 relation 2026-11-21 11:18:08 -06:00
alberto 6d87071756 feat(tea): gold view of the ADOS-2 association model with the observed ADOS-2 outcome 2026-11-21 11:18:08 -06:00
alberto 4366a9cb67 feat(tea): the age at the EEG and each metric's baseline label through silver to the gold views 2026-11-21 11:18:08 -06:00
alberto fe767dae21 feat(tea): tables for the ADOS-2 association model and its per-patient values 2026-11-21 11:18:08 -06:00
rockdrigo 2d86d54fe5 Submodule pointers: patient figure legend 2026-11-21 10:53:41 -06:00
rockdrigo 4402b77ec7 Submodule pointers: CaMa survival aligned with the SEER pipeline 2026-11-21 10:33:48 -06:00
rockdrigo 0df069383f Submodule pointers: patient survival figure, no test-data tags 2026-11-21 10:13:48 -06:00
rockdrigo a8b4b64873 Submodule pointers: ordered development tables 2026-11-21 05:03:52 -06:00
rockdrigo f3f21bb64b Submodule pointers: TEA reference folder for training jobs, risk batches spec 2026-11-21 04:48:43 -06:00
rockdrigo 74b421d434 Submodule pointers: governance risk batches for CaMa 2026-11-21 04:24:19 -06:00
rockdrigo 07c7a66e3e Merge remote-tracking branch 'origin/dev' into feature/cama-roundtrip 2026-11-21 04:03:00 -06:00
rockdrigo 2b642a57b9 Merge origin/feature/cohorts-dbt-canonical 2026-11-21 04:03:00 -06:00
rockdrigo cb9ca9d735 Submodule pointers: lazy SEER imports 2026-11-21 03:33:44 -06:00
rockdrigo 21885d6a10 Submodule pointers: CaMa development stages, governance training jobs; extraction negation pseudo-trigger 2026-11-21 03:28:13 -06:00
rockdrigo 56520a33c6 CaCu: the heads of the CaCu migration chain joined 2026-11-21 02:57:36 -06:00
rockdrigo 6a91ba67cf Merge feature/tea-eeg-analysis 2026-11-21 02:52:01 -06:00
rockdrigo 50decaf915 Merge origin/feature/163-cama-risk-curves
# Conflicts:
#	Core/core/catalogos/cama.toml
#	Transformation/dbt_project.yml
#	Transformation/models/cama/silver/cama_linea_de_tiempo.sql
#	WebApi
#	WebApp
2026-11-21 02:52:01 -06:00
rockdrigo 10d30d18c4 Merge remote-tracking branch 'origin/feature/cohorts-dbt-canonical' into feature/cama-roundtrip 2026-11-21 02:51:35 -06:00
edgar 5c2c689d47 Pin WebApi with the cycle test over every dbt cohort
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-21 02:14:26 -06:00
rockdrigo eefefed966 CaMa: the patient's date of death, the total cohort, and the heads of the CaMa migration chain joined
The date of death (paciente.pac_fecha_defuncion, persona.fecha_defuncion) arrives on the timeline as the persona's
birth and death. cama/cohorte_total is every patient with a clinical event, for the scenarios that index and filter in
their own pipeline; its window and cut-off are one dbt var. A merge revision joins the date-of-death and risk-index-date
revisions.
2026-11-21 02:07:34 -06:00
edgar 7af7fd12db Merge feature/163-cama-risk-curves into feature/cohorts-dbt-canonical
dbt_project.yml keeps dev's TEA vars (without the EEG thresholds) and adds CaMa's survival cohort. The risk index
date migrations now follow the date-of-death ones (cacu a1d4e7c20b31 after c3d8f5a20b47, cama b2e5f8d31c42 after
a9c4e2f17d38), so each project keeps a single alembic head. WebApi and WebApp point at their
feature/cohorts-dbt-canonical branches with feature/163-cama-risk-curves merged in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-21 02:07:26 -06:00
rockdrigo 87977b4ca5 CaMa scenarios: post-treatment from its evidence and every other patient under observation, without screening or control levels; submodule pointers 2026-11-21 01:55:05 -06:00
Angel Capetillo Zavala 5fdb23a28e Pin WebApi and WebApp with CaCu's category groups and stratified views 2026-11-21 01:29:46 -06:00
Angel Capetillo Zavala ba99bbd311 feat(cacu): declare the category groups of EU7 and the confirmation, and the status captions 2026-11-21 01:29:39 -06:00
Angel Capetillo Zavala f7a5693455 feat(cacu): declare the figures and category captions of CaCu's measures 2026-11-21 01:29:39 -06:00
rockdrigo 06839a6f35 CaMa: clinical stage and tumour size of invasive cancers are no longer served as measures 2026-11-20 23:28:34 -06:00
edgar 8ec77fc4f8 Pin models, WebApi and WebApp to feature/cohorts-dbt-canonical
The three submodules move to their branches of this change, so this branch holds all of it: models (the scenarios'
index and rules in their pipelines, dbt as the only cohort definition, the risk's index date), WebApi (the cycle
builds dbt's cohorts, CaCu's FHIR RiskAssessment, the old risk route retired) and WebApp (the patient record reads the
RiskAssessment). They change together: the risk's shape and the record's endpoint changed in all four.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:23:35 -06:00
edgar 1f144a5cec Merge dev into feature/cohorts-dbt-canonical
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:23:24 -06:00
edgar 3f1925b775 Each risk keeps the model's index date for its patient
evaluacion_riesgo.fecha_indice: the decision point the model scored the patient from, which the horizons count from
(the model defines it, not the cohort member). Migrations for CaCu, CaMa and TEA add it, fill existing risks with their
member's index date in the batch's build, and make it required. save_batch takes (pac_id, fecha_indice, horizonte,
probabilidad, ic_bajo, ic_alto) and refuses a risk with no date or two dates for one patient; change_state keeps it;
current_risk returns it and the batch's outcome. The risk-band measure dates each row by the estimate's index date.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:02:45 -06:00
edgar 650b3fdf7b Merge dev into feature/cohorts-dbt-canonical
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 22:10:04 -06:00
Angel Capetillo Zavala f01dcbbde5 Update WebApp with the TEA EEG follow-up fixes 2026-11-20 21:57:47 -06:00
edgar 9b4e18c345 CaCu cohorts share one recruitment window and cut-off
`cacu_window` in dbt_project.yml (a YAML anchor, merged into each cohort's vars): the post-colposcopy and total
cohorts recruit as the surveillance cohort does, and the total cohort carries the window in its parameters for the
scenarios indexed in their pipelines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 21:54:48 -06:00
edgar 697702d497 CaCu cohorts in dbt only: post-colposcopy per visit, post-treatment and a total cohort
Post-colposcopy (Cheung et al. 2020, doi:10.1097/LGT.0000000000000528): one cohort per visit k, indexed at the first
colposcopy's result (k = 0) or at its k-th surveillance visit, with a cotest, before any later colposcopy; the rules are
macros (macros/cacu_post_colposcopy.sql), so a visit is a folder. PROVISIONAL: a colposcopy without a biopsy order is
taken as below CIN2, which assumes the colposcopic impression misses no CIN2+. The timeline adds `orden_biopsia`.
Post-treatment: the first cytology after the first treatment. cacu/cohorte_total: everyone with an event, for models
whose rules don't fit SQL. dbt is the only definition of a cohort: each population meta carries its `version`, and the
surveillance cohort a `variables` query (pap_0, hpv_0) that the WebApi cycle stores with its build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 20:17:48 -06:00
edgar 8fc3dda18a CaCu glandular cytology result: catalog, timeline, extraction vocabulary and the surveillance rule
The glandular result (`citologia.celulas_glandulares`) is a closed result with the codes AGC and ADENOCARCINOMA, one of
KPNC's six cytology categories. The timeline carries it as `glandular`; the surveillance cohort's `no_index_result`
counts it; the extractor maps the Bethesda wordings to its codes. Known gap: "adenocarcinoma in situ" is still read as
ADENOCARCINOMA (no AIS code in the catalog).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 20:17:48 -06:00
AlbertoPMDM 26cf87a49a WebApp: one card per TEA EEG metric and the electrode map within its column 2026-11-20 19:56:08 -06:00
Angel Capetillo Zavala 4b363b9c97 Pin WebApp with the full domain names and CaMa's summary layout shared by CaCu and TEA 2026-11-20 19:54:46 -06:00
rockdrigo 5105059c0c Submodule pointer: the WebApi with the date of death in silver persona 2026-11-20 18:46:41 -06:00
rockdrigo ddeabab640 CaMa survival cohort: no exclusions, the surgery as its procedure of interest and only the patients in post-treatment 2026-11-20 18:40:54 -06:00
rockdrigo 1937834b25 CaMa survival cohort in dbt: indexed at the first surgery, excluding a prior radiotherapy or chemotherapy and no invasive cancer by the surgical report 2026-11-20 18:29:03 -06:00
rockdrigo 655067e47d CaMa timeline: the surgical report, staging, the mammogram's findings, BRCA, marital status, treatments, and birth and death from persona 2026-11-20 18:29:03 -06:00
rockdrigo 27caa1173e CaMa catalog: the registry's breast morphologies the WHO list leaves out, the mass's margin and marital status as an observation 2026-11-20 18:24:57 -06:00
rockdrigo f106a3e09d CaCu: the patient's date of death, in staging and in silver's persona (new revision) 2026-11-20 17:04:16 -06:00
rockdrigo 6ca7f7f368 CaMa: the patient's date of death, in staging and in silver's persona (new revision) 2026-11-20 17:04:15 -06:00
rockdrigo 75a114df94 CaMa: clinical scenarios as a hierarchy (screening, control, post-treatment), each level from its first evidence; submodule pointer 2026-11-20 17:04:15 -06:00
rockdrigo 97b68cc316 Submodule pointers: the WebApi with CaMa's scenario and stage tests and coded results with a code system, the WebApp with the stratum sidebar 2026-11-20 17:04:10 -06:00
rockdrigo 6bb7b1d5e9 CaMa catalog: the NOM-041-SSA2-2011 minimum by procedure, with treatment, risk factors and the BRCA test as studies; a coded result may name its code system 2026-11-20 17:04:04 -06:00
rockdrigo 0b6384097a CaMa: each patient's scenario (follow-up, post-diagnosis, post-treatment) inferred from configurable evidence onto her timeline 2026-11-20 17:04:04 -06:00
rockdrigo 8ecef0bb03 CaMa: stage and size of invasive cancers as their own measures, without a molecular subtype; the prior mammogram's BI-RADS without strata 2026-11-20 17:04:04 -06:00
Angel Capetillo Zavala ab82a4c805 Pin WebApi with the tea library declared as its own dependency 2026-11-20 16:56:55 -06:00
Angel Capetillo Zavala 9a3f9f2813 Merge feature/tea-eeg-analysis into dev (TEA candidate composition) 2026-11-20 14:45:03 -06:00
angel 315ad3b269 Merge pull request 'Pin WebApp with the CaMa selective rollback' (#16) from chore/pin-webapp-cama-reversion into dev 2026-11-20 10:04:42 -06:00
Angel Capetillo Zavala 1bbf5d4877 Pin WebApp with the CaMa selective rollback 2026-11-20 10:02:50 -06:00
AlbertoPMDM 65e153aae8 Merge feature/tea-eeg-analysis into feature/tea-eeg-baseline-bundles 2026-11-20 09:40:20 -06:00
AlbertoPMDM ea316a6d59 models: TEA EEG baselines trained on a local cohort and moved as a bundle 2026-11-20 09:36:41 -06:00
AlbertoPMDM ea4b8ef235 models: loading a TEA EEG baseline leaves sys.path as it was 2026-11-20 09:33:21 -06:00
angel 13e8c4fd87 Merge pull request 'Pin WebApp with final CaMa demo changes' (#15) from feature/cama-clasificacion-histologica-webapp-pin into dev 2026-11-20 00:53:52 -06:00
Angel Capetillo Zavala 70f10e57d1 Pin WebApp with final CaMa demo changes 2026-11-20 00:52:04 -06:00
AlbertoPMDM 752495bbc8 models: TEA EEG baselines keep their artifacts under MLFLOW_ARTIFACT_ROOT 2026-11-19 23:17:42 -06:00
AlbertoPMDM 59de353672 WebApi: lock the tea library at 0.2.0 2026-11-19 20:34:09 -06:00
angel ef0cdff393 Merge pull request 'Pin WebApp with the CaMa BI-RADS and histopathology updates' (#14) from feature/cama-histopathology-webapp-pin into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/14
2026-11-19 19:48:36 -06:00
Angel Capetillo Zavala 746ad93c4e Pin WebApp with the CaMa BI-RADS and histopathology updates 2026-11-19 19:45:33 -06:00
AlbertoPMDM a67eaa0646 models: the TEA EEG analysis takes the age from the EDF header 2026-11-19 19:20:29 -06:00
angel 1a8bad2815 Merge pull request 'Pin WebApp with the CaMa diagnosis-to-treatment card' (#13) from feature/cama-diagnosis-treatment-webapp-pin into dev 2026-11-19 17:52:06 -06:00
Angel Capetillo Zavala 8e43dccfe0 Pin WebApp with the CaMa diagnosis-to-treatment card 2026-11-19 17:50:26 -06:00
Angel Capetillo Zavala b8f58585ad Update WebApp pin for CaMa BI-RADS charts 2026-11-19 16:07:01 -06:00
AlbertoPMDM 2144d60d06 feat(tea): tables and dbt models for the EEG analysis's output; submodules on the TEA EEG analysis 2026-11-19 15:43:27 -06:00
Angel Capetillo Zavala 6bd3f40a6c Pin WebApp with visual login test fixes 2026-11-19 11:44:47 -06:00
Erick ivan 87cfae3969 chore(submodules): bump WebApi and WebApp with the front-only login
WebApi drops the session login and stays open for the data service; WebApp keeps the login and the per-account domains in the browser. .env.example no longer documents the session variables.
2026-11-19 10:32:44 -06:00
Erick ivan 47046eaea7 chore(submodules): bump WebApi and WebApp with the session login
WebApi brings /auth and the per-domain scope; WebApp brings the sign-in screen, the route guard and the domain filtering in the import workspace and governance. .env.example documents WEBAPI_USUARIOS and the session key.
2026-11-19 09:37:30 -06:00
angel b81c626013 Merge pull request 'chore(submodules): update WebApp with the CI spec fixes' (#12) from fix/ci-spec-contracts into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/12
2026-11-19 00:11:39 -06:00
Angel Capetillo Zavala aa840b9f31 chore(submodules): update WebApp with the CI spec fixes 2026-11-18 23:41:47 -06:00
Angel Capetillo Zavala d2f597cec8 chore(submodules): update WebApp dev color fixes 2026-11-18 15:30:00 -06:00
Angel Capetillo Zavala cc5738d036 chore(submodules): update WebApp for CaMa BI-RADS donut 2026-11-18 15:13:27 -06:00
Angel Capetillo Zavala 3cd094a8c5 chore: actualizar WebApp con ajustes de CaMa 2026-11-18 14:29:34 -06:00
Angel Capetillo Zavala 9ace5da517 chore: actualizar WebApp con ajustes de CaMa 2026-11-18 09:25:45 -06:00
Angel Capetillo Zavala 0017b0ca4c Update WebApp CaMa indicator labels 2026-11-17 12:44:43 -06:00
Angel Capetillo Zavala 9903e22c2a Add CaMa cohort and L3 measures with integrated API and dashboard
Publish deterministic cohort candidates and detection, result-to-diagnosis and BI-RADS histopathology measures. Pin locally prepared WebApi and WebApp commits based on current dev; retain models and shared persistence changes from upstream. Document compatibility, required views and stored-report behavior.
2026-11-17 10:44:08 -06:00
Roberto Treviño Cervantes 8885162147 wording fixes 2026-11-17 02:20:15 -06:00
Roberto Treviño Cervantes 20f244c014 wording fixes 2026-11-17 02:18:05 -06:00
roberto 9baeeb7ff0 Merge pull request 'Kit exit: retire indicadores_kit, converge TEA/CaMa work onto dev' (#11) from feature/kit-exit-integration into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/11
2026-11-16 21:09:40 -06:00
Roberto Treviño Cervantes 28d80ad7e3 Submodule pointers: the WebApi with live estimators and pac_id follow-up, the WebApp with the CaMa dashboard over FHIR 2026-11-15 05:40:28 -06:00
Roberto Treviño Cervantes 80e0677b3a Compose profile that trains the CaCu model on the loaded data; the manual explains the measures, the model and the risk batches 2026-11-15 05:39:26 -06:00
Roberto Treviño Cervantes a6a05febfd TEA: one migration head again, joining the source-terminology and order-PDF revisions 2026-11-15 00:48:48 -06:00
Roberto Treviño Cervantes 1405208c3e Merge remote-tracking branch 'origin/feature/163-tea-redesign' into feature/kit-exit-integration
# Conflicts:
#	Core/core/tea/models.py
#	Core/spec/tablas_TEA.md
#	Persistance/persistance/cacu/__init__.py
#	Persistance/persistance/cama/__init__.py
#	Persistance/persistance/edges/silver/__init__.py
#	Persistance/persistance/tea/__init__.py
#	README.md
#	Transformation/.gitignore
#	Transformation/dbt_project.yml
#	WebApi
#	WebApp
#	indicadores_kit
#	models
2026-11-15 00:47:16 -06:00
Roberto Treviño Cervantes 64abc56989 Retire the indicadores_kit submodule: its jobs live in Transformation, the WebApi and models 2026-11-15 00:40:13 -06:00
alberto 918fe01ea1 WebApp submodule pointer: history chart and KPI card with measures that publish more groups 2026-11-13 21:15:48 -06:00
alberto 130ef28a16 WebApp submodule pointer: the EEG result measure draws one bar per alteration 2026-11-13 19:38:47 -06:00
rockdrigo 983b702488 WebApi and WebApp submodule pointers: indicators over FHIR and the TEA views; dbt's local database ignored 2026-11-13 17:03:23 -06:00
rockdrigo 72d092d0f3 Submodule pointers: the WebApi with the source mappings and the import path off the kit; the kit without add_resultado's tests
How: WebApi at 73cbf0c (catalog matching and commit on the WebApi's own modules, source_mapping, seeding and validated writes); indicadores_kit at f79e8d2.

Implications: on this branch the five repositories sit on dev's latest; WebApi 510 tests pass, models 179, Persistance 51, Core 19, failing only where tesseract or pymssql aren't installed.
2026-11-13 15:41:47 -06:00
rockdrigo d6e2c68dbf dbt: silver's source mappings declared, and a test that no form maps to two targets while both are in force
How: `cat_sistema_fuente` and `cat_mapeo` are silver sources in every domain; the generic test
`vigencias_sin_traslape` self-joins the rows of the same form (compared null-safe) and fails on each pair
with a different target and overlapping validity, in portable SQL (`date_literal` for the open end). Its
arguments stay at the test's top level, which dbt-core 1.7 (the MySQL group) reads.

Implications: a mapping written past the application's check (by hand, by a script, by a restore) shows up
in `dbt test`. Checked on the three domains' seeded databases (pass) and with a planted clash (1 failure).
2026-11-13 15:35:01 -06:00
alberto 1dbde8b830 The webapi image builds its own dbt manifest: a local Transformation/target stays out of the build context; submodule pointer 2026-11-13 15:31:29 -06:00
rockdrigo 14dff24f85 Persistance: a repository of each domain's source systems and mappings
How: `SourceMappingRepository` (`source_mapping_repository` in cacu, cama and tea) lists systems and mappings,
adds a missing system, seeds only the forms with no row yet, adds one mapping after running the caller's check
against the stored rows of the same form in the same session, and closes a row's validity once.

Implications: a deploy never changes a stored mapping; the rule that the mapping is a function stays with the
caller, which runs it on every write.
2026-11-13 15:29:36 -06:00
rockdrigo 74eb5a4a4c Persistance: a revision per domain creating cat_sistema_fuente and cat_mapeo
How: cacu f89e1f081998, cama f82b64f43abd and tea 6d772e9a342f, on each chain's head; plain types, check
constraints, foreign keys and a unique key that every engine accepts. Verified upgrade, `alembic check`,
downgrade and upgrade again on SQLite.

Implications: both tables start empty; the catalog step seeds the TOML's own mappings.
2026-11-13 15:29:07 -06:00
rockdrigo 66c4ba5c5f Core: cat_sistema_fuente and cat_mapeo, how each source writes the catalog's codes, in the three domains
How: `CatSistemaFuenteBase` (who sends the data, its staging table and validity) and `CatMapeoBase` (a study
code, caption or spelling of a source, mapped to `estudio_id`, `resultado_id` or a `cat_valor`, with its
validity, author and reason), with their constraints in `reglas_de_mapeo` and `vigencia_ordenada`: a known
class and the target it needs, the value's foreign key to `cat_valor`, and one row per form and start date.

Implications: the codes stay in the TOML; how a provider writes them becomes data, edited without a deploy.
Overlapping validities aren't a portable constraint and are checked by the writer and by dbt.
2026-11-13 15:29:07 -06:00
rockdrigo 86b8da08bf CaMa: tumour stratifiers derived in dbt, and the BI-RADS of invasive cancers broken down by them
How: `cama_estratificadores` turns the timeline's lines read from reports into timeline facts: the clinical stage's
group, early or advanced stage, the surrogate molecular subtype from one pathology report, and T by the lesion's
size, by the rules in `vars.cama.estratos`. `cama_cancer_invasor` has one row per biopsy report with an invasive
cancer (`vars.cama.grados_invasor`) and the BI-RADS of the mammogram that led to it. CAMA_BIRADS_CANCER_INVASOR
counts those patients by BI-RADS, stratified by age group, stage, early or advanced, subtype and size. Bumps WebApi
to the stratum read by the event cut-off.

Implications: the analysis' stratifiers exist as data and reach FHIR as stratifiers. Their rules (stage groups,
Ki-67 and progesterone thresholds, T bounds) are provisional placeholders in dbt's vars. BRCA has no source yet.
2026-11-13 15:19:19 -06:00
rockdrigo 7842170a0e CaMa: provisional catalog results read from reports, with their captions and spellings, on the timeline
How: `cama.toml` declares density and lesion size (mammography), histological type, Nottingham grade, estrogen
and progesterone receptors with their percentages, HER2 and Ki-67 (pathology), and the clinical stage (note),
each with `etiquetas_fuente`, value aliases and `provisional = true`. `cama_linea_de_tiempo.yml` gives each one a
timeline line. The catalog's README documents the keys. Bumps WebApi to the load that reads them.

Implications: the analysis' stratifiers (molecular classification, stage, early or advanced, size) can be derived
in dbt from these lines. A new caption or spelling from the laboratory is one line in the catalog, applied on the
next load. BRCA, recurrence and vital status still have no source.
2026-11-13 15:19:19 -06:00
alberto 087168044e Ignore graphify's output 2026-11-13 15:19:19 -06:00
alberto 0f3b5851eb TEA: one version of each child per load that brought its facts, and a neuropediatrics note counts from the psychology step on; submodule pointer 2026-11-13 15:19:19 -06:00
edgar cb5a56de15 TEA staging by study (eight tables and a new revision), its catalog, and dbt's TEA models and measures; submodule pointers 2026-11-13 15:19:19 -06:00
edgar 865412ea7a SQL Server 2016: dbt's sources in the target's schema, one type per timeline value, LTRIM(RTRIM()) for TRIM, stratum values added to their catalog 2026-11-13 15:19:19 -06:00
edgar 47caff4034 The indicator kit's code lives in its owners now: the WebApi, models and Transformation 2026-11-13 15:19:19 -06:00
edgar cef2c62c3c English names: Persistance's edges (bronze, silver, gold), the materializer and their repositories 2026-11-13 15:19:19 -06:00
edgar ef872f6b12 CaCu and CaMa measures from dbt's semantic layer over the generic tables: follow-up status from inferred procedures, one timeline for every reader 2026-11-13 15:19:18 -06:00
alberto 5aa90c230a Merge remote-tracking branch 'origin/feature/163-tea-redesign' into feature/163-tea-redesign 2026-11-13 15:13:42 -06:00
alberto 92cf95e1af TEA: ordenes_estudio.ord_pdf_blob holds the study's report as a PDF (new revision); submodule pointer 2026-11-13 15:03:02 -06:00
Angel Capetillo Zavala 532338cdea Update TEA web application 2026-11-13 14:28:10 -06:00
Roberto Treviño Cervantes 5d2d5ea4cb updating nlp policies; more robust recognition beyond rules 2026-11-13 11:53:07 -06:00
Roberto Treviño Cervantes 0b8ba5c43a fix governance reqs; allow for sandboxed jupyter notebooks for testing 2026-11-13 11:53:07 -06:00
Roberto Treviño Cervantes 4ce7f21017 improve ingestion system to match isssteleon setup 2026-11-13 11:53:06 -06:00
alberto 11dabc4714 Ignore graphify's output 2026-11-12 19:47:50 -06:00
alberto c67b52b828 TEA: one version of each child per load that brought its facts, and a neuropediatrics note counts from the psychology step on; submodule pointer 2026-11-12 19:47:19 -06:00
edgar 3aec97a8b7 TEA staging by study (eight tables and a new revision), its catalog, and dbt's TEA models and measures; submodule pointers 2026-11-12 15:21:26 -06:00
Roberto Treviño Cervantes 5d80c480ef Let structured source fields key and override extracted document records 2026-11-12 01:13:34 -06:00
Roberto Treviño Cervantes 4275f9bcc9 Merge staging into dev 2026-11-12 01:12:29 -06:00
Roberto Treviño Cervantes 2188d7a5e8 Submodule pointers: WebApi and indicadores_kit at their dev with import files in columns 2026-11-11 11:20:13 -06:00
Roberto Treviño Cervantes d8ff604b6f import files in columns 2026-11-11 11:19:41 -06:00
Roberto Treviño Cervantes f6d00f51f3 WebApi pointer: fold repeated catalog-matching captions 2026-11-11 09:16:03 -06:00
Roberto Treviño Cervantes 32df6dadf8 Submodule pointers: WebApi, indicadores_kit and models at their merged staging 2026-11-11 07:27:16 -06:00
Roberto Treviño Cervantes 362d97af70 Merge import files in columns into staging 2026-11-11 07:27:03 -06:00
Roberto Treviño Cervantes 461cae1490 Merge dev into staging 2026-11-11 07:27:00 -06:00
Roberto Treviño Cervantes e6eb3157a3 import files in columns 2026-11-11 07:19:29 -06:00
edgar f7faabf699 SQL Server 2016: dbt's sources in the target's schema, one type per timeline value, LTRIM(RTRIM()) for TRIM, stratum values added to their catalog 2026-11-08 17:28:24 -06:00
edgar 987efe54f8 The indicator kit's code lives in its owners now: the WebApi, models and Transformation 2026-11-08 17:28:24 -06:00
edgar bcfd6aef07 English names: Persistance's edges (bronze, silver, gold), the materializer and their repositories 2026-11-08 17:28:24 -06:00
edgar f13efbad67 CaCu and CaMa measures from dbt's semantic layer over the generic tables: follow-up status from inferred procedures, one timeline for every reader 2026-11-08 17:28:24 -06:00
edgar a69db40067 Merge pull request 'Persistance: cohort membership and current risks; models, WebApi and indicadores_kit pointers' (#10) from feature/model-proto into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/10
2026-11-06 15:06:53 +00:00
edgar e27a5da077 indicadores_kit: README with BIRTH_DATE 2026-11-06 08:46:21 -06:00
edgar 7e4c643c4d indicadores_kit: staging patients in tests get a birth date 2026-11-06 08:33:52 -06:00
edgar 4a30d64193 models and WebApi: the CIN2+ prototype, risk batches stored and served, report eda, cohorts list and show 2026-11-06 08:29:05 -06:00
edgar a31d987548 Persistance: a patient's membership in a cohort's latest build and risks in the current confirmed batch 2026-11-06 08:21:52 -06:00
angel c6c8bdf3f8 Merge pull request 'chore: update WebApi submodule to latest dev' (#9) from fix/webapi-lock-gitlink into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/9
2026-11-06 06:23:25 +00:00
Angel Capetillo Zavala 6ff683ad80 chore: update WebApi submodule to latest dev 2026-11-06 00:21:10 -06:00
edgar a43f41727e Merge pull request 'Feature/model proto' (#8) from feature/model-proto into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/8
2026-11-06 05:38:58 +00:00
edgar af7ed4495a Persistance reads dbt's timeline view and compiled queries; Transformation: the CaCu surveillance cohort as one query per rule 2026-11-05 16:12:23 -06:00
edgar a377ed0eaf Submodules: models and WebApi at their merged dev 2026-11-04 13:38:25 -06:00
edgar 4e7b5701e5 Merge pull request 'Core: docstring points to models.io.registry' (#7) from feature/model-proto into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/7
2026-11-04 19:13:40 +00:00
edgar ef1fd82a42 Core: docstring points to models.io.registry 2026-11-04 12:48:41 -06:00
edgar 92c46e4f78 Merge pull request 'Feature/model proto' (#6) from feature/model-proto into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/6
2026-11-04 18:15:22 +00:00
edgar 9b9b4b7f8b Submodules: models and WebApi at their merged dev 2026-11-04 12:12:20 -06:00
edgar 924c5f17a3 Merge pull request 'Feature/model proto' (#5) from feature/model-proto into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/ISSSTELEON/pulls/5
2026-11-04 17:36:58 +00:00
edgar 3b024f5314 Persistance: CohorteRepository.builds lists the builds, newest first 2026-11-04 09:23:37 -06:00
edgar 90c083e305 Transformation: the timeline as a view from each domain's declared sources, equal to the kit's in the three domains 2026-11-04 02:03:49 +00:00
edgar 55ee3cfba7 Transformation: one silver source shared by the three domains; dbt_utils no longer used 2026-11-04 02:03:49 +00:00
edgar 2f210c4797 Transformation: renamed from Transformacion; models per project in silver and gold, one folder per indicator family 2026-11-04 01:42:28 +00:00
edgar 0d12c73d15 Transformacion: SQL Server through the mssql-python driver, without system ODBC libraries 2026-11-04 01:31:29 +00:00
edgar 5370805886 Transformacion: date_literal, as_text and as_integer, MySQL's datediff, typed output of tiempo_reporte and a unit test of datediff 2026-11-04 01:31:29 +00:00
edgar 01d0f11dfb Transformacion: the CIE lists as variables instead of seeds; dbt creates only views 2026-11-04 01:23:47 +00:00
edgar db2a7804d0 Transformacion: intermediates compiled as CTEs over silver's tables; only the timeline and the marts are created 2026-11-04 01:22:51 +00:00
edgar 69896d641a Transformacion: datediff arguments in order, biopsies linked to their cytology through the order, cytology id as procedimiento_id 2026-11-04 01:11:21 +00:00
edgar 5b6e701310 Transformacion: SQLite variants of generate_schema_name and datediff 2026-11-04 01:11:21 +00:00
edgar 29c9963e5d Transformacion: the intermediates read silver's procedimiento and observacion_clinica; the staging views over bronze are removed 2026-11-04 01:11:21 +00:00
edgar f5819efa7a Transformacion: dbt-core in one group per engine (sqlite, sqlserver, postgres on 1.12; mysql on 1.7) and one profile per domain 2026-11-04 01:02:20 +00:00
Klingsor0 b5a53c587f feat(Transformacion): marts CaCu IND1, TIEMPO_REPORTE, DIAS_TOMA_DIAGNOSTICO y schema_marts
- int_cacu_notas: pivot columnar desde int_cacu_procedimiento/observacion (silver, no bronze)
- mart_cacu_ind1: C1 tamizadas con resultado anómalo
- mart_cacu_tiempo_reporte: C3r días toma→reporte con horizonte y pendiente
- mart_cacu_dias_toma_diagnostico: C3r días toma→nota diagnóstico, join-based (workaround SQLite 3.40)
- stg_cacu_nota_medica_{proc,obs}: refactor; clasificacion de tipo_nota via seeds (no CASE hardcodeado)
- seeds cacu: seed_cacu_nota_cie (es_diagnostico, es_antecedente), seed_cacu_nota_especialidad (prioridad)
- dbt_project.yml: vars citologia_anomala, especialidades_diagnostico, horizontes; marts → view; seeds schema
- schema_marts.yml: meta FHIR (measure_url, contrato, parametros, poblaciones) para los seis marts CaCu

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Pruebas: Core 18, Persistance 20, kit 218.

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

Pruebas: Core 17, Persistance 20, kit 208.

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

Pruebas: Persistance 20 pasan.

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

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

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

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

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

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

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

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

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

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

El puntero del submódulo indicadores_kit no se incluye.

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 02:20:41 +00:00
edgar 9a11248f09 indicadores_kit en v0 2026-10-07 02:48:06 +00:00
edgar b96b4b3d8f submodulo de indicadores 2026-10-06 22:39:31 +00:00
edgar 46aa111cca version cero 2026-10-06 22:31:52 +00:00
365 changed files with 24489 additions and 2452 deletions
+7 -3
View File
@@ -1,6 +1,4 @@
# WebApi's docker-compose service builds with context: . (this directory)
# so it can COPY its sibling Core/, Persistance/ and models/ directories —
# this is the .dockerignore Docker actually reads for that build.
# Read by the webapi build, whose context is the repo root.
.git/
WebApp/
**/__pycache__/
@@ -10,3 +8,9 @@ WebApp/
**/.pytest_cache/
**/*.db
**/uv.lock
!WebApi/uv.lock
dist/
# The image compiles its own manifest.
Transformation/target/
Transformation/logs/
**/node_modules/
+32
View File
@@ -0,0 +1,32 @@
# Copy to .env (docker compose reads it for the webapi service; Persistance's
# settings also read a .env in the working directory when run directly).
# --- Target databases (one per domain; SQLite files by default) ---
# CACU_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_cacu
# CAMA_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_cama
# TEA_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_tea
# GOVERNANCE_DATABASE_URL=mysql+pymysql://isss_app:CHANGE_ME@db-host:3306/isss_governance
CACU_DATABASE_URL=sqlite:////data/cacu.db
CAMA_DATABASE_URL=sqlite:////data/cama.db
TEA_DATABASE_URL=sqlite:////data/tea.db
# Stored predictions and the OCR extraction log.
GOVERNANCE_DATABASE_URL=sqlite:////data/governance.db
# --- SQL import sources a client may point the server at ---
# SQLAlchemy backend names. sqlite is excluded on purpose: its URL is a
# path on this server's disk.
WEBAPI_SQL_ALLOWED_DIALECTS=mysql,mariadb,postgresql,mssql
# Optional host allowlist (unset = any host reachable from the server).
# WEBAPI_SQL_ALLOWED_HOSTS=10.0.0.5,his-db.internal
# --- WebApi process ---
# Max request size (files travel inside import requests). Keep nginx's
# client_max_body_size (WebApp/nginx.conf) about 35% above it.
WEBAPI_MAX_UPLOAD_MB=200
# WEBAPI_WORKERS=2
# Seconds; OCR over many scanned pages runs inside one request.
# WEBAPI_TIMEOUT=600
# Tesseract languages for scanned documents.
# EXTRACTION_OCR_LANG=spa+eng
# Only for browser clients on another origin (the WebApp uses the proxy).
# WEBAPI_CORS_ORIGINS=https://example.internal
+14 -1
View File
@@ -1,4 +1,17 @@
# Local orientation docs, not committed anywhere in this workspace.
# Local notes.
CLAUDE.md
AGENTS.md
HANDOFF*.md
# Local environment (database credentials); docker-compose reads it but git
# must never see it. Committed template lives in .env.example.
.env
.DS_Store
# Deliverable bundle: images and local state are built/created, not versioned.
dist/imagenes/
dist/.env
dist/datos/
dist/*.tar.gz
graphify-out/
+3 -3
View File
@@ -1,9 +1,9 @@
[submodule "WebApp"]
path = WebApp
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApp.git
url = ../WebApp.git
[submodule "WebApi"]
path = WebApi
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApi.git
url = ../WebApi.git
[submodule "models"]
path = models
url = ssh://git@10.0.10.41:2222/ISSSTELEON/models.git
url = ../models.git
+2 -3
View File
@@ -7,7 +7,6 @@ registry = orm.registry()
class CaCuModel(SQLModel, registry=registry):
"""Base class for every CaCu table.
Own SQLAlchemy registry/metadata so table names (e.g. NotaMedica) don't
collide with CaMa's identically-named tables now that both domains live
in the same Python package.
Uses its own SQLAlchemy registry so table names such as `notamedica`
don't collide with CaMa's tables of the same name.
"""
+1 -29
View File
@@ -31,32 +31,4 @@ Join hacia ordenes_estudio por ord_numero_hospital (lógico, sin FK constraint).
| `plaquetas_mil_ul` | Derivado, OCR sobre PDF BH1 | Conteo de plaquetas (miles/µL) |
| `vpm_fl` | Derivado, OCR sobre PDF BH1 | Volumen plaquetario medio (fL) |
Validadores:
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| ----------------------------- | ------- | ------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| `bh_id` | INTEGER | entero positivo, no nulo | `BH_ID_AUSENTE` si el campo llega nulo, detectado por `fv:before` al requerir tipo `int` | |
| `ord_numero_hospital` | INTEGER | entero positivo, no nulo, join lógico hacia ordenesstudio | `ORD_NUMERO_AUSENTE` si el campo llega nulo, `ORD_NUMERO_INVALIDO` si no es convertible a int | |
| `pac_id` | INTEGER | entero positivo, nulo permitido si el lookup por pac_id_hospital no resuelve al momento de carga | `PAC_ID_INVALIDO` si el valor no es convertible a int | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo | `PAC_ID_HOSPITAL_AUSENTE` si el campo llega nulo | |
| `bh_fecha` | DATE | fecha de solicitud del estudio, nulo permitido | sin validador implementado | |
| `eritrocitos_mill_ul` | FLOAT | rango [0, 25] millones/µL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera del rango [0, 25] | |
| `hemoglobina_g_dl` | FLOAT | rango [0.5, 75] g/dL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera del rango [0.5, 75]. `BH_HEMOGLOBINA_HEMATOCRITO` cuando `\|hto − 3×hb\| > 10`, evaluado en `mv:after validar_indices_eritrocitarios` | |
| `hematocrito_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_HEMOGLOBINA_HEMATOCRITO` cuando `\|hto − 3×hb\| > 10`, evaluado en `mv:after validar_indices_eritrocitarios` | |
| `vcm_fl` | FLOAT | rango [0, 400] fL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 400]. `BH_VCM_INCOHERENTE` cuando `vcm ≠ 10×hto/rbc` (tolerancia ±15% o ±5 fL), evaluado en `mv:after validar_indices_eritrocitarios` | |
| `hcm_pg` | FLOAT | rango [0, 100] pg, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_HCM_INCOHERENTE` cuando `hcm ≠ 10×hb/rbc` (tolerancia ±15% o ±3 pg), evaluado en `mv:after validar_indices_eritrocitarios` | |
| `chcm_g_dl` | FLOAT | rango [0, 100] g/dL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_CHCM_INCOHERENTE` cuando `chcm ≠ 100×hb/hto` (tolerancia ±15% o ±3 g/dL), evaluado en `mv:after validar_indices_eritrocitarios` | |
| `rdw_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100] | |
| `leucocitos_mil_ul` | FLOAT | rango [0, 500] miles/µL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 500] | |
| `neutrofilos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_DIFERENCIAL_INVALIDO` cuando los cinco componentes básicos (neutrófilos, linfocitos, monocitos, eosinófilos, basófilos) suman ≠ 100% ± 2 pp, evaluado en `mv:after validar_diferencial` | |
| `linfocitos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DIFERENCIAL_INVALIDO` en neutrofilos_pct | |
| `monocitos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DIFERENCIAL_INVALIDO` en neutrofilos_pct | |
| `eosinofilos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DIFERENCIAL_INVALIDO` en neutrofilos_pct | |
| `basofilos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DIFERENCIAL_INVALIDO` en neutrofilos_pct | |
| `neutrofilos_segmentados_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_DESGLOSE_NEUTROFILICO` cuando segmentados + banda + metamielocitos + mielocitos ≠ neutrofilos_pct ± 2 pp, evaluado en `mv:after validar_diferencial` | |
| `neutrofilos_banda_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DESGLOSE_NEUTROFILICO` en neutrofilos_segmentados_pct | |
| `metamielocitos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DESGLOSE_NEUTROFILICO` en neutrofilos_segmentados_pct | |
| `mielocitos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DESGLOSE_NEUTROFILICO` en neutrofilos_segmentados_pct | |
| `plaquetas_mil_ul` | FLOAT | valor ≥ 0 miles/µL, sin máximo de plausibilidad, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor es negativo | |
| `vpm_fl` | FLOAT | valor ≥ 0 fL, sin máximo de plausibilidad, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor es negativo | |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
+6 -5
View File
@@ -4,6 +4,7 @@ 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):
@@ -16,20 +17,20 @@ class BiometriaHematica(CaCuModel, table=True):
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# join logico — resuelto por el loader via lookup en paciente.pac_id_hospital
# 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),
)
# Identificador del hospital — permite vincular estudios con pacientes
# Hospital patient id: links studies to patients
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# join logico hacia ordenes_estudio.ord_numero_hospital, sin FK constraint
# 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",
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
bh_fecha: Optional[date] = Field(
default=None,
+1 -16
View File
@@ -18,19 +18,4 @@ Join hacia ordenes_estudio por ord_numero_hospital (lógico, sin FK constraint).
| `bx_ocr_confianza` | Derivado, pipeline OCR | Score de confianza global del motor OCR sobre el documento |
| `bx_pdf_blob` | Derivado, extracción ETL HPC1 | Contenido binario del PDF del reporte histopatológico |
Validadores:
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| --------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `bx_id` | INTEGER | entero positivo, no nulo | `BX_ID_AUSENTE` si el campo llega nulo, detectado por `fv:before` al requerir tipo `int` | |
| `ord_numero_hospital` | INTEGER | entero positivo, no nulo, join lógico hacia ordenesstudio | `ORD_NUMERO_AUSENTE` si el campo llega nulo, `ORD_NUMERO_INVALIDO` si no es convertible a int | |
| `pac_id` | INTEGER | entero positivo, nulo permitido si el lookup por pac_id_hospital no resuelve al momento de carga | | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo | | |
| `cit_id` | INTEGER | entero positivo, FK hacia citologiacervical, nulo permitido porque una biopsia puede existir sin citología previa documentada | | |
| `bx_fecha_solicitud` | DATE | fecha entregada por sistema estructurado, nulo permitido | `BX_FECHA_SOLICITUD_FUTURA` cuando la fecha es posterior a hoy, verificado en `fv:before fechas_no_futuras` | |
| `bx_fecha_reporte` | DATE | fecha entregada por sistema estructurado, nulo permitido | `BX_FECHA_REPORTE_FUTURA` cuando la fecha es posterior a hoy, verificado en `fv:before fechas_no_futuras`. `BX_REPORTE_ANTES_SOLICITUD` cuando el reporte es anterior a la solicitud, evaluado en `mv:after reporte_no_antes_de_solicitud` | |
| `bx_cin_grado` | TEXT | `GradoCIN` enum, nulo permitido | `BX_CIN_GRADO_INVALIDO` cuando el valor no corresponde al enum tras normalización en `fv:before normalizar_cin_grado` | |
| `bx_ocr_confianza` | FLOAT | valor entre 0.0 y 1.0, nulo permitido | `BX_OCR_CONFIANZA_FUERA_RANGO` cuando el valor cae fuera de 0.0 a 1.0, verificado en `fv:before confianza_en_rango` | `BX_OCR_CONFIANZA_BAJA` cuando el valor es inferior al umbral `BX_OCR_THRESHOLD` (actualmente 0.0, pendiente de ajustar a 0.700 según especificación externa), evaluado en `mv:after ocr_confianza_suficiente` |
| `bx_observaciones` | TEXT | texto libre, nulo permitido | sin validador implementado | |
| `bx_pdf_blob` | BLOB | contenido binario del PDF del reporte histopatológico, nulo permitido | | |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
+5 -1
View File
@@ -5,7 +5,7 @@ class GradoCIN(str, Enum):
LIEBG = "LIEBG" # histological low-grade — CIN1 equivalent
LIEAG = "LIEAG" # histological high-grade — CIN2/3 equivalent
CIS = "CIS" # carcinoma in situ
CARCINOMA = "CARCINOMA" # invasor
CARCINOMA = "CARCINOMA" # invasive
DESCONOCIDO = "DESCONOCIDO"
GRADO_CIN_ALIAS: dict[str, str] = {
@@ -15,4 +15,8 @@ GRADO_CIN_ALIAS: dict[str, str] = {
"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",
}
+25 -6
View File
@@ -4,6 +4,7 @@ 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):
"""
@@ -15,20 +16,20 @@ class BiopsiaCervical(CaCuModel, table=True):
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# join logico — resuelto por el loader via lookup en paciente.pac_id_hospital
# 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),
)
# Identificador del hospital — obligatorio, es el que permite vincular estudios con pacientes
# Hospital patient id, required: links studies to patients
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# join logico hacia ordenes_estudio.ord_numero_hospital, sin FK constraint
# 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",
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
cit_id: Optional[int] = Field(
default=None,
@@ -53,11 +54,29 @@ class BiopsiaCervical(CaCuModel, table=True):
)
bx_pdf_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(sa.LargeBinary),
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 -25
View File
@@ -26,28 +26,4 @@ Join hacia ordenes_estudio por ord_numero_hospital (lógico, sin FK constraint).
| `cit_pdf_blob` | Derivado, extracción ETL | Contenido binario del PDF del resultado citológico |
| `cit_vph_pdf_blob` | Derivado, extracción ETL TVPH1 | Contenido binario del PDF del resultado VPH, su presencia distingue VPH no solicitado de extracción fallida |
Validadores:
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| --------------------------- | ------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `cit_id` | INTEGER | entero positivo, no nulo | `CIT_ID_AUSENTE` si el campo llega nulo, detectado por `fv:before` al requerir tipo `int` | |
| `ord_numero_hospital` | INTEGER | entero positivo, no nulo, join lógico hacia ordenesstudio | `ORD_NUMERO_AUSENTE` si el campo llega nulo, `ORD_NUMERO_INVALIDO` si no es convertible a int | |
| `pac_id` | INTEGER | entero positivo, nulo permitido si el lookup por pac_id_hospital no resuelve al momento de carga | | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo | | |
| `cit_fecha_toma` | DATE | fecha entregada por sistema estructurado, no nulo | `CIT_FECHA_TOMA_FUTURA` cuando la fecha es posterior a hoy, evaluado en `mv:after fechas_plausibles` | |
| `cit_fecha_reporte` | DATE | fecha entregada por sistema estructurado, no nulo | `CIT_FECHA_REPORTE_FUTURA` cuando la fecha es posterior a hoy, `CIT_FECHA_REPORTE_ANTERIOR` cuando el reporte es anterior a la toma, evaluado en `mv:after fechas_plausibles` | |
| `cit_calidad_especimen` | TEXT | SATISFACTORIO, INSATISFACTORIO, nulo permitido | `CALIDAD_INSATISFACTORIA` cuando el valor no corresponde a ninguna entrada conocida tras normalización en `fv:before normalizar_calidad_especimen` | |
| `cit_celulas_escamosas` | TEXT | `CelulasEscamosas` enum, nulo permitido | `CEL_ESC_INVALIDA` cuando el valor no corresponde al enum tras normalización en `fv:before normalizar_celulas_escamosas` | |
| `cit_vph_resultado` | TEXT | `ResultadoVPH` enum, nulo permitido | `VPH_RESULTADO_INVALIDO` cuando el valor no es reconocible tras normalización en `fv:before normalizar_vph_resultado` | `VPH_NO_SOLICITADO` cuando el resultado es nulo y no hay PDF adjunto, `VPH_EXTRACCION_FALLIDA` cuando el resultado es nulo pero hay PDF adjunto, evaluados en `mv:after vph_disponibilidad` |
| `cit_vph_ocr_confianza` | FLOAT | valor entre 0.0 y 1.0, nulo permitido | `CIT_VPH_OCR_SCORE_FUERA_RANGO` cuando el valor cae fuera de 0.0 a 1.0, verificado en `fv:before ocr_score_en_rango` | `VPH_OCR_SCORE_BAJO` cuando el valor es inferior al umbral `VPH_OCR_THRESHOLD`, evaluado en `mv:after vph_ocr_score_suficiente` |
| `cit_vph_genotipo_16` | INTEGER | 0 o 1, nulo permitido | | `VPH_GENOTIPO_INCOHERENTE` cuando el genotipo es positivo pero el resultado VPH es NEGATIVO, evaluado en `mv:after vph_genotipo_coherente` |
| `cit_vph_genotipo_18` | INTEGER | 0 o 1, nulo permitido | | `VPH_GENOTIPO_INCOHERENTE` mismo validador que genotipo 16 |
| `cit_condiciones_ginecoobs` | TEXT | TC2, valores pendientes de confirmar, nulo permitido | sin validador implementado | |
| `cit_dx_lesion` | TEXT | TC6, NEGATIVO, LIEBG, LIEAG, CARCINOMA_EPIDERMOIDE, AGC, ADENOCARCINOMA, OTRAS_NEOPLASIAS, NO_VALORABLE, nulo permitido | sin validador implementado | |
| `cit_celulas_glandulares` | TEXT | TC9, valores pendientes de confirmar, nulo permitido | sin validador implementado | |
| `cit_carcinoma_invasor` | TEXT | TC8, almacenado como TEXT, nulo permitido | sin validador implementado | |
| `cit_exploracion` | TEXT | TC4, texto libre para NLP, nulo permitido | sin validador implementado | |
| `cit_observaciones` | TEXT | TC10, texto libre para NLP, nulo permitido | sin validador implementado | |
| `cit_pdf_blob` | BLOB | contenido binario del PDF del resultado citológico, nulo permitido | | |
| `cit_vph_pdf_blob` | BLOB | contenido binario del PDF del resultado VPH, nulo permitido | | |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
+13 -3
View File
@@ -13,17 +13,27 @@ class CelulasEscamosas(str, Enum):
LIEAG = "LIEAG"
CIS = "CIS"
class CelulasGlandulares(str, Enum):
"""Resultado de células glandulares (Bethesda): atípicas o adenocarcinoma."""
AGC = "AGC"
ADENOCARCINOMA = "ADENOCARCINOMA"
CELULAS_ESCAMOSAS_ALIAS: dict[str,str] = {
# Se tienen las formas largas, asumiendo que aparecerán igual que en la plataforma
# 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", # sin tilde
"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] = {
# Formas en cadenas asumidas por plataformas
# String forms the source platforms are expected to send
"SATISFACTORIO": True,
"INSATISFACTORIO": False,
"1": True, # from JSON bool serialization
+34 -14
View File
@@ -4,26 +4,27 @@ from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
class CitologiaCervical(CaCuModel, table=True):
cit_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# join logico — resuelto por el loader via lookup en paciente.pac_id_hospital
# 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),
)
# Identificador del hospital — obligatorio, es el que permite vincular estudios con pacientes
# Hospital patient id, required: links studies to patients
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# join logico hacia ordenes_estudio.ord_numero_hospital, sin FK constraint
# 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",
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
cit_fecha_toma: Optional[date] = Field(
default=None,
@@ -40,38 +41,38 @@ class CitologiaCervical(CaCuModel, table=True):
)
cit_pdf_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(sa.LargeBinary),
sa_column=sa.Column(FileBlob),
description="PDF de resultado",
)
cit_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Observaciones — hacer enum cuando se conozcan valores",
description="Observaciones",
)
cit_condiciones_ginecoobs: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Condiciones gineco-obstétricas: embarazo, DIU, etc. — hacer enum",
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 — hacer enum",
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 — hacer enum",
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 — hacer enum",
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, hacer enum",
description="TC8 Carcinoma epidermoide invasor",
)
cit_celulas_escamosas: Optional[str] = Field(
default=None,
@@ -79,7 +80,7 @@ class CitologiaCervical(CaCuModel, table=True):
)
cit_vph_pdf_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(sa.LargeBinary)
sa_column=sa.Column(FileBlob)
)
cit_vph_ocr_confianza: Optional[float] = Field(
default=None,
@@ -94,9 +95,28 @@ class CitologiaCervical(CaCuModel, table=True):
sa_column=sa.Column(sa.Integer)
)
cit_vph_genotipo_18: Optional[int] = Field(
default=None,
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),
)
+2 -1
View File
@@ -1,5 +1,6 @@
from core.cacu.paciente.enums import SexoBiologico, SEXO_BIOLOGICO_ALIAS
from core.cacu.citologia_cervical.enums import CelulasEscamosas, CELULAS_ESCAMOSAS_ALIAS, CITO_CALIDAD_ESPECIMEN_ALIAS, ResultadoVPH
from core.cacu.citologia_cervical.enums import CelulasEscamosas, CelulasGlandulares, CELULAS_ESCAMOSAS_ALIAS, CITO_CALIDAD_ESPECIMEN_ALIAS, ResultadoVPH
from core.cacu.biopsia_cervical.enums import GradoCIN, GRADO_CIN_ALIAS
from core.cacu.nota_medica.enums import TipoNota, TIPO_NOTA_ALIAS, Especialidad, ESPECIALIDAD_ALIAS, Parentesco, PARENTESCO_ALIAS, Dependencia, DEPENDENCIA_ALIAS
from core.cacu.ordenes_estudio.enums import TipoEstudio, TIPO_ESTUDIO_ALIAS
from core.cacu.episodio_clinico.enums import TipoEpisodio, TIPO_EPISODIO_ALIAS
+17
View File
@@ -0,0 +1,17 @@
from enum import Enum
class TipoEpisodio(str, Enum):
"""IND-02: la unidad de análisis para evaluación de desempeño del
modelo es un episodio de tamizaje, diagnóstico o tratamiento."""
TAMIZAJE = "TAMIZAJE"
DIAGNOSTICO = "DIAGNOSTICO"
TRATAMIENTO = "TRATAMIENTO"
TIPO_EPISODIO_ALIAS: dict[str, str] = {
"SCREENING": "TAMIZAJE",
"DIAGNOSTIC": "DIAGNOSTICO",
"TREATMENT": "TRATAMIENTO",
}
+72
View File
@@ -0,0 +1,72 @@
from datetime import date, datetime, timezone
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import HOSPITAL_ID_LENGTH
class EpisodioClinico(CaCuModel, table=True):
"""IND-02/IND-03: a screening, diagnosis or treatment episode, the unit
of analysis for model evaluation.
An episode combines a CIE10 code and medical specialty, a time window
bounded by the previous episode (`episodio_anterior_id`), and the medical
note it originates from (`nm_id`). The CIE10 code and specialty are
usually copied from `NotaMedica` and stored here so episodes can be
filtered without joining back to the note. Storage only; building
episodes from notes and orders is not implemented yet.
"""
episodio_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
)
tipo_episodio: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="valor de core.cacu.episodio_clinico.enums.TipoEpisodio guardado como texto",
)
nm_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("notamedica.nm_id"), index=True),
description="nota médica cuyo contenido escrito origina/documenta el episodio",
)
cie10_codigo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
especialidad_medica: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
evento_fecha: date = Field(
sa_column=sa.Column(sa.Date, nullable=False),
description="fecha del evento de interés que define el episodio",
)
ventana_inicio: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="inicio de la ventana de tiempo fija delimitada a partir del evento anterior",
)
ventana_fin: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
episodio_anterior_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("episodioclinico.episodio_id"), index=True),
description="evento anterior que delimita la ventana de este episodio",
)
created_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_column=sa.Column(sa.DateTime, nullable=False),
)
+218
View File
@@ -0,0 +1,218 @@
"""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 datetime import date
from core.cacu.base import CaCuModel
from core.indicadores.cohortes import (
CohorteArmadoBase,
CohorteExclusionBase,
CohorteMiembroBase,
CohorteVariableBase,
EvaluacionRiesgoBase,
EvaluacionRiesgoLoteBase,
armado_unico,
evaluacion_unica,
variable_con_un_valor,
)
from core.indicadores.catalogos import (
CatEstudioBase,
CatMapeoBase,
CatResultadoBase,
CatSistemaFuenteBase,
CatValorBase,
estado_de_valor_conocido,
reglas_de_mapeo,
tipo_de_valor_conocido,
vigencia_ordenada,
)
from core.indicadores.plata import (
ObservacionClinicaBase,
ProcedimientoClinicoBase,
clase_conocida,
indice_de_observacion,
indice_de_procedimiento,
observacion_en_catalogo,
llave_de_observacion,
llave_de_procedimiento,
)
from core.indicadores.comunes import CargaBase, PeriodoObservacionBase, PersonaDerechohabienteBase
from core.indicadores.registro import (
DefParametroBase,
DimFechaBase,
DimGrupoEdadBase,
DimPeriodoBase,
)
from core.indicadores.publicacion import (
CatEstratoBase,
CatEstratoValorBase,
CatMeasureBase,
CatMeasureEstratoBase,
CatMeasureGrupoBase,
CatMeasureResultadoBase,
CatMeasureValorBase,
MeasureReportUnidadBase,
MeasureReportUnidadEstratoBase,
contrato_y_unidad_conocidos,
origen_conocido,
poblacion_conocida,
una_poblacion_por_indicador,
unidad_de_estrato_conocida,
valor_de_estrato_en_catalogo,
)
from core.indicadores.reportes import (
MeasureReportBase,
)
class Persona(CaCuModel, PersonaDerechohabienteBase, table=True):
__tablename__ = "persona"
fecha_defuncion: date | None = None # survival's outcome (`pac_fecha_defuncion`); null while alive or unknown
class PeriodoObservacion(CaCuModel, PeriodoObservacionBase, table=True):
__tablename__ = "periodo_observacion"
class Carga(CaCuModel, CargaBase, table=True):
__tablename__ = "carga"
class DefParametro(CaCuModel, DefParametroBase, table=True):
__tablename__ = "def_parametro"
class DimPeriodo(CaCuModel, DimPeriodoBase, table=True):
__tablename__ = "dim_periodo"
class DimFecha(CaCuModel, DimFechaBase, table=True):
__tablename__ = "dim_fecha"
class DimGrupoEdad(CaCuModel, DimGrupoEdadBase, table=True):
__tablename__ = "dim_grupo_edad"
class MeasureReport(CaCuModel, MeasureReportBase, table=True):
__tablename__ = "measure_report"
# --- El oro por unidad y su catálogo (§6f, MD-19) ---
class CatMeasure(CaCuModel, CatMeasureBase, table=True):
__tablename__ = "cat_measure"
__table_args__ = contrato_y_unidad_conocidos()
class CatMeasureResultado(CaCuModel, CatMeasureResultadoBase, table=True):
__tablename__ = "cat_measure_resultado"
__table_args__ = (poblacion_conocida(), una_poblacion_por_indicador())
class CatMeasureValor(CaCuModel, CatMeasureValorBase, table=True):
__tablename__ = "cat_measure_valor"
__table_args__ = (origen_conocido(),)
class CatMeasureGrupo(CaCuModel, CatMeasureGrupoBase, table=True):
__tablename__ = "cat_measure_grupo"
class CatEstrato(CaCuModel, CatEstratoBase, table=True):
__tablename__ = "cat_estrato"
__table_args__ = (unidad_de_estrato_conocida(),)
class CatEstratoValor(CaCuModel, CatEstratoValorBase, table=True):
__tablename__ = "cat_estrato_valor"
class CatMeasureEstrato(CaCuModel, CatMeasureEstratoBase, table=True):
__tablename__ = "cat_measure_estrato"
class MeasureReportUnidad(CaCuModel, MeasureReportUnidadBase, table=True):
__tablename__ = "measure_report_unidad"
class MeasureReportUnidadEstrato(CaCuModel, MeasureReportUnidadEstratoBase, table=True):
__tablename__ = "measure_report_unidad_estrato"
__table_args__ = (valor_de_estrato_en_catalogo(),)
# --- Catálogos de la plata (F1): estudio -> resultado -> valor, de core/catalogos/cacu.toml ---
class CatEstudio(CaCuModel, CatEstudioBase, table=True):
__tablename__ = "cat_estudio"
class CatResultado(CaCuModel, CatResultadoBase, table=True):
__tablename__ = "cat_resultado"
__table_args__ = (tipo_de_valor_conocido(),)
class CatValor(CaCuModel, CatValorBase, table=True):
__tablename__ = "cat_valor"
__table_args__ = (estado_de_valor_conocido(),)
class CatSistemaFuente(CaCuModel, CatSistemaFuenteBase, table=True):
__tablename__ = "cat_sistema_fuente"
__table_args__ = (vigencia_ordenada("cat_sistema_fuente"),)
class CatMapeo(CaCuModel, CatMapeoBase, table=True):
__tablename__ = "cat_mapeo"
__table_args__ = reglas_de_mapeo()
# --- La plata de dos tablas (F5, ADR-MD-007) ---
class Procedimiento(CaCuModel, ProcedimientoClinicoBase, table=True):
__tablename__ = "procedimiento"
__table_args__ = (clase_conocida(), llave_de_procedimiento(), indice_de_procedimiento())
class Observacion(CaCuModel, ObservacionClinicaBase, table=True):
__tablename__ = "observacion_clinica" # `observacion` choca con la CTE `observacion` del motor (T-18r)
__table_args__ = (*observacion_en_catalogo(), llave_de_observacion(), indice_de_observacion())
# --- Cohortes para modelos y estimaciones de riesgo (oro restringido, ADR-MD-003) ---
class CohorteArmado(CaCuModel, CohorteArmadoBase, table=True):
__tablename__ = "cohorte_armado"
__table_args__ = (armado_unico(),)
class CohorteMiembro(CaCuModel, CohorteMiembroBase, table=True):
__tablename__ = "cohorte_miembro"
class CohorteExclusion(CaCuModel, CohorteExclusionBase, table=True):
__tablename__ = "cohorte_exclusion"
class CohorteVariable(CaCuModel, CohorteVariableBase, table=True):
__tablename__ = "cohorte_variable"
__table_args__ = (variable_con_un_valor(),)
class EvaluacionRiesgoLote(CaCuModel, EvaluacionRiesgoLoteBase, table=True):
__tablename__ = "evaluacion_riesgo_lote"
class EvaluacionRiesgo(CaCuModel, EvaluacionRiesgoBase, table=True):
__tablename__ = "evaluacion_riesgo"
__table_args__ = (evaluacion_unica(),)
+2
View File
@@ -4,6 +4,7 @@ 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",
@@ -12,4 +13,5 @@ __all__ = [
"BiopsiaCervical",
"NotaMedica",
"BiometriaHematica",
"EpisodioClinico",
]
+1 -29
View File
@@ -32,32 +32,4 @@
---
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
|---|---|---|---|---|
| `nm_id` | INTEGER | entero positivo, autoincrement, no nulo | `NM_ID_AUSENTE` si el campo llega nulo | |
| `pac_id` | INTEGER | entero positivo, indexado, nulo permitido | `PAC_ID_AUSENTE`, `PAC_ID_INVALIDO` | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, indexado, no nulo en schema de validación | | |
| `nm_id_hospital` | TEXT | alfanumérico, no nulo en schema de validación; normalizado con strip y uppercase | `NM_ID_HOSPITAL_AUSENTE` cuando llega nulo | |
| `nm_nota_previa_id` | TEXT | alfanumérico, nulo si es nota inaugural; normalizado con strip | | |
| `nm_tipo_nota` | TEXT | `TipoNota` enum: CONSULTA, EGRESO, INGRESO, URG_EGRESO; alias TIPO_NOTA_ALIAS resuelve variantes HIS ("URG. EGRESO"); no nulo | `NM_TIPO_NOTA_AUSENTE` cuando llega nulo, `NM_TIPO_NOTA_INVALIDA` cuando el valor no corresponde al enum tras normalización | |
| `nm_especialidad` | TEXT | `Especialidad` enum: MEDICINA_FAMILIAR, CIRUGIA_ONCOLOGICA, CLINICA_MUJER_COLPOSCOPIA; alias ESPECIALIDAD_ALIAS resuelve variantes HIS; no nulo | `NM_ESPECIALIDAD_AUSENTE` cuando llega nulo, `NM_ESPECIALIDAD_INVALIDA` cuando el valor no corresponde al enum tras normalización | |
| `nm_fecha` | DATE | fecha de la consulta, no nulo en schema de validación | `NM_FECHA_AUSENTE` cuando llega nulo, `NM_FECHA_FUTURA` cuando es posterior a hoy | |
| `nm_medico_tratante` | TEXT | texto libre, máximo 100 caracteres, nulo permitido | `NM_MEDICO_TRATANTE_INVALIDO` cuando supera 100 caracteres | |
| `nm_motivo_consulta` | TEXT | texto libre, no nulo en schema de validación; normalizado con strip | `NM_MOTIVO_CONSULTA_AUSENTE` cuando llega nulo | |
| `nm_interrogatorio` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_diagnostico_texto` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_cie_codigo` | TEXT | formato `[A-Z][0-9]{2}(\.[0-9]{1,2})?`, nulo permitido | `NM_CIE_CODIGO_INVALIDO` cuando no cumple el formato regex | |
| `nm_cie_descripcion` | TEXT | texto libre, máximo 200 caracteres, nulo permitido | `NM_CIE_DESCRIPCION_INVALIDA` cuando supera 200 caracteres | |
| `nm_tratamiento_texto` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_receta` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_plan_estudios` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_pronostico` | TEXT | texto libre normalizado con strip y uppercase, nulo permitido | | |
| `nm_observaciones` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_masa_corporal` | FLOAT | rango [20.0, 300.0] kg, nulo permitido | `NM_MASA_CORPORAL_FUERA_RANGO` cuando cae fuera del rango | |
| `nm_talla` | FLOAT | rango [100, 250] cm, nulo permitido | `NM_TALLA_FUERA_RANGO` cuando cae fuera del rango | |
| `nm_imc_visita` | FLOAT | rango [12.0, 90.0], nulo si peso o talla ausentes | `NM_IMC_FUERA_RANGO` cuando cae fuera del rango, `NM_IMC_INCOHERENTE` cuando no corresponde a peso/talla registrados (tolerancia ±0.5) | |
| `nm_frecuencia_cardiaca` | INTEGER | rango [0, 500] lpm, nulo permitido | `NM_FRECUENCIA_CARDIACA_FUERA_RANGO` cuando cae fuera del rango | |
| `nm_frecuencia_respiratoria` | INTEGER | rango [0, 200] rpm, nulo permitido | `NM_FRECUENCIA_RESPIRATORIA_FUERA_RANGO` cuando cae fuera del rango | |
| `nm_presion_arterial_sistolica` | INTEGER | rango [0, 560] mmHg, nulo permitido | `NM_PRESION_SISTOLICA_FUERA_RANGO` cuando cae fuera del rango, `NM_PRESION_INCOHERENTE` cuando la sistólica no supera a la diastólica | |
| `nm_presion_arterial_diastolica` | INTEGER | rango [0, 360] mmHg, nulo permitido | `NM_PRESION_DIASTOLICA_FUERA_RANGO` cuando cae fuera del rango, `NM_PRESION_INCOHERENTE` cuando la sistólica no supera a la diastólica | |
| `nm_temperatura` | FLOAT | rango [24.0, 45.0] °C, nulo permitido | `NM_TEMPERATURA_FUERA_RANGO` cuando cae fuera del rango | |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
+2 -3
View File
@@ -23,7 +23,7 @@ ESPECIALIDAD_ALIAS: dict[str, str] = {
class Parentesco(str, Enum):
AFILIADO = "Afiliado"
# TODO: otros valores pendientes de confirmar con el HIS
# Other values pending confirmation with the HIS administrator.
PARENTESCO_ALIAS: dict[str, str] = {
"AFILIADO": "Afiliado",
@@ -32,10 +32,9 @@ PARENTESCO_ALIAS: dict[str, str] = {
class Dependencia(str, Enum):
GOBIERNO = "GOBIERNO"
CALLES_Y_CAMINOS = "CALLES Y CAMINOS"
# TODO: valores tentativos — confirmar con administrador del HIS
# Tentative values, pending confirmation with the HIS administrator.
DEPENDENCIA_ALIAS: dict[str, str] = {
"CALLES Y CAMINOS": "CALLES Y CAMINOS",
}
# TODO: EstatusOrden -- valores pendientes de confirmar con administrador del HIS
+6 -3
View File
@@ -4,6 +4,7 @@ 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):
"""
@@ -17,14 +18,16 @@ class NotaMedica(CaCuModel, table=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",
description="rellenado por el loader via lookup en paciente.pac_id_hospital; puede quedar nulo",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.Text, index=True, nullable=False),
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.Text, nullable=False),
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
)
nm_nota_previa_id: Optional[str] = Field(
default=None,
+1 -18
View File
@@ -20,21 +20,4 @@ Tabla de órdenes, 1 fila por solicitud médica. Fuente: TC2 parcial, TVPH2, HPC
| `ord_especialidad` | Hospital, NM1 | Especialidad del médico solicitante |
| `ord_medico_solicitante` | Hospital, NM4 | Nombre o clave del médico tratante que emite la orden |
Validadores:
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| --------------------- | ------- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ----------------------------- |
| `ord_id` | INTEGER | entero positivo, autoincrement, no nulo | | |
| `pac_id` | INTEGER | entero positivo, FK hacia paciente, nulo si el lookup falla al momento de ingesta | | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo | | |
| `ord_numero_hospital` | INTEGER | entero de 5 dígitos, identificador de la orden en el HIS, índice único, no nulo | `ORD_NUMERO_AUSENTE` cuando la clave llega ausente del dict, `ORD_NUMERO_INVALIDO` cuando el valor no es convertible a entero | |
| `ord_tipo_estudio` | TEXT | valores pendientes de confirmar con administrador, nulo permitido. Candidatos: CITOLOGIA_CERVICAL, TAMIZAJE_VPH, BIOPSIA_CERVICAL | sin validador implementado | |
| `ord_fecha` | DATE | fecha de emisión de la orden por el médico, nulo permitido | sin validador implementado | |
| `ord_fecha_solicitud` | DATE | fecha sugerida por el médico para realizar el estudio, nulo permitido | sin validador implementado | |
| `ord_fecha_resultado` | DATE | fecha en que el resultado estuvo disponible, nulo permitido porque la orden puede existir sin resultado | sin validador implementado | |
| `ord_estatus` | TEXT | valores pendientes de confirmar con administrador, nulo permitido. Candidatos: SOLICITADO, EN_PROCESO, RESULTADO_DISPONIBLE, CANCELADO | sin validador implementado | |
| `ord_diagnostico` | TEXT | diagnóstico presuntivo del médico, pantalla Asignar diagnóstico, texto libre, nulo permitido | sin validador implementado | |
| `ord_observaciones` | TEXT | texto libre, nulo permitido | sin validador implementado | |
| `ord_especialidad` | TEXT | valores pendientes de confirmar con administrador, nulo permitido. Candidatos: GINECOLOGIA, ONCOLOGIA, MEDICINA_FAMILIAR, COLPOSCOPIA, OTRO | sin validador implementado | |
| `ord_medico_solicitante` | TEXT | nombre o clave del médico tratante, texto libre, nulo permitido | sin validador implementado | |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
+3 -2
View File
@@ -4,6 +4,7 @@ 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):
"""
@@ -20,9 +21,9 @@ class OrdenesEstudio(CaCuModel, table=True):
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("paciente.pac_id"), index=True),
)
# Desnormalizado para joins directos sin pasar por paciente
# Denormalized so studies join without going through paciente
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
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),
+2 -14
View File
@@ -6,22 +6,10 @@
| `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_fecha_defuncion` | Hospital, — | Fecha de defunción; nula mientras vive o si se desconoce |
| `pac_sexo` | Hospital, DG3 | Sexo biológico |
| `pac_codigo_postal` | Hospital, DG4 | Código postal de residencia |
| `pac_dependencia` | Hospital, DG5 | Unidad de cobertura o dependencia administrativa |
| `pac_parentesco` | Hospital, — | Parentesco del titular respecto al trabajador |
Validadores:
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| ---------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pac_id` | INTEGER | entero positivo, no nulo | `PAC_ID_AUSENTE` si el campo llega nulo, detectado por `fv:before` al requerir tipo `int` | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo | | |
| `pac_sexo` | TEXT | `SexoBiologico` enum, nulo permitido | `SEXO_INVALIDO` cuando el valor no corresponde a ninguna entrada del enum, normalizado en `fv:before` con strip y uppercase antes de la coerción | |
| `pac_fecha_nacimiento` | DATE | fecha, nulo permitido | `FECHA_NACIMIENTO_FUTURA` cuando la fecha es posterior a hoy, verificado en `fv:before fecha_nacimiento_no_futura` | `EDAD_FUERA_DE_RANGO` cuando la edad implícita cae fuera del rango de 1 a 110 años, evaluado en `mv:after edad_plausible_para_registro` una vez que la fecha fue validada |
| `pac_codigo_postal` | CHAR(5) | CP de 5 dígitos, nulo permitido. El ORM tiene una `CheckConstraint` REGEXP para el formato pero no está disponible en SQLite | sin validador implementado en schema | |
| `pac_dependencia` | TEXT | valores pendientes de confirmar con administrador, nulo permitido | sin validador implementado | |
| `pac_parentesco` | TEXT | texto libre, nulo permitido, sin fuente documentada | sin validador implementado | |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
+11 -5
View File
@@ -4,6 +4,7 @@ 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):
"""
@@ -14,15 +15,21 @@ class Paciente(CaCuModel, table=True):
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# Identificador original del paciente en el HIS (DG1) — indice unico para lookups confiables
# The patient's original HIS id (DG1), uniquely indexed for lookups
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.Text, unique=True, index=True, nullable=False),
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),
)
pac_fecha_nacimiento: Optional[date] = Field(
# 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),
)
# Survival's outcome and a competing risk; null while she is alive or the date is unknown.
pac_fecha_defuncion: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
@@ -30,7 +37,6 @@ class Paciente(CaCuModel, table=True):
default=None,
sa_column=sa.Column(
sa.CHAR(5),
# sa.CheckConstraint("pac_codigo_postal REGEXP '^[0-9]{5}$'"), # CheckConstraint con REGEXP no aplica en SQLite
),
description="Código postal de 5 dígitos",
)
@@ -42,7 +48,7 @@ class Paciente(CaCuModel, table=True):
pac_parentesco: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Parentesco", # descripción original decía Departamento — corregida
description="Parentesco",
)
+2 -3
View File
@@ -7,7 +7,6 @@ registry = orm.registry()
class CaMaModel(SQLModel, registry=registry):
"""Base class for every CaMa table.
Own SQLAlchemy registry/metadata so table names (e.g. NotaMedica) don't
collide with CaCu's identically-named tables now that both domains live
in the same Python package.
Uses its own SQLAlchemy registry so table names such as `notamedica`
don't collide with CaCu's tables of the same name.
"""
+1 -29
View File
@@ -31,32 +31,4 @@ Join hacia ordenes_estudio por ord_numero_hospital (lógico, sin FK constraint).
| `plaquetas_mil_ul` | Derivado, OCR sobre PDF BH1 | Conteo de plaquetas (miles/µL) |
| `vpm_fl` | Derivado, OCR sobre PDF BH1 | Volumen plaquetario medio (fL) |
Validadores:
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| ----------------------------- | ------- | ------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| `bh_id` | INTEGER | entero positivo, no nulo | `BH_ID_AUSENTE` si el campo llega nulo, detectado por `fv:before` al requerir tipo `int` | |
| `ord_numero_hospital` | INTEGER | entero positivo, no nulo, join lógico hacia ordenesstudio | `ORD_NUMERO_AUSENTE` si el campo llega nulo, `ORD_NUMERO_INVALIDO` si no es convertible a int | |
| `pac_id` | INTEGER | entero positivo, nulo permitido si el lookup por pac_id_hospital no resuelve al momento de carga | `PAC_ID_INVALIDO` si el valor no es convertible a int | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo | `PAC_ID_HOSPITAL_AUSENTE` si el campo llega nulo | |
| `bh_fecha` | DATE | fecha de solicitud del estudio, nulo permitido | sin validador implementado | |
| `eritrocitos_mill_ul` | FLOAT | rango [0, 25] millones/µL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera del rango [0, 25] | |
| `hemoglobina_g_dl` | FLOAT | rango [0.5, 75] g/dL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera del rango [0.5, 75]. `BH_HEMOGLOBINA_HEMATOCRITO` cuando `\|hto − 3×hb\| > 10`, evaluado en `mv:after validar_indices_eritrocitarios` | |
| `hematocrito_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_HEMOGLOBINA_HEMATOCRITO` cuando `\|hto − 3×hb\| > 10`, evaluado en `mv:after validar_indices_eritrocitarios` | |
| `vcm_fl` | FLOAT | rango [0, 400] fL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 400]. `BH_VCM_INCOHERENTE` cuando `vcm ≠ 10×hto/rbc` (tolerancia ±15% o ±5 fL), evaluado en `mv:after validar_indices_eritrocitarios` | |
| `hcm_pg` | FLOAT | rango [0, 100] pg, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_HCM_INCOHERENTE` cuando `hcm ≠ 10×hb/rbc` (tolerancia ±15% o ±3 pg), evaluado en `mv:after validar_indices_eritrocitarios` | |
| `chcm_g_dl` | FLOAT | rango [0, 100] g/dL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_CHCM_INCOHERENTE` cuando `chcm ≠ 100×hb/hto` (tolerancia ±15% o ±3 g/dL), evaluado en `mv:after validar_indices_eritrocitarios` | |
| `rdw_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100] | |
| `leucocitos_mil_ul` | FLOAT | rango [0, 500] miles/µL, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 500] | |
| `neutrofilos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_DIFERENCIAL_INVALIDO` cuando los cinco componentes básicos (neutrófilos, linfocitos, monocitos, eosinófilos, basófilos) suman ≠ 100% ± 2 pp, evaluado en `mv:after validar_diferencial` | |
| `linfocitos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DIFERENCIAL_INVALIDO` en neutrofilos_pct | |
| `monocitos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DIFERENCIAL_INVALIDO` en neutrofilos_pct | |
| `eosinofilos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DIFERENCIAL_INVALIDO` en neutrofilos_pct | |
| `basofilos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DIFERENCIAL_INVALIDO` en neutrofilos_pct | |
| `neutrofilos_segmentados_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. `BH_DESGLOSE_NEUTROFILICO` cuando segmentados + banda + metamielocitos + mielocitos ≠ neutrofilos_pct ± 2 pp, evaluado en `mv:after validar_diferencial` | |
| `neutrofilos_banda_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DESGLOSE_NEUTROFILICO` en neutrofilos_segmentados_pct | |
| `metamielocitos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DESGLOSE_NEUTROFILICO` en neutrofilos_segmentados_pct | |
| `mielocitos_pct` | FLOAT | porcentaje [0, 100], nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor cae fuera de [0, 100]. Ver `BH_DESGLOSE_NEUTROFILICO` en neutrofilos_segmentados_pct | |
| `plaquetas_mil_ul` | FLOAT | valor ≥ 0 miles/µL, sin máximo de plausibilidad, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor es negativo | |
| `vpm_fl` | FLOAT | valor ≥ 0 fL, sin máximo de plausibilidad, nulo permitido; cadenas numéricas normalizadas por `_numero_local` | `BH_CAMPO_INVALIDO` cuando el valor es negativo | |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
+6 -5
View File
@@ -4,6 +4,7 @@ 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):
@@ -16,20 +17,20 @@ class BiometriaHematica(CaMaModel, table=True):
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# join logico — resuelto por el loader via lookup en paciente.pac_id_hospital
# 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),
)
# Identificador del hospital — permite vincular estudios con pacientes
# Hospital patient id: links studies to patients
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# join logico hacia ordenes_estudio.ord_numero_hospital, sin FK constraint
# 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",
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
bh_fecha: Optional[date] = Field(
default=None,
+2 -14
View File
@@ -3,7 +3,7 @@ Una fila por reporte de biopsia mamaria · fuente: sistema estructurado + OCR/NL
| Columna | Fuente | Descripción |
| --------------------- | ------------------------------- | --------------------------------------------------------------------- |
| `bx_id` | Derivado, autoincrement | Llave primaria sustituta generada por SQLite |
| `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` |
@@ -15,16 +15,4 @@ Una fila por reporte de biopsia mamaria · fuente: sistema estructurado + OCR/NL
| `bx_pdf_blob` | Hospital, BX5 | Contenido binario del PDF del reporte histopatológico |
| `bx_ocr_confianza` | Derivado, pipeline OCR | Score de confianza del OCR sobre este documento |
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| --------------------- | ------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| `bx_id` | INTEGER | entero positivo, autoincrement, no nulo | `BX_ID_AUSENTE` si el campo llega nulo, detectado por `fv:before` al requerir tipo `int` | |
| `pac_id` | INTEGER | entero positivo, sin FK constraint, indexado, nulo permitido si el lookup falla al momento de ingesta | | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo en schema de validación, indexado | | |
| `ord_id` | INTEGER | FK formal a `ordenesestudio.ord_id`, indexado, nulo si el lookup falla | | |
| `ord_numero_hospital` | INTEGER | entero, clave de join para resolver `ord_id`, indexado, nulo permitido | | |
| `mast_id` | INTEGER | entero positivo, FK formal hacia mastografia con integridad referencial en SQLite, nulo permitido | | |
| `bx_fecha_solicitud` | DATE | fecha del sistema estructurado, nulo permitido | `BX_FECHA_SOLICITUD_FUTURA` cuando la fecha es posterior a hoy, verificado en `fv:before fechas_no_futuras` | |
| `bx_fecha_reporte` | DATE | fecha del sistema estructurado, nulo permitido | `BX_FECHA_REPORTE_FUTURA` cuando la fecha es posterior a hoy, verificado en `fv:before fechas_no_futuras`, `BX_REPORTE_ANTES_SOLICITUD` cuando el reporte es anterior a la solicitud, evaluado en `mv:after reporte_no_antes_de_solicitud` | |
| `bx_grado_histologico`| TEXT | `GradoHistologicoMama` enum, valores BENIGNO, CARCINOMA_IN_SITU, CARCINOMA_INVASOR, DESCONOCIDO, no nulo | `BX_GRADO_HISTOLOGICO_INVALIDO` cuando el valor no corresponde al enum tras normalización con strip y uppercase, evaluado en `fv:before normalizar_grado_histologico` | |
| `bx_pdf_blob` | BLOB | contenido binario del PDF, nulo permitido | | |
| `bx_ocr_confianza` | FLOAT | valor entre 0.0 y 1.0, nulo permitido | `BX_OCR_CONFIANZA_FUERA_RANGO` cuando cae fuera de [0.0, 1.0], verificado en `fv:before confianza_en_rango`, `BX_OCR_CONFIANZA_BAJA` cuando es inferior al umbral `BX_OCR_THRESHOLD` y el grado está presente, evaluado en `mv:after ocr_confianza_suficiente` | |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
+97 -6
View File
@@ -4,10 +4,11 @@ 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.
Modelo ORM para biopsia de mama. Fechas en sa.Date (sistema estructurado).
"""
bx_id: Optional[int] = Field(
default=None,
@@ -16,11 +17,11 @@ class BiopsiaMama(CaMaModel, table=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",
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.Text, nullable=False, index=True),
description="identificador hospitalario — obligatorio para vincular estudios con pacientes",
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,
@@ -30,7 +31,7 @@ class BiopsiaMama(CaMaModel, table=True):
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",
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
mast_id: Optional[int] = Field(
default=None,
@@ -48,14 +49,104 @@ class BiopsiaMama(CaMaModel, table=True):
default=None,
sa_column=sa.Column(sa.Text),
)
bx_tipo_histologico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_grado_nottingham: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_receptor_estrogeno: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_receptor_estrogeno_pct: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
bx_receptor_progesterona: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_receptor_progesterona_pct: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
bx_her2: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_her2_fish: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_ki67_pct: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
bx_tamano_tumor_mm: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
bx_ganglios_positivos: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
bx_invasion_linfovascular: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_multifocalidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_margenes: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_pt: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_pn: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_lateralidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_localizacion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_pdf_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(sa.LargeBinary),
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),
)
+1
View File
@@ -3,3 +3,4 @@ from core.cama.nota_medica.enums import TipoNota, TIPO_NOTA_ALIAS, Especialidad,
from core.cama.ordenes_estudio.enums import TipoEstudio, TIPO_ESTUDIO_ALIAS
from core.cama.biopsia_mama.enums import GradoHistologicoMama
from core.cama.mastografia.enums import BIRADS, BIRADS_ALIAS
from core.cama.episodio_clinico.enums import TipoEpisodio, TIPO_EPISODIO_ALIAS
+17
View File
@@ -0,0 +1,17 @@
from enum import Enum
class TipoEpisodio(str, Enum):
"""IND-02: la unidad de análisis para evaluación de desempeño del
modelo es un episodio de tamizaje, diagnóstico o tratamiento."""
TAMIZAJE = "TAMIZAJE"
DIAGNOSTICO = "DIAGNOSTICO"
TRATAMIENTO = "TRATAMIENTO"
TIPO_EPISODIO_ALIAS: dict[str, str] = {
"SCREENING": "TAMIZAJE",
"DIAGNOSTIC": "DIAGNOSTICO",
"TREATMENT": "TRATAMIENTO",
}
+62
View File
@@ -0,0 +1,62 @@
from datetime import date, datetime, timezone
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import HOSPITAL_ID_LENGTH
class EpisodioClinico(CaMaModel, table=True):
"""IND-02/IND-03: clinical episode for CaMa. Same structure as
`core.cacu.episodio_clinico.model.EpisodioClinico`."""
episodio_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
)
tipo_episodio: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="valor de core.cama.episodio_clinico.enums.TipoEpisodio guardado como texto",
)
nm_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("notamedica.nm_id"), index=True),
description="nota médica cuyo contenido escrito origina/documenta el episodio",
)
cie10_codigo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
especialidad_medica: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
evento_fecha: date = Field(
sa_column=sa.Column(sa.Date, nullable=False),
description="fecha del evento de interés que define el episodio",
)
ventana_inicio: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
ventana_fin: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
episodio_anterior_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("episodioclinico.episodio_id"), index=True),
)
created_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_column=sa.Column(sa.DateTime, nullable=False),
)
+218
View File
@@ -0,0 +1,218 @@
"""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 datetime import date
from core.cama.base import CaMaModel
from core.indicadores.cohortes import (
CohorteArmadoBase,
CohorteExclusionBase,
CohorteMiembroBase,
CohorteVariableBase,
EvaluacionRiesgoBase,
EvaluacionRiesgoLoteBase,
armado_unico,
evaluacion_unica,
variable_con_un_valor,
)
from core.indicadores.catalogos import (
CatEstudioBase,
CatMapeoBase,
CatResultadoBase,
CatSistemaFuenteBase,
CatValorBase,
estado_de_valor_conocido,
reglas_de_mapeo,
tipo_de_valor_conocido,
vigencia_ordenada,
)
from core.indicadores.plata import (
ObservacionClinicaBase,
ProcedimientoClinicoBase,
clase_conocida,
indice_de_observacion,
indice_de_procedimiento,
observacion_en_catalogo,
llave_de_observacion,
llave_de_procedimiento,
)
from core.indicadores.comunes import CargaBase, PeriodoObservacionBase, PersonaDerechohabienteBase
from core.indicadores.registro import (
DefParametroBase,
DimFechaBase,
DimGrupoEdadBase,
DimPeriodoBase,
)
from core.indicadores.publicacion import (
CatEstratoBase,
CatEstratoValorBase,
CatMeasureBase,
CatMeasureEstratoBase,
CatMeasureGrupoBase,
CatMeasureResultadoBase,
CatMeasureValorBase,
MeasureReportUnidadBase,
MeasureReportUnidadEstratoBase,
contrato_y_unidad_conocidos,
origen_conocido,
poblacion_conocida,
una_poblacion_por_indicador,
unidad_de_estrato_conocida,
valor_de_estrato_en_catalogo,
)
from core.indicadores.reportes import (
MeasureReportBase,
)
class Persona(CaMaModel, PersonaDerechohabienteBase, table=True):
__tablename__ = "persona"
fecha_defuncion: date | None = None # survival's outcome (`pac_fecha_defuncion`); null while alive or unknown
class PeriodoObservacion(CaMaModel, PeriodoObservacionBase, table=True):
__tablename__ = "periodo_observacion"
class Carga(CaMaModel, CargaBase, table=True):
__tablename__ = "carga"
class DefParametro(CaMaModel, DefParametroBase, table=True):
__tablename__ = "def_parametro"
class DimPeriodo(CaMaModel, DimPeriodoBase, table=True):
__tablename__ = "dim_periodo"
class DimFecha(CaMaModel, DimFechaBase, table=True):
__tablename__ = "dim_fecha"
class DimGrupoEdad(CaMaModel, DimGrupoEdadBase, table=True):
__tablename__ = "dim_grupo_edad"
class MeasureReport(CaMaModel, MeasureReportBase, table=True):
__tablename__ = "measure_report"
# --- El oro por unidad y su catálogo (§6f, MD-19) ---
class CatMeasure(CaMaModel, CatMeasureBase, table=True):
__tablename__ = "cat_measure"
__table_args__ = contrato_y_unidad_conocidos()
class CatMeasureResultado(CaMaModel, CatMeasureResultadoBase, table=True):
__tablename__ = "cat_measure_resultado"
__table_args__ = (poblacion_conocida(), una_poblacion_por_indicador())
class CatMeasureValor(CaMaModel, CatMeasureValorBase, table=True):
__tablename__ = "cat_measure_valor"
__table_args__ = (origen_conocido(),)
class CatMeasureGrupo(CaMaModel, CatMeasureGrupoBase, table=True):
__tablename__ = "cat_measure_grupo"
class CatEstrato(CaMaModel, CatEstratoBase, table=True):
__tablename__ = "cat_estrato"
__table_args__ = (unidad_de_estrato_conocida(),)
class CatEstratoValor(CaMaModel, CatEstratoValorBase, table=True):
__tablename__ = "cat_estrato_valor"
class CatMeasureEstrato(CaMaModel, CatMeasureEstratoBase, table=True):
__tablename__ = "cat_measure_estrato"
class MeasureReportUnidad(CaMaModel, MeasureReportUnidadBase, table=True):
__tablename__ = "measure_report_unidad"
class MeasureReportUnidadEstrato(CaMaModel, MeasureReportUnidadEstratoBase, table=True):
__tablename__ = "measure_report_unidad_estrato"
__table_args__ = (valor_de_estrato_en_catalogo(),)
# --- Catálogos de la plata (F1): estudio -> resultado -> valor, de core/catalogos/cama.toml ---
class CatEstudio(CaMaModel, CatEstudioBase, table=True):
__tablename__ = "cat_estudio"
class CatResultado(CaMaModel, CatResultadoBase, table=True):
__tablename__ = "cat_resultado"
__table_args__ = (tipo_de_valor_conocido(),)
class CatValor(CaMaModel, CatValorBase, table=True):
__tablename__ = "cat_valor"
__table_args__ = (estado_de_valor_conocido(),)
class CatSistemaFuente(CaMaModel, CatSistemaFuenteBase, table=True):
__tablename__ = "cat_sistema_fuente"
__table_args__ = (vigencia_ordenada("cat_sistema_fuente"),)
class CatMapeo(CaMaModel, CatMapeoBase, table=True):
__tablename__ = "cat_mapeo"
__table_args__ = reglas_de_mapeo()
# --- La plata de dos tablas (F5, ADR-MD-007) ---
class Procedimiento(CaMaModel, ProcedimientoClinicoBase, table=True):
__tablename__ = "procedimiento"
__table_args__ = (clase_conocida(), llave_de_procedimiento(), indice_de_procedimiento())
class Observacion(CaMaModel, ObservacionClinicaBase, table=True):
__tablename__ = "observacion_clinica" # `observacion` choca con la CTE `observacion` del motor (T-18r)
__table_args__ = (*observacion_en_catalogo(), llave_de_observacion(), indice_de_observacion())
# --- Cohortes para modelos y estimaciones de riesgo (oro restringido, ADR-MD-003; CaMa desde MD-12) ---
class CohorteArmado(CaMaModel, CohorteArmadoBase, table=True):
__tablename__ = "cohorte_armado"
__table_args__ = (armado_unico(),)
class CohorteMiembro(CaMaModel, CohorteMiembroBase, table=True):
__tablename__ = "cohorte_miembro"
class CohorteExclusion(CaMaModel, CohorteExclusionBase, table=True):
__tablename__ = "cohorte_exclusion"
class CohorteVariable(CaMaModel, CohorteVariableBase, table=True):
__tablename__ = "cohorte_variable"
__table_args__ = (variable_con_un_valor(),)
class EvaluacionRiesgoLote(CaMaModel, EvaluacionRiesgoLoteBase, table=True):
__tablename__ = "evaluacion_riesgo_lote"
class EvaluacionRiesgo(CaMaModel, EvaluacionRiesgoBase, table=True):
__tablename__ = "evaluacion_riesgo"
__table_args__ = (evaluacion_unica(),)
+2 -14
View File
@@ -3,7 +3,7 @@ Una fila por estudio de mastografía · fuente: DICOM + OCR/NLP sobre PDF de int
| Columna | Fuente | Descripción |
| --------------------- | ------------------------------- | ------------------------------------------------------------------ |
| `mast_id` | Derivado, autoincrement | Llave primaria sustituta generada por SQLite |
| `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` |
@@ -15,16 +15,4 @@ Una fila por estudio de mastografía · fuente: DICOM + OCR/NLP sobre PDF de int
| `mast_dicom_blob` | Hospital, IM6 | Contenido binario del archivo DICOM |
| `mast_interpretacion` | Hospital, IM5 | Enlace o referencia a la interpretación del radiólogo |
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| --------------------- | ------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| `mast_id` | INTEGER | entero positivo, autoincrement, no nulo | `MAST_ID_AUSENTE` si el campo llega nulo, detectado por `fv:before` al requerir tipo `int` | |
| `pac_id` | INTEGER | entero positivo, sin FK constraint, indexado, nulo permitido si el lookup falla al momento de ingesta | | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo en schema de validación, indexado | | |
| `ord_id` | INTEGER | FK formal a `ordenesestudio.ord_id`, indexado, nulo si el lookup falla | | |
| `ord_numero_hospital` | INTEGER | entero, join lógico hacia ordenes_estudio sin FK constraint, indexado, nulo permitido | | |
| `mast_fecha_toma` | DATE | fecha entregada por DICOM, nulo permitido | `MAST_FECHA_TOMA_FUTURA` cuando la fecha es posterior a hoy, evaluado en `mv:after fechas_plausibles` | |
| `mast_fecha_reporte` | DATE | fecha del reporte, nulo permitido | `MAST_FECHA_REPORTE_FUTURA` cuando la fecha es posterior a hoy, `MAST_FECHA_REPORTE_ANTERIOR` cuando es anterior a la toma, ambos evaluados en `mv:after fechas_plausibles` | |
| `mast_calidad_imagen` | TEXT | texto libre normalizado con strip y uppercase, nulo permitido, valores reales pendientes de confirmar | | |
| `mast_birads` | TEXT | `BIRADS` enum, nulo permitido, valores B0 a B6, resolución de alias DICOM en `BIRADS_ALIAS` | `MAST_BIRADS_INVALIDO` cuando el valor no corresponde al enum ni a ninguna entrada del alias, evaluado en `fv:before normalizar_birads` | |
| `mast_dicom_blob` | BLOB | contenido binario del archivo DICOM, nulo permitido | | |
| `mast_interpretacion` | TEXT | enlace o referencia a la interpretación del radiólogo, nulo permitido, formato pendiente de confirmar | | |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
+16 -7
View File
@@ -1,13 +1,13 @@
from enum import Enum
class BIRADS(str, Enum):
B0 = "B0" # incompleto
B1 = "B1" # negativo
B2 = "B2" # hallazgo benigno
B3 = "B3" # probablemente benigno
B4 = "B4" # sospechoso
B5 = "B5" # altamente sospechoso
B6 = "B6" # malignidad confirmada
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",
@@ -15,6 +15,15 @@ BIRADS_ALIAS: dict[str, str] = {
"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):
+19 -6
View File
@@ -4,6 +4,7 @@ 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):
"""
@@ -16,11 +17,11 @@ class Mastografia(CaMaModel, table=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",
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.Text, nullable=False, index=True),
description="identificador hospitalario — obligatorio para vincular estudios con pacientes",
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,
@@ -30,7 +31,7 @@ class Mastografia(CaMaModel, table=True):
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",
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
mast_fecha_toma: Optional[date] = Field(
default=None,
@@ -50,12 +51,24 @@ class Mastografia(CaMaModel, table=True):
)
mast_dicom_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(sa.LargeBinary),
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",
description="enlace o referencia a la interpretación del radiólogo; formato pendiente",
)
mast_densidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
mast_margen_masa: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
mast_tipo_hallazgo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
+6
View File
@@ -4,6 +4,9 @@ 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
from core.cama.tratamiento_mama.model import TratamientoMama
from core.cama.seguimiento_mama.model import SeguimientoMama
__all__ = [
"Paciente",
@@ -12,4 +15,7 @@ __all__ = [
"BiopsiaMama",
"NotaMedica",
"BiometriaHematica",
"EpisodioClinico",
"TratamientoMama",
"SeguimientoMama",
]
+1 -29
View File
@@ -32,32 +32,4 @@
---
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
|---|---|---|---|---|
| `nm_id` | INTEGER | entero positivo, autoincrement, no nulo | `NM_ID_AUSENTE` si el campo llega nulo | |
| `pac_id` | INTEGER | entero positivo, indexado, nulo permitido | `PAC_ID_AUSENTE`, `PAC_ID_INVALIDO` | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, indexado, no nulo en schema de validación | | |
| `nm_id_hospital` | TEXT | alfanumérico, no nulo en schema de validación; normalizado con strip y uppercase | `NM_ID_HOSPITAL_AUSENTE` cuando llega nulo | |
| `nm_nota_previa_id` | TEXT | alfanumérico, nulo si es nota inaugural; normalizado con strip | | |
| `nm_tipo_nota` | TEXT | `TipoNota` enum: CONSULTA, EGRESO, INGRESO, URG_EGRESO; alias TIPO_NOTA_ALIAS resuelve variantes HIS ("URG. EGRESO"); no nulo | `NM_TIPO_NOTA_AUSENTE` cuando llega nulo, `NM_TIPO_NOTA_INVALIDA` cuando el valor no corresponde al enum tras normalización | |
| `nm_especialidad` | TEXT | `Especialidad` enum: MEDICINA_FAMILIAR, CIRUGIA_ONCOLOGICA, CLINICA_MUJER_COLPOSCOPIA; alias ESPECIALIDAD_ALIAS resuelve variantes HIS; no nulo | `NM_ESPECIALIDAD_AUSENTE` cuando llega nulo, `NM_ESPECIALIDAD_INVALIDA` cuando el valor no corresponde al enum tras normalización | |
| `nm_fecha` | DATE | fecha de la consulta, no nulo en schema de validación | `NM_FECHA_AUSENTE` cuando llega nulo, `NM_FECHA_FUTURA` cuando es posterior a hoy | |
| `nm_medico_tratante` | TEXT | texto libre, máximo 100 caracteres, nulo permitido | `NM_MEDICO_TRATANTE_INVALIDO` cuando supera 100 caracteres | |
| `nm_motivo_consulta` | TEXT | texto libre, no nulo en schema de validación; normalizado con strip | `NM_MOTIVO_CONSULTA_AUSENTE` cuando llega nulo | |
| `nm_interrogatorio` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_diagnostico_texto` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_cie_codigo` | TEXT | formato `[A-Z][0-9]{2}(\.[0-9]{1,2})?`, nulo permitido | `NM_CIE_CODIGO_INVALIDO` cuando no cumple el formato regex | |
| `nm_cie_descripcion` | TEXT | texto libre, máximo 200 caracteres, nulo permitido | `NM_CIE_DESCRIPCION_INVALIDA` cuando supera 200 caracteres | |
| `nm_tratamiento_texto` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_receta` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_plan_estudios` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_pronostico` | TEXT | texto libre normalizado con strip y uppercase, nulo permitido | | |
| `nm_observaciones` | TEXT | texto libre, nulo permitido; normalizado con strip | | |
| `nm_masa_corporal` | FLOAT | rango [20.0, 300.0] kg, nulo permitido | `NM_MASA_CORPORAL_FUERA_RANGO` cuando cae fuera del rango | |
| `nm_talla` | FLOAT | rango [100, 250] cm, nulo permitido | `NM_TALLA_FUERA_RANGO` cuando cae fuera del rango | |
| `nm_imc_visita` | FLOAT | rango [12.0, 90.0], nulo si peso o talla ausentes | `NM_IMC_FUERA_RANGO` cuando cae fuera del rango, `NM_IMC_INCOHERENTE` cuando no corresponde a peso/talla registrados (tolerancia ±0.5) | |
| `nm_frecuencia_cardiaca` | INTEGER | rango [0, 500] lpm, nulo permitido | `NM_FRECUENCIA_CARDIACA_FUERA_RANGO` cuando cae fuera del rango | |
| `nm_frecuencia_respiratoria` | INTEGER | rango [0, 200] rpm, nulo permitido | `NM_FRECUENCIA_RESPIRATORIA_FUERA_RANGO` cuando cae fuera del rango | |
| `nm_presion_arterial_sistolica` | INTEGER | rango [0, 560] mmHg, nulo permitido | `NM_PRESION_SISTOLICA_FUERA_RANGO` cuando cae fuera del rango, `NM_PRESION_INCOHERENTE` cuando la sistólica no supera a la diastólica | |
| `nm_presion_arterial_diastolica` | INTEGER | rango [0, 360] mmHg, nulo permitido | `NM_PRESION_DIASTOLICA_FUERA_RANGO` cuando cae fuera del rango, `NM_PRESION_INCOHERENTE` cuando la sistólica no supera a la diastólica | |
| `nm_temperatura` | FLOAT | rango [24.0, 45.0] °C, nulo permitido | `NM_TEMPERATURA_FUERA_RANGO` cuando cae fuera del rango | |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
+2 -3
View File
@@ -23,7 +23,7 @@ ESPECIALIDAD_ALIAS: dict[str, str] = {
class Parentesco(str, Enum):
AFILIADO = "Afiliado"
# TODO: otros valores pendientes de confirmar con el HIS
# Other values pending confirmation with the HIS administrator.
PARENTESCO_ALIAS: dict[str, str] = {
"AFILIADO": "Afiliado",
@@ -32,10 +32,9 @@ PARENTESCO_ALIAS: dict[str, str] = {
class Dependencia(str, Enum):
GOBIERNO = "GOBIERNO"
CALLES_Y_CAMINOS = "CALLES Y CAMINOS"
# TODO: valores tentativos — confirmar con administrador del HIS
# Tentative values, pending confirmation with the HIS administrator.
DEPENDENCIA_ALIAS: dict[str, str] = {
"CALLES Y CAMINOS": "CALLES Y CAMINOS",
}
# TODO: EstatusOrden -- valores pendientes de confirmar con administrador del HIS
+14 -3
View File
@@ -4,6 +4,7 @@ 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):
"""
@@ -17,14 +18,16 @@ class NotaMedica(CaMaModel, table=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",
description="rellenado por el loader via lookup en paciente.pac_id_hospital; puede quedar nulo",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.Text, index=True, nullable=False),
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.Text, nullable=False),
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
)
nm_nota_previa_id: Optional[str] = Field(
default=None,
@@ -66,6 +69,14 @@ class NotaMedica(CaMaModel, table=True):
default=None,
sa_column=sa.Column(sa.Text),
)
nm_estadio_clinico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_metastasis: 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),
+1 -18
View File
@@ -20,21 +20,4 @@ Tabla de órdenes, 1 fila por solicitud médica. Fuente: TC2 parcial, TVPH2, HPC
| `ord_especialidad` | Hospital, NM1 | Especialidad del médico solicitante |
| `ord_medico_solicitante` | Hospital, NM4 | Nombre o clave del médico tratante que emite la orden |
Validadores:
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| --------------------- | ------- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ----------------------------- |
| `ord_id` | INTEGER | entero positivo, autoincrement, no nulo | | |
| `pac_id` | INTEGER | entero positivo, FK hacia paciente, nulo si el lookup falla al momento de ingesta | | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo | | |
| `ord_numero_hospital` | INTEGER | entero de 5 dígitos, identificador de la orden en el HIS, índice único, no nulo | `ORD_NUMERO_AUSENTE` cuando la clave llega ausente del dict, `ORD_NUMERO_INVALIDO` cuando el valor no es convertible a entero | |
| `ord_tipo_estudio` | TEXT | valores pendientes de confirmar con administrador, nulo permitido. Candidatos: CITOLOGIA_CERVICAL, TAMIZAJE_VPH, BIOPSIA_CERVICAL | sin validador implementado | |
| `ord_fecha` | DATE | fecha de emisión de la orden por el médico, nulo permitido | sin validador implementado | |
| `ord_fecha_solicitud` | DATE | fecha sugerida por el médico para realizar el estudio, nulo permitido | sin validador implementado | |
| `ord_fecha_resultado` | DATE | fecha en que el resultado estuvo disponible, nulo permitido porque la orden puede existir sin resultado | sin validador implementado | |
| `ord_estatus` | TEXT | valores pendientes de confirmar con administrador, nulo permitido. Candidatos: SOLICITADO, EN_PROCESO, RESULTADO_DISPONIBLE, CANCELADO | sin validador implementado | |
| `ord_diagnostico` | TEXT | diagnóstico presuntivo del médico, pantalla Asignar diagnóstico, texto libre, nulo permitido | sin validador implementado | |
| `ord_observaciones` | TEXT | texto libre, nulo permitido | sin validador implementado | |
| `ord_especialidad` | TEXT | valores pendientes de confirmar con administrador, nulo permitido. Candidatos: GINECOLOGIA, ONCOLOGIA, MEDICINA_FAMILIAR, COLPOSCOPIA, OTRO | sin validador implementado | |
| `ord_medico_solicitante` | TEXT | nombre o clave del médico tratante, texto libre, nulo permitido | sin validador implementado | |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
+1
View File
@@ -1,6 +1,7 @@
from enum import Enum
class TipoEstudio(str, Enum):
MASTOGRAFIA = "MASTOGRAFIA" # the study this domain orders
BIOPSIA_CHICA = "BIOPSIA_CHICA"
SOLICITUD_PAPANICOLAO_BASE_LIQUIDA = "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA"
+3 -2
View File
@@ -4,6 +4,7 @@ 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):
"""
@@ -20,9 +21,9 @@ class OrdenesEstudio(CaMaModel, table=True):
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("paciente.pac_id"), index=True),
)
# Desnormalizado para joins directos sin pasar por paciente
# Denormalized so studies join without going through paciente
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
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),
+2 -14
View File
@@ -7,21 +7,9 @@
| `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_fecha_defuncion` | Hospital, — | Fecha de defunción; nula mientras vive o si se desconoce |
| `pac_codigo_postal` | Hospital, DG4 | Código postal de residencia |
| `pac_dependencia` | Hospital, DG5 | Unidad de cobertura o dependencia administrativa |
| `pac_parentesco` | Hospital, — | Parentesco del titular respecto al trabajador |
Validadores:
| Columna | DB type | Dominio / Valores / Nullable | Razones de exclusión por calidad | Razones de exclusión clínicas |
| ---------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pac_id` | INTEGER | entero positivo, no nulo | `PAC_ID_AUSENTE` si el campo llega nulo, detectado por `fv:before` al requerir tipo `int` | |
| `pac_id_hospital` | TEXT | alfanumérico HIS, no nulo | | |
| `pac_sexo` | TEXT | `SexoBiologico` enum, nulo permitido | `SEXO_INVALIDO` cuando el valor no corresponde a ninguna entrada del enum, normalizado en `fv:before` con strip y uppercase antes de la coerción | |
| `pac_fecha_nacimiento` | DATE | fecha, nulo permitido | `FECHA_NACIMIENTO_FUTURA` cuando la fecha es posterior a hoy, verificado en `fv:before fecha_nacimiento_no_futura` | `EDAD_FUERA_DE_RANGO` cuando la edad implícita cae fuera del rango de 1 a 110 años, evaluado en `mv:after edad_plausible_para_registro` una vez que la fecha fue validada |
| `pac_codigo_postal` | CHAR(5) | CP de 5 dígitos, nulo permitido. El ORM tiene una `CheckConstraint` REGEXP para el formato pero no está disponible en SQLite | sin validador implementado en schema | |
| `pac_dependencia` | TEXT | valores pendientes de confirmar con administrador, nulo permitido | sin validador implementado | |
| `pac_parentesco` | TEXT | texto libre, nulo permitido, sin fuente documentada | sin validador implementado | |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
+59 -5
View File
@@ -4,6 +4,7 @@ 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):
"""
@@ -14,23 +15,76 @@ class Paciente(CaMaModel, table=True):
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# Identificador original del paciente en el HIS (DG1) — indice unico para lookups confiables
# The patient's original HIS id (DG1), uniquely indexed for lookups
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.Text, unique=True, index=True, nullable=False),
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),
)
pac_fecha_nacimiento: Optional[date] = Field(
# 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),
)
# Survival's outcome; null while she is alive or the date is unknown.
pac_fecha_defuncion: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
pac_estado_civil: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_raza: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_brca1: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_brca2: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_estado_menopausico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_pam50: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_subtipo_clinico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_cluster_integrativo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_celularidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_carga_mutacional: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
pac_ki67_categoria: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_fuente: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_codigo_postal: Optional[str] = Field(
default=None,
sa_column=sa.Column(
sa.CHAR(5),
sa.CheckConstraint("pac_codigo_postal REGEXP '^[0-9]{5}$'"), # CheckConstraint con REGEXP no aplica en SQLite
),
description="Código postal de 5 dígitos",
)
@@ -42,7 +96,7 @@ class Paciente(CaMaModel, table=True):
pac_parentesco: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Parentesco", # descripción original decía Departamento — corregida
description="Parentesco",
)
+39
View File
@@ -0,0 +1,39 @@
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 SeguimientoMama(CaMaModel, table=True):
"""
Un hecho del seguimiento de la paciente: una recaída o el último contacto, con su fecha.
`seg_tipo` es el estudio del catálogo (`recurrencia`, `ultimo_contacto`); `seg_detalle`, su resultado:
el sitio de la recaída.
"""
seg_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",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
)
seg_tipo: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
)
seg_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
seg_detalle: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
+43
View File
@@ -0,0 +1,43 @@
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 TratamientoMama(CaMaModel, table=True):
"""
Un tratamiento del cáncer de mama: una cirugía, un curso de radioterapia o uno de quimioterapia, con su fecha.
`trat_tipo` es el estudio del catálogo (`cirugia`, `radioterapia`, `quimioterapia`); `trat_detalle`, su resultado:
el tipo de cirugía o la intención del curso.
"""
trat_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",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
)
trat_tipo: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
)
trat_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
trat_detalle: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
trat_lateralidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
+43
View File
@@ -0,0 +1,43 @@
# Catálogos de la plata (F1)
Un TOML por proyecto: estudio → resultado → valor.
El paso `catalogos` de `webapi.orchestration` los materializa en `cat_estudio`, `cat_resultado` y `cat_valor`
(`core/indicadores/catalogos.py`) antes de cargar. Un valor que sale del TOML pasa a `retirado`; nunca se borra.
```toml
[<estudio>]
etiqueta = "..."
codigos_hospital = ["..."] # cómo lo nombra el hospital (tipo de estudio de la orden, instrumento)
[<estudio>.resultados.<resultado>] # resultado_id = "<estudio>.<resultado>"
etiqueta = "..."
tipo_valor = "codigo" # codigo, booleano, numero, fecha, texto, externo
unidad = "min" # opcional (numero)
sistema = "CIE-10" # externo o codigo: el sistema de códigos de sus valores
valores = [ # solo codigo; el orden de la lista es el de presentación
{ valor = "NORMAL", etiqueta = "Normal" },
]
```
A result read from a document's text (a report's interpretation, a PDF's text layer, a note) also says how it's
printed. These keys don't reach any table; the silver load reads them (`webapi.orchestration.silver.extracted`):
```toml
[<estudio>.resultados.<resultado>]
etiquetas_fuente = ["Densidad mamaria", "Densidad"] # the captions it's printed under
buscar_en_texto = true # codigo only: also as a mention anywhere in the text
provisional = true # captions and spellings not yet confirmed with the hospital's documents
valores = [
{ valor = "C", etiqueta = "Heterogéneamente densa", alias = ["Tipo C", "ACR C"] }, # each spelling of the value
]
```
A spelling with no alias is stored as `valor_fuente` without `valor_id` and counted as out of catalog; adding it
as an alias and reloading turns it into the code. One spelling on two values of a result is rejected.
A coded result with `sistema` takes its `valor` from that code system as the system writes it (`8500/3` in CIE-O-3,
`T1c` in TNM-AJCC, `C504` in CIE-10): the code is what other systems exchange, and how the hospital or a lab prints
it goes in `alias` or, per source, in `cat_mapeo`. A result without `sistema` uses the project's own codes.
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.
+149
View File
@@ -0,0 +1,149 @@
# 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 = "codigo"
valores = [
{ valor = "AGC", etiqueta = "Células glandulares atípicas (AGC)" },
{ valor = "ADENOCARCINOMA", etiqueta = "Adenocarcinoma" },
]
[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)" },
]
File diff suppressed because it is too large Load Diff
+581
View File
@@ -0,0 +1,581 @@
# TEA's catalog: the studies of the screening (M-CHAT, ADOS-2, neuropediatrics note, EEG) and their results.
# Values are Core's enums (`core/tea/enums.py`). `codigos_hospital` are the codes of `ord_tipo_estudio`: an order's
# `estudio_id` is the study it asks for.
[mchat]
etiqueta = "M-CHAT-R/F"
[mchat.resultados.puntaje]
etiqueta = "Puntaje total"
tipo_valor = "numero"
unidad = "puntos"
# The ADOS-2: module, algorithm, classification, CSS and the algorithm items. An item's domain is its prefix:
# `sa_` social affect, `rrb_` restricted and repetitive behaviour. Labels of the items without a published short name
# wait for the hospital's manuals.
[ados2]
etiqueta = "Evaluación psicológica (ADOS-2)"
codigos_hospital = ["ADOS2"]
[ados2.resultados.modulo]
etiqueta = "Módulo"
tipo_valor = "codigo"
valores = [
{ valor = "TODDLER", etiqueta = "Módulo T (niños pequeños)" },
{ valor = "MODULO_1", etiqueta = "Módulo 1" },
{ valor = "MODULO_2", etiqueta = "Módulo 2" },
{ valor = "MODULO_3", etiqueta = "Módulo 3" },
]
[ados2.resultados.algoritmo]
etiqueta = "Algoritmo"
tipo_valor = "texto"
[ados2.resultados.clasificacion]
etiqueta = "Clasificación"
tipo_valor = "codigo"
valores = [
{ valor = "NO_ESPECTRO", etiqueta = "No espectro" },
{ valor = "ESPECTRO_AUTISTA", etiqueta = "Espectro autista" },
{ valor = "AUTISMO", etiqueta = "Autismo" },
{ valor = "PREOCUPACION_LEVE_MODERADA", etiqueta = "Preocupación leve a moderada" },
{ valor = "PREOCUPACION_SEVERA", etiqueta = "Preocupación moderada a severa" },
]
[ados2.resultados.css]
etiqueta = "Puntaje de severidad (CSS)"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_a2]
etiqueta = "Frecuencia de la vocalización espontánea dirigida a otros"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_a6]
etiqueta = "Uso del cuerpo de otra persona para comunicarse"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_a7]
etiqueta = "Señalar"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_a8]
etiqueta = "Gestos"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b1]
etiqueta = "Contacto visual inusual"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b2]
etiqueta = "Sonrisa social en respuesta"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b3]
etiqueta = "Expresiones faciales dirigidas a otros"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b4]
etiqueta = "Integración de la mirada y otras conductas en las iniciaciones sociales"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b5]
etiqueta = "Placer compartido durante la interacción"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b6]
etiqueta = "Respuesta al nombre"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b7]
etiqueta = "Pedir"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b8]
etiqueta = "Dar"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b9]
etiqueta = "Mostrar"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b10]
etiqueta = "Iniciación espontánea de la atención conjunta"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b11]
etiqueta = "Respuesta a la atención conjunta"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b12]
etiqueta = "Calidad de los acercamientos sociales"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b13]
etiqueta = "Reactivo B13"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b14]
etiqueta = "Reactivo B14"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b15]
etiqueta = "Reactivo B15"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b16b]
etiqueta = "Reactivo B16b"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.sa_b18]
etiqueta = "Reactivo B18"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.rrb_a3]
etiqueta = "Entonación de las vocalizaciones o verbalizaciones"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.rrb_a4]
etiqueta = "Ecolalia inmediata"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.rrb_a5]
etiqueta = "Uso estereotipado o idiosincrásico de palabras o frases"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.rrb_d1]
etiqueta = "Interés sensorial inusual en los materiales de juego o en las personas"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.rrb_d2]
etiqueta = "Manierismos de manos, dedos y otros manierismos complejos"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.rrb_d4]
etiqueta = "Intereses inusualmente repetitivos o conductas estereotipadas"
tipo_valor = "numero"
unidad = "puntos"
[ados2.resultados.rrb_d5]
etiqueta = "Reactivo D5"
tipo_valor = "numero"
unidad = "puntos"
[evaluacion_neuropediatrica]
etiqueta = "Evaluación neuropediátrica"
codigos_hospital = ["NEUROPEDIATRIA"]
[evaluacion_neuropediatrica.resultados.diagnostico]
etiqueta = "Diagnóstico"
tipo_valor = "externo"
sistema = "CIE-10"
# The EEG: what its analysis (the `tea` library) writes. On the recording (`toma`): the verdict, triage level, clean
# fraction, sleep, channels, duration and line noise; each study-wide quality check (`calidad_<check>`, with
# `_anormal`, `_decisivo` and its limit, `_bajo` or `_alto`); and each metric's value with, against its age baseline, its z
# (`_z`), -1/0/+1 (`_fuera`), the curve's p5, median and p95 there and the registered label of the baseline that curve
# belongs to (`_modelo`). On each bad channel (`parte`, `codigo_fuente` the electrode): the check that flagged it, with
# the library's reason. On each electrode of a metric (`parte`, `codigo_fuente` the electrode): the metric's value and z
# there, under the same results.
[eeg]
etiqueta = "Electroencefalograma"
codigos_hospital = ["EEG"]
[eeg.resultados.valido]
etiqueta = "EEG válido para el estudio"
tipo_valor = "booleano"
[eeg.resultados.nivel]
etiqueta = "Nivel de triaje"
tipo_valor = "texto"
[eeg.resultados.fraccion_limpia]
etiqueta = "Fracción del registro limpia"
tipo_valor = "numero"
unidad = "fracción"
[eeg.resultados.canales_malos]
etiqueta = "Canales malos"
tipo_valor = "numero"
unidad = "canales"
[eeg.resultados.edad_meses]
etiqueta = "Edad al estudio"
tipo_valor = "numero"
unidad = "meses"
[eeg.resultados.con_sueno]
etiqueta = "Registro con sueño"
tipo_valor = "booleano"
[eeg.resultados.canales]
etiqueta = "Canales"
tipo_valor = "numero"
unidad = "canales"
[eeg.resultados.duracion_min]
etiqueta = "Duración del registro"
tipo_valor = "numero"
unidad = "min"
[eeg.resultados.ruido_linea]
etiqueta = "Ruido de la línea eléctrica"
tipo_valor = "numero"
unidad = "dB"
[eeg.resultados.calidad_clean_windows]
etiqueta = "Ventanas limpias"
tipo_valor = "numero"
unidad = "%"
[eeg.resultados.calidad_clean_windows_anormal]
etiqueta = "Ventanas limpias: fuera de rango"
tipo_valor = "booleano"
[eeg.resultados.calidad_clean_windows_decisivo]
etiqueta = "Ventanas limpias: basta para invalidar el EEG"
tipo_valor = "booleano"
[eeg.resultados.calidad_clean_windows_bajo]
etiqueta = "Ventanas limpias: límite inferior"
tipo_valor = "numero"
unidad = "%"
[eeg.resultados.calidad_internal_coverage]
etiqueta = "Cobertura interna"
tipo_valor = "numero"
unidad = "fracción"
[eeg.resultados.calidad_internal_coverage_anormal]
etiqueta = "Cobertura interna: fuera de rango"
tipo_valor = "booleano"
[eeg.resultados.calidad_internal_coverage_decisivo]
etiqueta = "Cobertura interna: basta para invalidar el EEG"
tipo_valor = "booleano"
[eeg.resultados.calidad_internal_coverage_bajo]
etiqueta = "Cobertura interna: límite inferior"
tipo_valor = "numero"
unidad = "fracción"
[eeg.resultados.calidad_bad_scalp_triage]
etiqueta = "Electrodos del cuero cabelludo inservibles"
tipo_valor = "numero"
unidad = "electrodos"
[eeg.resultados.calidad_bad_scalp_triage_anormal]
etiqueta = "Electrodos del cuero cabelludo inservibles: fuera de rango"
tipo_valor = "booleano"
[eeg.resultados.calidad_bad_scalp_triage_decisivo]
etiqueta = "Electrodos del cuero cabelludo inservibles: basta para invalidar el EEG"
tipo_valor = "booleano"
[eeg.resultados.calidad_bad_scalp_triage_alto]
etiqueta = "Electrodos del cuero cabelludo inservibles: límite superior"
tipo_valor = "numero"
unidad = "electrodos"
[eeg.resultados.calidad_usable_scalp]
etiqueta = "Electrodos del cuero cabelludo útiles"
tipo_valor = "numero"
unidad = "electrodos"
[eeg.resultados.calidad_usable_scalp_anormal]
etiqueta = "Electrodos del cuero cabelludo útiles: fuera de rango"
tipo_valor = "booleano"
[eeg.resultados.calidad_usable_scalp_decisivo]
etiqueta = "Electrodos del cuero cabelludo útiles: basta para invalidar el EEG"
tipo_valor = "booleano"
[eeg.resultados.calidad_usable_scalp_bajo]
etiqueta = "Electrodos del cuero cabelludo útiles: límite inferior"
tipo_valor = "numero"
unidad = "electrodos"
[eeg.resultados.calidad_triage_level]
etiqueta = "Nivel de triaje"
tipo_valor = "texto"
[eeg.resultados.calidad_triage_level_anormal]
etiqueta = "Nivel de triaje: fuera de rango"
tipo_valor = "booleano"
[eeg.resultados.calidad_triage_level_decisivo]
etiqueta = "Nivel de triaje: basta para invalidar el EEG"
tipo_valor = "booleano"
[eeg.resultados.calidad_line_noise]
etiqueta = "Ruido de la línea eléctrica"
tipo_valor = "numero"
unidad = "dB"
[eeg.resultados.calidad_line_noise_anormal]
etiqueta = "Ruido de la línea eléctrica: fuera de rango"
tipo_valor = "booleano"
[eeg.resultados.calidad_line_noise_decisivo]
etiqueta = "Ruido de la línea eléctrica: basta para invalidar el EEG"
tipo_valor = "booleano"
[eeg.resultados.calidad_line_noise_alto]
etiqueta = "Ruido de la línea eléctrica: límite superior"
tipo_valor = "numero"
unidad = "dB"
[eeg.resultados.calidad_file]
etiqueta = "Archivo EDF"
tipo_valor = "texto"
[eeg.resultados.calidad_file_anormal]
etiqueta = "Archivo EDF: fuera de rango"
tipo_valor = "booleano"
[eeg.resultados.calidad_file_decisivo]
etiqueta = "Archivo EDF: basta para invalidar el EEG"
tipo_valor = "booleano"
[eeg.resultados.calidad_dead_channel]
etiqueta = "Canal muerto"
tipo_valor = "texto"
[eeg.resultados.calidad_frozen]
etiqueta = "Señal congelada"
tipo_valor = "texto"
[eeg.resultados.calidad_saturated]
etiqueta = "Señal saturada"
tipo_valor = "texto"
[eeg.resultados.calidad_inf_values]
etiqueta = "Valores infinitos"
tipo_valor = "texto"
[eeg.resultados.calidad_own_gaps]
etiqueta = "Huecos propios"
tipo_valor = "texto"
[eeg.resultados.calidad_bridge]
etiqueta = "Puente con otro electrodo"
tipo_valor = "texto"
[eeg.resultados.calidad_amplitude]
etiqueta = "Amplitud anómala frente al cuero cabelludo"
tipo_valor = "texto"
[eeg.resultados.calidad_aux_amplitude]
etiqueta = "Amplitud fuera de rango (canal auxiliar)"
tipo_valor = "texto"
[eeg.resultados.calidad_does_not_correlate]
etiqueta = "Sin correlación con sus vecinos"
tipo_valor = "texto"
[eeg.resultados.calidad_intermittent_contact]
etiqueta = "Contacto intermitente"
tipo_valor = "texto"
[eeg.resultados.calidad_intermittent_bursts]
etiqueta = "Contacto intermitente por ráfagas"
tipo_valor = "texto"
[eeg.resultados.ritmo_posterior]
etiqueta = "Ritmo posterior"
tipo_valor = "numero"
unidad = "Hz"
[eeg.resultados.ritmo_posterior_z]
etiqueta = "Ritmo posterior: puntaje z"
tipo_valor = "numero"
unidad = "z"
[eeg.resultados.ritmo_posterior_fuera]
etiqueta = "Ritmo posterior: fuera de la referencia (-1, 0, +1)"
tipo_valor = "numero"
[eeg.resultados.ritmo_posterior_p5]
etiqueta = "Ritmo posterior: percentil 5 de la referencia"
tipo_valor = "numero"
unidad = "Hz"
[eeg.resultados.ritmo_posterior_mediana]
etiqueta = "Ritmo posterior: mediana de la referencia"
tipo_valor = "numero"
unidad = "Hz"
[eeg.resultados.ritmo_posterior_p95]
etiqueta = "Ritmo posterior: percentil 95 de la referencia"
tipo_valor = "numero"
unidad = "Hz"
[eeg.resultados.ritmo_posterior_modelo]
etiqueta = "Ritmo posterior: modelo de la referencia"
tipo_valor = "texto"
[eeg.resultados.husos_sueno_n2]
etiqueta = "Husos de sueño N2"
tipo_valor = "numero"
unidad = "husos/min"
[eeg.resultados.husos_sueno_n2_z]
etiqueta = "Husos de sueño N2: puntaje z"
tipo_valor = "numero"
unidad = "z"
[eeg.resultados.husos_sueno_n2_fuera]
etiqueta = "Husos de sueño N2: fuera de la referencia (-1, 0, +1)"
tipo_valor = "numero"
[eeg.resultados.husos_sueno_n2_p5]
etiqueta = "Husos de sueño N2: percentil 5 de la referencia"
tipo_valor = "numero"
unidad = "husos/min"
[eeg.resultados.husos_sueno_n2_mediana]
etiqueta = "Husos de sueño N2: mediana de la referencia"
tipo_valor = "numero"
unidad = "husos/min"
[eeg.resultados.husos_sueno_n2_p95]
etiqueta = "Husos de sueño N2: percentil 95 de la referencia"
tipo_valor = "numero"
unidad = "husos/min"
[eeg.resultados.husos_sueno_n2_modelo]
etiqueta = "Husos de sueño N2: modelo de la referencia"
tipo_valor = "texto"
[eeg.resultados.husos_sueno_n3]
etiqueta = "Husos de sueño N3"
tipo_valor = "numero"
unidad = "husos/min"
[eeg.resultados.husos_sueno_n3_z]
etiqueta = "Husos de sueño N3: puntaje z"
tipo_valor = "numero"
unidad = "z"
[eeg.resultados.husos_sueno_n3_fuera]
etiqueta = "Husos de sueño N3: fuera de la referencia (-1, 0, +1)"
tipo_valor = "numero"
[eeg.resultados.husos_sueno_n3_p5]
etiqueta = "Husos de sueño N3: percentil 5 de la referencia"
tipo_valor = "numero"
unidad = "husos/min"
[eeg.resultados.husos_sueno_n3_mediana]
etiqueta = "Husos de sueño N3: mediana de la referencia"
tipo_valor = "numero"
unidad = "husos/min"
[eeg.resultados.husos_sueno_n3_p95]
etiqueta = "Husos de sueño N3: percentil 95 de la referencia"
tipo_valor = "numero"
unidad = "husos/min"
[eeg.resultados.husos_sueno_n3_modelo]
etiqueta = "Husos de sueño N3: modelo de la referencia"
tipo_valor = "texto"
[eeg.resultados.picos_paroxisticos]
etiqueta = "Picos paroxísticos"
tipo_valor = "numero"
unidad = "picos/min"
[eeg.resultados.picos_paroxisticos_z]
etiqueta = "Picos paroxísticos: puntaje z"
tipo_valor = "numero"
unidad = "z"
[eeg.resultados.picos_paroxisticos_fuera]
etiqueta = "Picos paroxísticos: fuera de la referencia (-1, 0, +1)"
tipo_valor = "numero"
[eeg.resultados.picos_paroxisticos_p5]
etiqueta = "Picos paroxísticos: percentil 5 de la referencia"
tipo_valor = "numero"
unidad = "picos/min"
[eeg.resultados.picos_paroxisticos_mediana]
etiqueta = "Picos paroxísticos: mediana de la referencia"
tipo_valor = "numero"
unidad = "picos/min"
[eeg.resultados.picos_paroxisticos_p95]
etiqueta = "Picos paroxísticos: percentil 95 de la referencia"
tipo_valor = "numero"
unidad = "picos/min"
[eeg.resultados.picos_paroxisticos_modelo]
etiqueta = "Picos paroxísticos: modelo de la referencia"
tipo_valor = "texto"
[eeg.resultados.gradiente_anteroposterior]
etiqueta = "Gradiente anteroposterior"
tipo_valor = "numero"
unidad = "pendiente"
[eeg.resultados.gradiente_anteroposterior_z]
etiqueta = "Gradiente anteroposterior: puntaje z"
tipo_valor = "numero"
unidad = "z"
[eeg.resultados.gradiente_anteroposterior_fuera]
etiqueta = "Gradiente anteroposterior: fuera de la referencia (-1, 0, +1)"
tipo_valor = "numero"
[eeg.resultados.gradiente_anteroposterior_p5]
etiqueta = "Gradiente anteroposterior: percentil 5 de la referencia"
tipo_valor = "numero"
unidad = "pendiente"
[eeg.resultados.gradiente_anteroposterior_mediana]
etiqueta = "Gradiente anteroposterior: mediana de la referencia"
tipo_valor = "numero"
unidad = "pendiente"
[eeg.resultados.gradiente_anteroposterior_p95]
etiqueta = "Gradiente anteroposterior: percentil 95 de la referencia"
tipo_valor = "numero"
unidad = "pendiente"
[eeg.resultados.gradiente_anteroposterior_modelo]
etiqueta = "Gradiente anteroposterior: modelo de la referencia"
tipo_valor = "texto"
# An order (procedure of class `orden`): its `estudio_id` is the study it asks for, from `codigos_hospital`.
[orden]
etiqueta = "Orden de estudio"
[orden.resultados.intencion]
etiqueta = "Intención (FHIR intent)"
tipo_valor = "texto"
+12
View File
@@ -0,0 +1,12 @@
"""Column types and sizes shared across domains, so the storage schema and
the import validation in WebApi use the same limits."""
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# Hospital patient identifiers are indexed in CaCu/CaMa, and MySQL can't
# index an unbounded TEXT column (error 1170), so they are a bounded VARCHAR.
HOSPITAL_ID_LENGTH = 64
# Stored files (PDF reports, DICOM, EDF). Plain LargeBinary is a 64 KB BLOB
# on MySQL/MariaDB; LONGBLOB holds up to 4 GB.
FileBlob = sa.LargeBinary().with_variant(mysql.LONGBLOB(), "mysql", "mariadb")
View File
+16
View File
@@ -0,0 +1,16 @@
import sqlalchemy.orm as orm
from sqlmodel import SQLModel
registry = orm.registry()
class GovernanceModel(SQLModel, registry=registry):
"""Base class for the governance domain: the OCR extraction log and stored
predictions (VAR, EL and MLD requirements). Model versions and artifacts
live in MLflow; cohorts for models are the indicator kit's builds
(`cohorte_armado`) in each domain's database.
Governance is its own database. Rows refer to CaCu/CaMa/TEA patients and
episodes by natural key (`pac_id_hospital`, `episodio_id`) because foreign
keys can't cross databases.
"""
+28
View File
@@ -0,0 +1,28 @@
from enum import Enum
class Environment(str, Enum):
"""ML-02: development versions are tagged separately from production."""
DEV = "DEV"
PROD = "PROD"
class ArtifactKind(str, Enum):
"""ML-01a: kinds of artifacts saved from the routines around training,
in addition to the final model."""
MUESTREO = "MUESTREO"
DATOS_FALTANTES = "DATOS_FALTANTES"
METODO_ANALITICO = "METODO_ANALITICO"
BALANCE_CLASES = "BALANCE_CLASES"
CONFIANZA_SALIDA = "CONFIANZA_SALIDA"
OTRO = "OTRO"
class EstatusExtraccion(str, Enum):
"""VAR-07/VAR-09: status of an extraction run."""
EN_PROGRESO = "EN_PROGRESO"
COMPLETADA = "COMPLETADA"
FALLIDA = "FALLIDA"
@@ -0,0 +1,70 @@
from datetime import datetime, timezone
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.governance.base import GovernanceModel
class ExtractionRun(GovernanceModel, table=True):
"""VAR-07/VAR-08/VAR-09: log of each extraction run (OCR or other).
Records the data source and date range (VAR-08), the transformation and
quality check applied (VAR-07), and serves as an idempotency log (VAR-09):
callers check for a `COMPLETADA` run on the same `(domain, entity,
entity_pk)` before extracting again. The extracted value itself lives in
the source row's `*_ocr_*` columns.
"""
extraction_run_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
domain: str = Field(
sa_column=sa.Column(sa.String(16), nullable=False, index=True),
description="cacu | cama | tea",
)
entity: str = Field(
sa_column=sa.Column(sa.String(64), nullable=False, index=True),
description="nombre de la tabla/entidad de Core sobre la que corrió la extracción",
)
entity_pk: str = Field(
sa_column=sa.Column(sa.String(64), nullable=False, index=True),
description="valor de la llave primaria de la fila extraída, como texto",
)
column_extracted: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="columna destino que esta corrida pobló (p.ej. cit_vph_resultado)",
)
source_description: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="VAR-08: fuente de los datos crudos",
)
source_started_at: Optional[datetime] = Field(
default=None,
sa_column=sa.Column(sa.DateTime),
description="VAR-08: inicio del periodo que cubren los datos crudos cargados",
)
source_ended_at: Optional[datetime] = Field(
default=None,
sa_column=sa.Column(sa.DateTime),
)
transform_description: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="VAR-07: descripción de la transformación de datos crudos aplicada",
)
quality_validation: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="VAR-07: resultado de la validación de calidad de los datos, texto libre o JSON serializado",
)
estatus: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="valor de core.governance.enums.EstatusExtraccion guardado como texto",
)
executed_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_column=sa.Column(sa.DateTime, nullable=False),
)
@@ -0,0 +1,83 @@
from datetime import datetime, timezone
from typing import Optional
import sqlalchemy as sa
from core.columns import HOSPITAL_ID_LENGTH
from sqlmodel import Field
from core.governance.base import GovernanceModel
class ModelPrediction(GovernanceModel, table=True):
"""MLD-4/MLD-5: a persisted prediction, linked to the MLflow model
version that produced it.
Model training, versioning and promotion live in MLflow, not here
(`models.io.registry`); this row only carries the keys to find that version
again (`mlflow_run_id`, `modelo_nombre`, `modelo_version`), the same
reference-only pattern `core.indicadores.cohortes.EvaluacionRiesgoLoteBase`
already uses for its own risk evaluations.
`interpretability` stores the MLD-03 fields (OR, HR, cumulative
probability) with the estimate. `applicability_passed` is False when the
input failed the EL-04b applicability check; the prediction is kept for
traceability but should not be used clinically.
"""
model_prediction_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
mlflow_run_id: str = Field(
sa_column=sa.Column(sa.String(64), nullable=False, index=True),
description="la corrida de MLflow que entrenó el modelo",
)
modelo_nombre: str = Field(
sa_column=sa.Column(sa.String(128), nullable=False, index=True),
description="nombre del modelo registrado en MLflow",
)
modelo_version: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="versión del modelo registrado en MLflow",
)
domain: str = Field(
sa_column=sa.Column(sa.String(16), nullable=False, index=True),
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
)
episodio_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
input_hash: str = Field(
sa_column=sa.Column(sa.String(128), nullable=False, index=True),
description="sha256 del vector de entrada, para detectar predicciones duplicadas",
)
output: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="JSON serializado: salida cruda del modelo",
)
prediccion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="etiqueta/puntaje principal, en texto, para filtrar sin deserializar `output`",
)
confianza: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
description="0..1, nivel de confianza casuístico de esta estimación (MLD-01)",
)
interpretability: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description='JSON serializado (MLD-03): {"odds_ratio":, "hazard_ratio":, "probabilidad_acumulada":}',
)
applicability_passed: bool = Field(
sa_column=sa.Column(sa.Boolean, nullable=False),
description="EL-04b: resultado de evaluar los criterios de aplicabilidad de producción contra esta fila",
)
created_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_column=sa.Column(sa.DateTime, nullable=False),
)
+7
View File
@@ -0,0 +1,7 @@
from core.governance.extraction_run.model import ExtractionRun
from core.governance.model_prediction.model import ModelPrediction
__all__ = [
"ExtractionRun",
"ModelPrediction",
]
View File
+141
View File
@@ -0,0 +1,141 @@
"""Los catálogos de la plata: estudio -> resultado -> valor (F1).
Son el diccionario de datos de cada proyecto: qué estudios hay, qué resultados
da cada uno y qué valores admite un resultado codificado. Se escriben en
`core/catalogos/<proyecto>.toml` y la arista `catalogos` los materializa en
estas tablas, antes de cargar. En F5 las observaciones apuntan a ellos con llave
foránea; hoy solo se materializan y se prueban contra los enums de Core y los
catálogos de `parametros.toml` del kit.
Un valor no se borra nunca: si sale del TOML, pasa a `retirado` (lo pueden
seguir usando hechos ya cargados).
How each source writes those codes lives apart, in the database: `cat_sistema_fuente` (who sends the data) and
`cat_mapeo` (FHIR's `ConceptMap`: a source's study code, a caption or a spelling, to our code). Those rows are edited
from the application, never by a deploy; the TOML only seeds the missing ones. A row is never deleted: a correction
closes it (`vigente_hasta`) and adds another.
"""
from datetime import date, datetime
from sqlalchemy import CheckConstraint, ForeignKeyConstraint, Index, UniqueConstraint
from sqlmodel import Field, SQLModel
from core.indicadores.tipos import FechaHoraUTC
# Cómo se guarda el valor de un resultado (en F5, la columna de `observacion` que lo lleva).
TIPOS_DE_VALOR = (
"codigo", # un `valor_id` de `cat_valor`
"booleano", # 0 o 1
"numero", # con `unidad` si la tiene
"fecha",
"texto", # texto libre, sin catálogo
"externo", # un código de otro sistema (`sistema`, p. ej. CIE-10), sin catálogo propio
)
ESTADOS_DE_VALOR = ("vigente", "retirado")
# What a source form maps to (`cat_mapeo.clase`).
CLASES_DE_MAPEO = (
"estudio", # a source's study or test code -> `estudio_id`
"etiqueta", # a caption a result is printed under -> `resultado_id`
"valor", # a spelling or code of a value -> `resultado_id` and `valor_id`
)
class CatEstudioBase(SQLModel):
"""Un estudio o acto clínico: citología, mastografía, EEG, una nota médica (FHIR `ActivityDefinition`)."""
estudio_id: str = Field(primary_key=True, max_length=64) # "citologia", "mastografia", "eeg"
etiqueta: str
class CatResultadoBase(SQLModel):
"""Un resultado que da un estudio (FHIR `ObservationDefinition`): qué se mide y cómo se guarda."""
resultado_id: str = Field(primary_key=True, max_length=128) # "<estudio>.<resultado>": "citologia.bethesda"
estudio_id: str = Field(foreign_key="cat_estudio.estudio_id", index=True, max_length=64)
etiqueta: str
tipo_valor: str # uno de TIPOS_DE_VALOR
unidad: str | None = None # "min", "s", "meses", "puntos"
sistema: str | None = None # el del código, si es externo: "CIE-10"
class CatValorBase(SQLModel):
"""Un valor admitido de un resultado codificado (FHIR `ValueSet`, una entrada)."""
resultado_id: str = Field(foreign_key="cat_resultado.resultado_id", primary_key=True, max_length=128)
valor_id: str = Field(primary_key=True, max_length=64) # "LIEAG", "B4A": tal como llega del hospital
etiqueta: str
orden: int # de presentación, de menos a más grave donde aplica
estado: str = "vigente" # vigente o retirado
def tipo_de_valor_conocido() -> CheckConstraint:
"""`cat_resultado.tipo_valor` es uno de `TIPOS_DE_VALOR`."""
return CheckConstraint(
"tipo_valor IN (" + ", ".join(f"'{t}'" for t in TIPOS_DE_VALOR) + ")", name="ck_cat_resultado_tipo_valor"
)
def estado_de_valor_conocido() -> CheckConstraint:
"""`cat_valor.estado` es uno de `ESTADOS_DE_VALOR`."""
return CheckConstraint(
"estado IN (" + ", ".join(f"'{e}'" for e in ESTADOS_DE_VALOR) + ")", name="ck_cat_valor_estado"
)
class CatSistemaFuenteBase(SQLModel):
"""Who sends the data: a lab, the record's header, a radiology system. A provider change is a new row."""
sistema_fuente_id: str = Field(primary_key=True, max_length=64)
etiqueta: str
fuente_tabla: str | None = Field(default=None, max_length=64) # its staging table; None: any
vigente_desde: date # first document date it applies to
vigente_hasta: date | None = None # last one; None while current
class CatMapeoBase(SQLModel):
"""How a source system writes one of our codes (FHIR `ConceptMap`, one element), while it's in force."""
mapeo_id: int | None = Field(default=None, primary_key=True)
sistema_fuente_id: str = Field(foreign_key="cat_sistema_fuente.sistema_fuente_id", max_length=64)
clase: str = Field(max_length=16) # one of CLASES_DE_MAPEO
forma: str = Field(max_length=255) # as the source writes it
forma_normalizada: str = Field(max_length=255) # uppercase, without accents, single spaces: what is compared
estudio_id: str | None = Field(default=None, foreign_key="cat_estudio.estudio_id", max_length=64)
resultado_id: str | None = Field(default=None, foreign_key="cat_resultado.resultado_id", max_length=128)
valor_id: str | None = Field(default=None, max_length=64)
vigente_desde: date
vigente_hasta: date | None = None
registrado_por: str = Field(max_length=64) # "catalogo" for a row seeded from the TOML
registrado_en: datetime = Field(sa_type=FechaHoraUTC)
motivo: str | None = None
def vigencia_ordenada(tabla: str) -> CheckConstraint:
"""`vigente_hasta`, if any, isn't before `vigente_desde`."""
return CheckConstraint("vigente_hasta IS NULL OR vigente_hasta >= vigente_desde", name=f"ck_{tabla}_vigencia")
def reglas_de_mapeo() -> tuple:
"""`cat_mapeo`'s constraints: a known class with the target it needs, a value that exists, one row per form and
start date. Overlapping validities with different targets are checked by whoever writes and by dbt's tests:
no portable constraint expresses them."""
clases = ", ".join(f"'{c}'" for c in CLASES_DE_MAPEO)
return (
CheckConstraint(f"clase IN ({clases})", name="ck_cat_mapeo_clase"),
CheckConstraint(
"(clase = 'estudio' AND estudio_id IS NOT NULL AND resultado_id IS NULL AND valor_id IS NULL)"
" OR (clase = 'etiqueta' AND estudio_id IS NULL AND resultado_id IS NOT NULL AND valor_id IS NULL)"
" OR (clase = 'valor' AND estudio_id IS NULL AND resultado_id IS NOT NULL AND valor_id IS NOT NULL)",
name="ck_cat_mapeo_destino",
),
vigencia_ordenada("cat_mapeo"),
ForeignKeyConstraint(
["resultado_id", "valor_id"], ["cat_valor.resultado_id", "cat_valor.valor_id"], name="fk_cat_mapeo_valor"
),
UniqueConstraint(
"sistema_fuente_id", "clase", "resultado_id", "estudio_id", "forma_normalizada", "vigente_desde",
name="uq_cat_mapeo",
),
Index("ix_cat_mapeo_busqueda", "sistema_fuente_id", "resultado_id", "forma_normalizada"),
)
+148
View File
@@ -0,0 +1,148 @@
"""Las columnas de las cohortes para modelos y de sus estimaciones de riesgo, sin tabla.
Oro restringido: identifican pacientes y no salen de la máquina segura. Adoptan
el diseño del kit de campo (`indicadores_kit_0/campo/cohortes/tablas.py` y
`campo/riesgos/columnas.py`) con tres cambios (ADR-MD-003):
- un armado tiene su llave (`armado_id`) y guarda su `marco_sha` (I-K90 de campo);
- las variables de cada miembro van en formato largo (`cohorte_variable`), sin nulos:
sin dato es sin fila. La vista ancha para el modelo se arma desde aquí;
- el lote apunta al armado puntuado por su llave, no por cuatro columnas.
MLflow y estas tablas no comparten filas: se guardan llaves del otro lado
(`mlflow_run_id`, `modelo_sha`; y en MLflow, `kit.marco_sha` y `kit.armado_id`).
cohorte_armado un armado de una definición (FHIR Group enumerado / OMOP COHORT)
cohorte_miembro quién entró: paciente, fecha índice y la fila de su hecho índice
cohorte_exclusion la atrición, un paso por fila (contrato C5)
cohorte_variable el desenlace y los predictores de cada miembro (EvidenceVariable)
evaluacion_riesgo_lote una puntuación: qué modelo, sobre qué armado, cuándo
evaluacion_riesgo el riesgo de una paciente a un horizonte (FHIR RiskAssessment)
"""
from dataclasses import dataclass
from datetime import date, datetime
from sqlalchemy import CheckConstraint, Text, UniqueConstraint
from sqlmodel import Field, SQLModel
from core.indicadores.tipos import FechaHoraUTC
# FHIR `RiskAssessment.status`: los que se usan. Una evaluación solo crece: cambiar de estado es otra versión.
ESTADOS_RIESGO = ("preliminary", "final", "entered-in-error")
class CohorteArmadoBase(SQLModel):
"""Un armado de una cohorte: qué definición, con qué parámetros y datos, y su huella."""
armado_id: int | None = Field(default=None, primary_key=True)
url: str # la definición: "cacu/cohorte_vigilancia"
version: str
definicion_sha: str # sha256 del TOML de la definición
reglas_sha: str # sha256 de sus reglas clínicas, en JSON canónico
parametros: str = Field(sa_type=Text) # JSON: ventana de reclutamiento y corte
datos_as_of: date # el corte: hasta qué día llegan los datos
huella: str = Field(max_length=128) # definición + reglas + parámetros: dos armados con la misma huella son el mismo pedido
marco_sha: str = Field(max_length=128) # el contenido del marco; con la huella, rearmar lo mismo no guarda otro
n_miembros: int
armado_en: datetime = Field(sa_type=FechaHoraUTC)
class CohorteMiembroBase(SQLModel):
"""Quién entró a un armado y desde cuándo cuenta su seguimiento."""
armado_id: int = Field(foreign_key="cohorte_armado.armado_id", primary_key=True)
pac_id: int = Field(foreign_key="persona.pac_id", primary_key=True)
fecha_indice: date
# El hecho índice (la citología en CaCu): su fila de staging, como en la línea de tiempo.
indice_fuente_tabla: str
indice_fuente_id: str
class CohorteExclusionBase(SQLModel):
"""La atrición de un armado: cuántas quedan después de cada paso (contrato C5)."""
armado_id: int = Field(foreign_key="cohorte_armado.armado_id", primary_key=True)
orden: int = Field(primary_key=True)
paso: str # "candidatas", "sin evento_previo"...
n: int
class CohorteVariableBase(SQLModel):
"""Una variable de un miembro: el desenlace (`c`, `l`, `r`) o un predictor. Sin dato es sin fila."""
armado_id: int = Field(foreign_key="cohorte_armado.armado_id", primary_key=True)
pac_id: int = Field(foreign_key="persona.pac_id", primary_key=True)
variable: str = Field(primary_key=True, max_length=128)
valor_codigo: str | None = None # una categoría
valor_numerico: float | None = None # un número
class EvaluacionRiesgoLoteBase(SQLModel):
"""Una puntuación. No copia nada de MLflow: solo las llaves que llevan a la corrida y a su artefacto."""
lote_id: int | None = Field(default=None, primary_key=True)
armado_id: int = Field(foreign_key="cohorte_armado.armado_id") # basis: la cohorte puntuada
modelo_nombre: str # el modelo registrado en MLflow
modelo_version: str
mlflow_run_id: str # method: la corrida que entrenó el modelo
modelo_sha: str # guarda: sha256 del artefacto; el run_id no fija su contenido
desenlace: str # prediction.outcome: la variable de desenlace de la cohorte
evaluado_en: datetime = Field(sa_type=FechaHoraUTC) # occurrence
n_evaluaciones: int
huella: str = Field(unique=True, max_length=128) # del contenido del lote: puntuar lo mismo no duplica
class EvaluacionRiesgoBase(SQLModel):
"""El riesgo de una paciente a un horizonte. Solo crece: cambiar de estado es una versión nueva."""
evaluacion_id: int | None = Field(default=None, primary_key=True)
lote_id: int = Field(foreign_key="evaluacion_riesgo_lote.lote_id", index=True)
pac_id: int = Field(foreign_key="persona.pac_id") # subject
# El punto de decisión desde el que el modelo predice para esta paciente (lo define el modelo, no la cohorte).
fecha_indice: date
horizonte_anios: float # prediction.when: años desde `fecha_indice`; 0 = prevalente
probabilidad: float # prediction.probabilityDecimal, de 0 a 1
# Incertidumbre, si el modelo la da (solo con un Hessiano definido positivo). Nula si no.
ic_bajo: float | None = None
ic_alto: float | None = None
version: int # 1, 2... por (lote, paciente, horizonte)
estado: str # preliminary, final o entered-in-error
motivo: str | None = None # por qué cambió de estado; nulo en la versión 1
registrado_en: datetime = Field(sa_type=FechaHoraUTC)
def armado_unico() -> UniqueConstraint:
"""Rearmar lo mismo (misma huella y mismo contenido) no agrega otro armado."""
return UniqueConstraint("huella", "marco_sha")
def variable_con_un_valor() -> CheckConstraint:
"""Cada fila de `cohorte_variable` trae exactamente un valor. Sin comparar
booleanos (`IS NULL <> IS NULL`): SQL Server no los admite."""
return CheckConstraint("(valor_codigo IS NULL AND valor_numerico IS NOT NULL) OR (valor_codigo IS NOT NULL AND valor_numerico IS NULL)", name="ck_cohorte_variable_un_valor")
def evaluacion_unica() -> UniqueConstraint:
"""Una sola fila por versión de cada evaluación."""
return UniqueConstraint("lote_id", "pac_id", "horizonte_anios", "version")
@dataclass(frozen=True)
class TablasCohorte:
"""Las seis tablas de cohortes y riesgos de un dominio, juntas (como `TablasKit` del kit).
Las declara cada proyecto (`webapi.orchestration.tables.<proyecto>.COHORTES`); el ciclo las lee
y Persistance las escribe.
"""
CohorteArmado: type[SQLModel]
CohorteMiembro: type[SQLModel]
CohorteExclusion: type[SQLModel]
CohorteVariable: type[SQLModel]
EvaluacionRiesgoLote: type[SQLModel]
EvaluacionRiesgo: type[SQLModel]
def todas(self) -> list[type[SQLModel]]:
return [self.CohorteArmado, self.CohorteMiembro, self.CohorteExclusion, self.CohorteVariable,
self.EvaluacionRiesgoLote, self.EvaluacionRiesgo]
+60
View File
@@ -0,0 +1,60 @@
"""Las columnas de las tablas comunes de indicadores_kit, sin tabla.
`persona` y `periodo_observacion` (OMOP `PERSON`, `OBSERVATION_PERIOD`) y
`carga` (FHIR `Provenance`, una fila por lote). Cada dominio las
instancia en su registro: `core/<dominio>/indicadores/models.py`.
"""
from datetime import date, datetime
from sqlalchemy import Text
from sqlmodel import Field, SQLModel
from core.indicadores.tipos import FechaHoraUTC
class PersonaBase(SQLModel):
"""Las columnas de `persona`, sin tabla: cada dominio la instancia."""
# Viene del staging: nunca lo genera la base.
pac_id: int = Field(primary_key=True, sa_column_kwargs={"autoincrement": False})
pac_id_hospital: str = Field(unique=True, max_length=64) # identificador original del hospital
fecha_nacimiento: date | None = None # para calcular la edad a una fecha
class PersonaDerechohabienteBase(PersonaBase):
"""`persona` con lo que el hospital sabe de la derechohabiente (CaCu y CaMa).
Es el valor vigente en staging, no el de la fecha de cada estudio. El
texto entra como viene, sin espacios alrededor; vacío es nulo.
"""
dependencia: str | None = None # dependencia de adscripción (`pac_dependencia`)
parentesco: str | None = None # afiliada o familiar de un afiliado (`pac_parentesco`)
codigo_postal: str | None = None # de su domicilio; no se publica, sirve para la zona
class PeriodoObservacionBase(SQLModel):
"""Periodo en que una paciente es observable; puede tener varios."""
periodo_observacion_id: int | None = Field(default=None, primary_key=True)
pac_id: int = Field(foreign_key="persona.pac_id") # de quién es el periodo
fecha_inicio: date # primer día en que hay datos de la paciente
fecha_fin: date # último día en que los hay
tipo_periodo: str # de dónde sale el periodo, por ejemplo "extraccion"
class CargaBase(SQLModel):
"""Las columnas de `carga`, sin tabla: cada dominio la instancia."""
carga_id: int | None = Field(default=None, primary_key=True)
fuente: str # tabla de staging que se cargó
inicio: datetime = Field(sa_type=FechaHoraUTC) # cuándo empezó la carga
fin: datetime | None = Field(default=None, sa_type=FechaHoraUTC) # nulo: no terminó
filas_nuevas: int = 0 # filas fuente que no existían
filas_cambiadas: int = 0 # filas fuente que dieron una versión nueva
filas_sin_cambio: int = 0 # filas fuente con el mismo contenido
codigo_sha: str | None = None # versión del código que hizo la carga
# Lo que la carga dejó fuera a propósito, por motivo, en JSON (`{"eeg sin paciente": 3}`): los descartes del
# staging directo y los huérfanos de la plata (T-20c). Nulo si no descartó nada.
descartes: str | None = Field(default=None, sa_type=Text)
+88
View File
@@ -0,0 +1,88 @@
"""Portable day-arithmetic SQL helpers for the indicator layer.
dias_entre(inicio, fin) means fin - inicio; an engine with no @compiles
rule gets the non-executable neutral default instead of silently running
invalid SQL, so a missing dialect rule fails loudly."""
from sqlalchemy import Float, Integer, cast, func
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import FunctionElement
class dias_entre(FunctionElement):
"""Whole days from `inicio` to `fin` (`fin - inicio`)."""
type = Integer()
inherit_cache = True
def _clauses(elemento, compilador, opciones):
inicio, fin = list(elemento.clauses)
return compilador.process(inicio, **opciones), compilador.process(fin, **opciones)
@compiles(dias_entre)
def _dias_entre_neutral(elemento, compilador, **opciones):
# No rule registered for this dialect: emit a non-executable
# placeholder instead of guessing at syntax, so an unsupported engine
# fails loudly rather than running the wrong SQL silently.
inicio, fin = _clauses(elemento, compilador, opciones)
return f"dias_entre({inicio}, {fin})"
@compiles(dias_entre, "sqlite")
def _dias_entre_sqlite(elemento, compilador, **opciones):
inicio, fin = _clauses(elemento, compilador, opciones)
return f"CAST(julianday({fin}) - julianday({inicio}) AS INTEGER)"
@compiles(dias_entre, "postgresql")
def _dias_entre_postgresql(elemento, compilador, **opciones):
inicio, fin = _clauses(elemento, compilador, opciones)
return f"(CAST({fin} AS DATE) - CAST({inicio} AS DATE))"
@compiles(dias_entre, "mysql", "mariadb")
def _dias_entre_mysql(elemento, compilador, **opciones):
# MySQL's DATEDIFF(a, b) is a - b with no "day" keyword, unlike
# SQL Server's DATEDIFF(day, start, end).
inicio, fin = _clauses(elemento, compilador, opciones)
return f"DATEDIFF({fin}, {inicio})"
@compiles(dias_entre, "mssql")
def _dias_entre_mssql(elemento, compilador, **opciones):
inicio, fin = _clauses(elemento, compilador, opciones)
return f"DATEDIFF(day, {inicio}, {fin})"
class redondear(FunctionElement):
"""`ROUND(x, decimales)`; PostgreSQL only rounds NUMERIC, so it casts."""
type = Float()
inherit_cache = True
@compiles(redondear)
def _redondear(elemento, compilador, **opciones):
x, decimales = list(elemento.clauses)
return f"ROUND({compilador.process(x, **opciones)}, {compilador.process(decimales, **opciones)})"
@compiles(redondear, "postgresql")
def _redondear_postgresql(elemento, compilador, **opciones):
x, decimales = list(elemento.clauses)
return (
f"CAST(ROUND(CAST({compilador.process(x, **opciones)} AS NUMERIC), "
f"{compilador.process(decimales, **opciones)}) AS DOUBLE PRECISION)"
)
def edad_meses(nacimiento, fecha, dias_por_mes: float):
"""Age in months, to one decimal, as of `fecha`."""
return redondear(cast(dias_entre(nacimiento, fecha), Float) / dias_por_mes, 1)
def meses_cumplidos(edad):
"""Completed months: truncates an already-rounded age in months."""
return func.floor(edad)
+97
View File
@@ -0,0 +1,97 @@
"""La plata de dos tablas (F5): `procedimiento` y `observacion` (ADR-MD-007).
Cada acto clínico con fecha es un `procedimiento`: la orden, el encuentro (una
nota, una evaluación, un parto), la toma (una citología, un EEG), el reporte de
una toma y una parte de un estudio (un segmento de EEG). `clase` dice cuál y
`estudio_id` de qué estudio del catálogo. `padre_id` liga el reporte con su toma,
la toma con su orden o con su encuentro, y la parte con su estudio.
Cada valor de un procedimiento es una `observacion`: un `resultado_id` del
catálogo y un solo valor (`valor_id` de `cat_valor`, número, fecha o texto). Un
diagnóstico es la observación `<estudio>.diagnostico` de un encuentro (decisión
del usuario, 2026-10-19). Los datos de una orden son resultados del estudio
`orden`.
Sin versiones de fila (decisión del usuario, 2026-10-20: queda para una versión
futura). Las dos tablas guardan el estado actual: recargar una fila de staging
actualiza en su lugar lo que cambió, por su llave lógica
`(fuente_tabla, fuente_id, estudio_id, clase)` en `procedimiento` y
`(procedimiento_id, resultado_id)` en `observacion`. Por eso `procedimiento_id`
es la llave primaria y `padre_id` y `observacion.procedimiento_id` son llaves
foráneas reales. `carga_id` dice qué carga escribió o cambió la fila por última
vez. Las tablas por tipo siguen versionando mientras existan.
"""
from datetime import date
from sqlalchemy import CheckConstraint, ForeignKeyConstraint, Index, Text, UniqueConstraint
from sqlmodel import Field, SQLModel
CLASES = ("orden", "encuentro", "toma", "reporte", "parte")
class ProcedimientoClinicoBase(SQLModel):
"""Un acto clínico con fecha. FHIR `ServiceRequest`, `Encounter`, `Procedure` o `DiagnosticReport`, según `clase`."""
procedimiento_id: int | None = Field(default=None, primary_key=True)
fuente_tabla: str = Field(max_length=64) # tabla de staging de donde vino
fuente_id: str = Field(max_length=64) # llave de la fila en esa tabla
carga_id: int = Field(foreign_key="carga.carga_id") # la última carga que lo escribió o lo cambió
pac_id: int = Field(foreign_key="persona.pac_id")
estudio_id: str = Field(foreign_key="cat_estudio.estudio_id", max_length=64)
clase: str = Field(max_length=16) # uno de CLASES
fecha: date | None = None # la del acto: la orden, el encuentro, la toma, el reporte
padre_id: int | None = Field(default=None, foreign_key="procedimiento.procedimiento_id") # la toma de un reporte, la orden de una toma
numero_hospital: int | None = None # el número de la orden (clase `orden`)
orden_numero: int | None = None # el número de orden que trae una toma, tal como llega
codigo_fuente: str | None = None # el código del acto tal como llega
id_hospital: str | None = None # el identificador del acto en el hospital, si es texto (la nota: `nm_id_hospital`); provisional (usuario, 2026-10-22)
class ObservacionClinicaBase(SQLModel):
"""Un valor de un procedimiento. FHIR `Observation` / OMOP `MEASUREMENT`, `OBSERVATION`, `CONDITION_OCCURRENCE`."""
observacion_id: int | None = Field(default=None, primary_key=True)
procedimiento_id: int = Field(foreign_key="procedimiento.procedimiento_id", index=True)
carga_id: int = Field(foreign_key="carga.carga_id") # la última carga que la escribió o la cambió
pac_id: int = Field(foreign_key="persona.pac_id")
resultado_id: str = Field(max_length=128) # de `cat_resultado`; la llave foránea va en `__table_args__` (compuesta con `valor_id`)
valor_id: str | None = Field(default=None, max_length=64) # de `cat_valor`, si el resultado es `codigo` y el valor está en el catálogo
valor_numerico: float | None = None # `numero` y `booleano` (0 o 1)
valor_fecha: date | None = None # `fecha`
valor_texto: str | None = Field(default=None, sa_type=Text) # `texto` y `externo` (el código, p. ej. CIE-10 normalizado)
valor_fuente: str | None = Field(default=None, sa_type=Text) # el valor tal como llegó, si es codigo (también fuera de catálogo)
def clase_conocida() -> CheckConstraint:
return CheckConstraint("clase IN (" + ", ".join(f"'{c}'" for c in CLASES) + ")", name="ck_procedimiento_clase")
def llave_de_procedimiento() -> UniqueConstraint:
"""Un procedimiento por fila de staging, estudio y clase: la llave con que se recarga."""
return UniqueConstraint("fuente_tabla", "fuente_id", "estudio_id", "clase", name="uq_procedimiento_llave")
def indice_de_procedimiento() -> Index:
"""Para buscar por paciente, estudio y clase en orden de fecha (casi todas las consultas)."""
return Index("ix_procedimiento_paciente", "pac_id", "estudio_id", "clase", "fecha")
def llave_de_observacion() -> UniqueConstraint:
"""Un valor por resultado en cada procedimiento."""
return UniqueConstraint("procedimiento_id", "resultado_id", name="uq_observacion_llave")
def observacion_en_catalogo() -> tuple:
"""Llaves foráneas de la observación al catálogo: el resultado, y el par (resultado, valor) si hay valor."""
return (
ForeignKeyConstraint(["resultado_id"], ["cat_resultado.resultado_id"], name="fk_observacion_resultado"),
ForeignKeyConstraint(
["resultado_id", "valor_id"], ["cat_valor.resultado_id", "cat_valor.valor_id"], name="fk_observacion_valor"
),
)
def indice_de_observacion() -> Index:
return Index("ix_observacion_resultado", "resultado_id", "valor_id")
+159
View File
@@ -0,0 +1,159 @@
"""El oro por unidad y su catálogo (§6f, MD-19): de qué se publica un indicador y con qué unidades.
El kit no agrega: escribe cada unidad en cada población de un reporte y el
estrato de cada unidad, decidido al calcular. El número publicado es una
vista (`v_c1`, `v_c2`, `v_c3r`) sobre estas tablas.
cat_measure, cat_measure_resultado el indicador, su contrato y sus poblaciones
cat_measure_valor las categorías de un C2, en orden
cat_measure_grupo los grupos de un indicador (`TOTAL`, las ventanas de TEA)
cat_estrato, cat_estrato_valor las dimensiones y sus valores
cat_measure_estrato qué estrato admite cada indicador como desglose o filtro
measure_report_unidad cada unidad en cada población de un reporte
measure_report_unidad_estrato el valor de cada estrato de cada unidad
Los catálogos se generan de los TOML del kit (el analista no los escribe) y
se reemplazan enteros. Las unidades identifican pacientes: no salen de la
máquina segura.
"""
from sqlalchemy import CheckConstraint, ForeignKeyConstraint, UniqueConstraint
from sqlmodel import Field, SQLModel
CONTRATOS = ("C1", "C2", "C3r")
UNIDADES = ("paciente", "examen", "episodio")
POBLACIONES = (
"initial-population", "denominator", "numerator", "denominator-exclusion", "numerator-exclusion", "measure-observation",
)
ORIGENES_DE_VALOR = ("catalogo", "fuera_de_catalogo")
class CatMeasureBase(SQLModel):
"""Un indicador como se publica: su contrato y su unidad. Sale del TOML del measure."""
measure_id: str = Field(primary_key=True, max_length=64) # "CACU_EU8": el final de su `url`
url: str = Field(unique=True, max_length=255)
version: str
titulo: str
contrato: str # uno de CONTRATOS
unidad: str # uno de UNIDADES
decide: str | None = None # qué procedimiento representa a la unidad (MD-Q8); nulo hasta decidirlo
class CatMeasureResultadoBase(SQLModel):
"""Una población de un indicador: `<measure_id>.<poblacion>`."""
resultado_id: str = Field(primary_key=True, max_length=128) # "CACU_EU8.numerator"
measure_id: str = Field(foreign_key="cat_measure.measure_id", index=True, max_length=64)
poblacion: str = Field(max_length=32) # una de POBLACIONES
etiqueta: str
class CatMeasureValorBase(SQLModel):
"""Una categoría de un C2, en el orden en que se presenta."""
measure_id: str = Field(foreign_key="cat_measure.measure_id", primary_key=True, max_length=64)
valor_id: str = Field(primary_key=True, max_length=64) # "LIEAG", "SIN_DATO"
etiqueta: str
orden: int
origen: str = "catalogo" # uno de ORIGENES_DE_VALOR
class CatMeasureGrupoBase(SQLModel):
"""Un grupo de un indicador, en orden: tiene filas publicadas aunque ninguna unidad caiga en él.
Sin ficha, el único grupo es el `linkId` del TOML; con ficha, los de la ficha (T-19c).
"""
measure_id: str = Field(foreign_key="cat_measure.measure_id", primary_key=True, max_length=64)
grupo: str = Field(primary_key=True, max_length=64) # "TOTAL", "V1_16_23"
etiqueta: str
orden: int
class CatEstratoBase(SQLModel):
"""Una dimensión por la que se desglosa o se filtra: `grupo_edad`, `ronda`."""
estrato_id: str = Field(primary_key=True, max_length=64)
etiqueta: str
unidad: str # uno de UNIDADES: a qué unidad se le asigna
class CatEstratoValorBase(SQLModel):
"""Un valor de un estrato, con `sin_dato` al final."""
estrato_id: str = Field(foreign_key="cat_estrato.estrato_id", primary_key=True, max_length=64)
valor_id: str = Field(primary_key=True, max_length=64)
etiqueta: str
orden: int
class CatMeasureEstratoBase(SQLModel):
"""Qué estrato admite un indicador: como desglose publicado o como filtro."""
measure_id: str = Field(foreign_key="cat_measure.measure_id", primary_key=True, max_length=64)
estrato_id: str = Field(foreign_key="cat_estrato.estrato_id", primary_key=True, max_length=64)
desglose: int = 1 # se publica desglosado por él
filtro: int = 0 # se puede filtrar por uno de sus valores
class MeasureReportUnidadBase(SQLModel):
"""Una unidad en una población de un reporte, con su categoría (C2) o su número (C3r)."""
report_id: int = Field(foreign_key="measure_report.report_id", primary_key=True)
grupo: str = Field(primary_key=True, max_length=64) # "principal"; en TEA, cada ventana
unidad_id: str = Field(primary_key=True, max_length=64) # el pac_id o la llave del examen, según la unidad
resultado_id: str = Field(foreign_key="cat_measure_resultado.resultado_id", primary_key=True, max_length=128)
pac_id: int | None = None
# El procedimiento que decide (MD-Q8): nulo hasta que la familia lo devuelva.
procedimiento_id: int | None = Field(default=None, foreign_key="procedimiento.procedimiento_id")
valor_id: str | None = Field(default=None, max_length=64) # la categoría, en C2
numero: float | None = None # la medición, en C3r
class MeasureReportUnidadEstratoBase(SQLModel):
"""El valor de un estrato de una unidad de un reporte; `sin_dato` si no tiene."""
report_id: int = Field(foreign_key="measure_report.report_id", primary_key=True)
unidad_id: str = Field(primary_key=True, max_length=64)
estrato_id: str = Field(primary_key=True, max_length=64)
estrato_valor: str = Field(max_length=64)
def _uno_de(tabla: str, columna: str, valores: tuple[str, ...]) -> CheckConstraint:
return CheckConstraint(
f"{columna} IN (" + ", ".join(f"'{v}'" for v in valores) + ")", name=f"ck_{tabla}_{columna}"
)
def contrato_y_unidad_conocidos() -> tuple[CheckConstraint, CheckConstraint]:
"""`cat_measure.contrato` es uno de `CONTRATOS` y `unidad`, uno de `UNIDADES`."""
return _uno_de("cat_measure", "contrato", CONTRATOS), _uno_de("cat_measure", "unidad", UNIDADES)
def poblacion_conocida() -> CheckConstraint:
"""`cat_measure_resultado.poblacion` es una de `POBLACIONES`."""
return _uno_de("cat_measure_resultado", "poblacion", POBLACIONES)
def una_poblacion_por_indicador() -> UniqueConstraint:
"""Un indicador tiene cada población una sola vez."""
return UniqueConstraint("measure_id", "poblacion", name="uq_cat_measure_resultado_poblacion")
def origen_conocido() -> CheckConstraint:
"""`cat_measure_valor.origen` es uno de `ORIGENES_DE_VALOR`."""
return _uno_de("cat_measure_valor", "origen", ORIGENES_DE_VALOR)
def unidad_de_estrato_conocida() -> CheckConstraint:
"""`cat_estrato.unidad` es una de `UNIDADES`."""
return _uno_de("cat_estrato", "unidad", UNIDADES)
def valor_de_estrato_en_catalogo() -> ForeignKeyConstraint:
"""`(estrato_id, estrato_valor)` es un valor de `cat_estrato_valor`."""
return ForeignKeyConstraint(
["estrato_id", "estrato_valor"], ["cat_estrato_valor.estrato_id", "cat_estrato_valor.valor_id"],
name="fk_measure_report_unidad_estrato_valor",
)
+66
View File
@@ -0,0 +1,66 @@
"""Las columnas del registro de indicadores_kit, sin tabla.
`def_parametro` (parámetros cargados de un TOML), `dim_periodo` (los
periodos de cálculo, cada uno `[inicio, fin)`), `dim_fecha` (un día por
fila, para la aritmética de fechas sin funciones del motor) y
`dim_grupo_edad` (los grupos de edad como datos). Se reconstruyen o se
completan desde el kit; nadie las edita a mano.
"""
from datetime import date
from sqlalchemy import Text
from sqlmodel import Field, SQLModel
class DefParametroBase(SQLModel):
"""Las columnas de `def_parametro`, sin tabla: cada dominio la instancia.
`valor` y `fuente` son `Text`, no un `str` corto: `valor` puede ser un
JSON largo (una lista de grupos de edad, un catálogo con colores) y
`fuente` es la explicación en prosa de por qué se eligió ese valor —
ambos superan los 255 caracteres de la `VARCHAR` por omisión en
bastantes filas reales de `parametros.toml` (confirmado contra MySQL:
sin esto, `INSERT` falla con "Data too long for column 'valor'").
"""
clave: str = Field(primary_key=True, max_length=128) # "seccion.nombre"
valor: str = Field(sa_type=Text) # JSON: un escalar o una lista
estado: str
fuente: str = Field(sa_type=Text)
toml_sha: str
class DimPeriodoBase(SQLModel):
"""Las columnas de `dim_periodo`, sin tabla: cada dominio la instancia."""
periodo_id: str = Field(primary_key=True, max_length=32) # "2024-S1"
tipo: str
inicio: date
fin: date # exclusivo
anio: int
semestre: int
class DimFechaBase(SQLModel):
"""Las columnas de `dim_fecha`, sin tabla: cada dominio la instancia.
Sumar días o medir un intervalo es una resta de `dia_num` con un
cruce; la edad cumplida sale de `anio`, `mes` y `dia`. Los días
hábiles son de lunes a viernes, sin festivos.
"""
fecha: date = Field(primary_key=True)
dia_num: int # días desde el inicio de la tabla
dia_habil_num: int # días hábiles transcurridos hasta esa fecha, incluida
anio: int
mes: int
dia: int # día del mes
class DimGrupoEdadBase(SQLModel):
"""Las columnas de `dim_grupo_edad`, sin tabla: cada dominio la instancia."""
etiqueta: str = Field(primary_key=True, max_length=32) # "25-34"
edad_min: int # años cumplidos, incluido
edad_max: int # años cumplidos, incluido
+47
View File
@@ -0,0 +1,47 @@
"""Las columnas de los resultados de indicadores_kit, sin tabla.
Forma de FHIR `MeasureReport`, formato largo (ADR-001). Solo reportes de
tipo `summary`: son los únicos que pueden salir de la máquina segura.
Las filas de un reporte son sus unidades (`core.indicadores.publicacion`, §6f);
el número publicado lo dan las vistas del kit (MD-19).
"""
from datetime import date, datetime
from sqlalchemy import Text
from sqlmodel import Field, SQLModel
from core.indicadores.tipos import FechaHoraUTC
class MeasureReportBase(SQLModel):
"""Las columnas de `measure_report`, sin tabla: cada dominio la instancia."""
report_id: int | None = Field(default=None, primary_key=True)
measure_url: str
measure_version: str
# Con la `url` y la `version` del Measure, identifica con qué se calculó
# (D-S2, v0.5.0); reemplaza a `sql_sha`. Nula en reportes anteriores.
kit_version: str | None = None
toml_sha: str # versión del archivo de parámetros con que se calculó
# Huella de los valores en uso: los que recibió el SQL y el umbral de
# supresión. Nula en los reportes de antes de v0.4.0 (I-K58).
parametros_sha: str | None = None
# Los valores en uso, en JSON: los que recibió la consulta y el umbral de
# supresión. Es el texto del que sale `parametros_sha`. Nula en los
# reportes anteriores.
parametros: str | None = Field(default=None, sa_type=Text)
# Hasta qué día llegan los datos con que se calculó (I-K2, D-T6). Nula en
# los reportes anteriores y en los de definiciones que no la usan.
fecha_corte: date | None = None
periodo_id: str = Field(foreign_key="dim_periodo.periodo_id", max_length=32)
periodo_inicio: date
periodo_fin: date
status: str
tipo: str
generado_en: datetime = Field(sa_type=FechaHoraUTC)
# §6f (MD-19): la revisión de las vistas con que se publica y la huella de sus unidades y
# estratos. Las filas del reporte son sus unidades (`measure_report_unidad`); desde T-19e no hay
# `measure_report_valor`, y la migración borró los reportes sin huella.
agregacion_version: str | None = None
huella: str | None = None
+30
View File
@@ -0,0 +1,30 @@
"""Tipos de columna propios de las tablas de indicadores_kit."""
from datetime import datetime, timezone
from sqlalchemy import Text
from sqlalchemy.types import TypeDecorator
def a_texto_utc(momento: datetime) -> str:
"""Texto ISO 8601 en UTC, de ancho fijo: se ordena igual que el tiempo."""
if momento.tzinfo is None:
raise ValueError("Se esperaba una fecha y hora con zona horaria.")
return momento.astimezone(timezone.utc).isoformat(timespec="microseconds")
class FechaHoraUTC(TypeDecorator):
"""Tiempo del sistema: se guarda como texto en UTC y se lee con zona.
SQLite no tiene tipo de fecha y hora, y el `DateTime` de SQLAlchemy
pierde la zona al leer. Rechaza valores sin zona horaria.
"""
impl = Text
cache_ok = True
def process_bind_param(self, value, dialect):
return None if value is None else a_texto_utc(value)
def process_result_value(self, value, dialect):
return None if value is None else datetime.fromisoformat(value)
+20
View File
@@ -0,0 +1,20 @@
"""OCR traceability vocabulary shared by CaCu and CaMa (VAR-03/VARM-04a).
Every OCR-derived value records its status, whether it needs manual review,
and which method produced it. The same columns appear on CaCu's
`citologia_cervical`/`biopsia_cervical` and CaMa's `biopsia_mama`, so the
enum lives here instead of in each domain."""
from enum import Enum
class OcrEstatus(str, Enum):
PENDIENTE = "PENDIENTE"
REALIZADO = "REALIZADO"
FALLIDO = "FALLIDO"
OCR_ESTATUS_ALIAS: dict[str, str] = {
"OK": "REALIZADO",
"EXITOSO": "REALIZADO",
"ERROR": "FALLIDO",
}
+4 -3
View File
@@ -5,7 +5,8 @@ registry = orm.registry()
class TeaModel(SQLModel, registry=registry):
"""Base class for every TEA table. Own SQLAlchemy registry/metadata,
same as CaCu/CaMa, so each domain's Alembic environment can target its
own metadata independently.
"""Base class for every TEA table.
Uses its own SQLAlchemy registry, like CaCu and CaMa, so each domain's
Alembic environment targets its own metadata.
"""
+57 -267
View File
@@ -1,299 +1,89 @@
# -*- coding: utf-8 -*-
"""Vocabularios controlados del proyecto TEA.
"""Controlled vocabularies of TEA's staging (spec/tablas_TEA.md).
Capa Core: sin importaciones de infraestructura. Seguro de importar
desde cualquier módulo de src/.
Generado desde spec/tablas_TEA.md. No editar a mano.
Core layer: no infrastructure imports.
"""
from enum import Enum
class Parentesco(str, Enum):
"""pac_parentesco in table pacientes."""
HIJO = "HIJO"
HIJA = "HIJA"
HIJASTRO = "HIJASTRO"
TUTELADO = "TUTELADO"
OTRO = "OTRO"
class SexoBiologico(str, Enum):
"""pac_sexo in table pacientes."""
F = "F"
M = "M"
I = "I"
class Especialidad(str, Enum):
"""ord_especialidad in table ordenes_estudio."""
NEUROLOGIA_PEDIATRICA = "NEUROLOGIA_PEDIATRICA"
PEDIATRIA = "PEDIATRIA"
PSICOLOGIA = "PSICOLOGIA"
PSIQUIATRIA_INFANTIL = "PSIQUIATRIA_INFANTIL"
AUDIOLOGIA = "AUDIOLOGIA"
MEDICINA_FAMILIAR = "MEDICINA_FAMILIAR"
ENFERMERIA = "ENFERMERIA"
OTRO = "OTRO"
class TipoEstudio(str, Enum):
"""ord_tipo_estudio in table ordenes_estudio."""
ELECTROENCEFALOGRAMA = "ELECTROENCEFALOGRAMA"
POTENCIALES_EVOCADOS_AUDITIVOS = "POTENCIALES_EVOCADOS_AUDITIVOS"
EVALUACION_PSICOLOGICA_TEA = "EVALUACION_PSICOLOGICA_TEA"
OTRO = "OTRO"
ADOS2 = "ADOS2"
NEUROPEDIATRIA = "NEUROPEDIATRIA"
EEG = "EEG"
class EstatusEstudio(str, Enum):
"""ord_estatus in table ordenes_estudio."""
SOLICITADO = "SOLICITADO"
EN_PROCESO = "EN_PROCESO"
REALIZADO = "REALIZADO"
RESULTADO_DISPONIBLE = "RESULTADO_DISPONIBLE"
CANCELADO = "CANCELADO"
NO_ACUDIO = "NO_ACUDIO"
class VentanaMadurativa(str, Enum):
"""ord_ventana_madurativa in table ordenes_estudio."""
V1_16_23 = "V1_16_23"
V2_24_30 = "V2_24_30"
V3_31_36 = "V3_31_36"
FUERA_DE_RANGO = "FUERA_DE_RANGO"
class TipoNota(str, Enum):
"""nm_tipo_nota in table nota_medica."""
PRIMERA_VEZ = "PRIMERA_VEZ"
TAMIZAJE = "TAMIZAJE"
INTERPRETACION_EEG = "INTERPRETACION_EEG"
TRATAMIENTO = "TRATAMIENTO"
SEGUIMIENTO = "SEGUIMIENTO"
INTERCONSULTA = "INTERCONSULTA"
URGENCIA = "URGENCIA"
OTRO = "OTRO"
class Pronostico(str, Enum):
"""nm_pronostico in table nota_medica."""
BUENO = "BUENO"
RESERVADO = "RESERVADO"
MALO = "MALO"
NO_ESPECIFICADO = "NO_ESPECIFICADO"
class InstrumentoTamizaje(str, Enum):
"""psi_instrumento_tamizaje in table evaluacion_psicologica."""
M_CHAT_R = "M_CHAT_R"
M_CHAT_RF = "M_CHAT_RF"
OTRO = "OTRO"
NO_REGISTRADO = "NO_REGISTRADO"
class NivelRiesgoTamizaje(str, Enum):
"""psi_tamizaje_riesgo in table evaluacion_psicologica."""
BAJO = "BAJO"
MEDIO = "MEDIO"
ALTO = "ALTO"
NO_APLICA = "NO_APLICA"
# How the hospital writes each study, normalized (upper case, without accents) before it is looked up.
TIPO_ESTUDIO_ALIAS: dict[str, str] = {
"ADOS-2": "ADOS2",
"ADOS 2": "ADOS2",
"EVALUACION PSICOLOGICA": "ADOS2",
"EVALUACION_PSICOLOGICA_TEA": "ADOS2",
"NEUROLOGIA PEDIATRICA": "NEUROPEDIATRIA",
"NEUROLOGIA_PEDIATRICA": "NEUROPEDIATRIA",
"EVALUACION NEUROPEDIATRICA": "NEUROPEDIATRIA",
"ELECTROENCEFALOGRAMA": "EEG",
}
class ModuloAdos2(str, Enum):
"""psi_ados2_modulo in table evaluacion_psicologica."""
"""ado_modulo in table ados2."""
TODDLER = "TODDLER"
MODULO_1 = "MODULO_1"
MODULO_2 = "MODULO_2"
NO_REGISTRADO = "NO_REGISTRADO"
MODULO_3 = "MODULO_3"
class ClasificacionAdos2(str, Enum):
"""psi_ados2_clasificacion in table evaluacion_psicologica."""
NO_TEA = "NO_TEA"
"""ado_clasificacion in table ados2."""
NO_ESPECTRO = "NO_ESPECTRO"
ESPECTRO_AUTISTA = "ESPECTRO_AUTISTA"
AUTISMO = "AUTISMO"
PREOCUPACION_LEVE_MODERADA = "PREOCUPACION_LEVE_MODERADA"
PREOCUPACION_SEVERA = "PREOCUPACION_SEVERA"
class GradoHipoacusia(str, Enum):
"""pea_grado_hipoacusia in table potenciales_evocados_auditivos."""
NORMAL = "NORMAL"
LEVE = "LEVE"
MODERADA = "MODERADA"
SEVERA = "SEVERA"
PROFUNDA = "PROFUNDA"
NO_CONCLUYENTE = "NO_CONCLUYENTE"
CLASIFICACION_ADOS2_ALIAS: dict[str, str] = {"NO_TEA": "NO_ESPECTRO", "NO ESPECTRO": "NO_ESPECTRO"}
class FuenteInterpretacionEeg(str, Enum):
"""eeg_fuente_interpretacion in table eeg_estudio."""
REPORTE_NEUROPEDIATRIA = "REPORTE_NEUROPEDIATRIA"
NOTA_MEDICA = "NOTA_MEDICA"
AMBAS = "AMBAS"
NINGUNA = "NINGUNA"
class MetricaEeg(str, Enum):
"""met_codigo in table eeg_metrica."""
RITMO_POSTERIOR = "RITMO_POSTERIOR"
HUSOS_SUENO_N2 = "HUSOS_SUENO_N2"
HUSOS_SUENO_N3 = "HUSOS_SUENO_N3"
PICOS_PAROXISTICOS = "PICOS_PAROXISTICOS"
GRADIENTE_ANTEROPOSTERIOR = "GRADIENTE_ANTEROPOSTERIOR"
class EstadoRegistroEeg(str, Enum):
"""eeg_estado_registro in table eeg_estudio."""
VIGILIA = "VIGILIA"
SUENO_ESPONTANEO = "SUENO_ESPONTANEO"
SUENO_INDUCIDO = "SUENO_INDUCIDO"
MIXTO = "MIXTO"
NO_ESPECIFICADO = "NO_ESPECIFICADO"
class NivelRelacionAdos2(str, Enum):
"""rel_nivel and rel_tipo in table relacion_ados2: what the model relates, an ADOS-2 item or a domain."""
ITEM = "item"
DOMINIO = "dominio"
class CalidadTecnicaEeg(str, Enum):
"""eeg_calidad_tecnica in table eeg_estudio."""
SATISFACTORIA = "SATISFACTORIA"
LIMITADA_POR_ARTEFACTO = "LIMITADA_POR_ARTEFACTO"
LIMITADA_POR_COLABORACION = "LIMITADA_POR_COLABORACION"
NO_VALORABLE = "NO_VALORABLE"
NO_ESPECIFICADA = "NO_ESPECIFICADA"
class CriterioEeg(str, Enum):
"""cri_codigo in table eeg_criterio: the EEG analysis's check codes, channel reasons without their numbers."""
ARCHIVO = "file"
VENTANAS_LIMPIAS = "clean-windows"
COBERTURA_INTERNA = "internal-coverage"
CUERO_CABELLUDO_MALO = "bad-scalp-triage"
CUERO_CABELLUDO_UTIL = "usable-scalp"
NIVEL_TRIAJE = "triage-level"
RUIDO_LINEA = "line-noise"
CANAL_MUERTO = "dead-channel"
CONGELADO = "frozen"
SATURADO = "saturated"
VALORES_INF = "inf-values"
HUECOS_PROPIOS = "own-gaps"
PUENTE = "bridge"
AMPLITUD = "amplitude"
AMPLITUD_AUXILIAR = "aux-amplitude"
SIN_CORRELACION = "does-not-correlate"
CONTACTO_INTERMITENTE = "intermittent-contact"
CONTACTO_POR_RAFAGAS = "intermittent-bursts"
class Simetria(str, Enum):
"""eeg_simetria in table eeg_estudio."""
SIMETRICO = "SIMETRICO"
ASIMETRICO_IZQUIERDO = "ASIMETRICO_IZQUIERDO"
ASIMETRICO_DERECHO = "ASIMETRICO_DERECHO"
NO_ESPECIFICADA = "NO_ESPECIFICADA"
class TipoGrafoelemento(str, Enum):
"""eeg_tipo_grafoelemento in table eeg_estudio."""
NINGUNO = "NINGUNO"
ESPIGA = "ESPIGA"
ONDA_AGUDA = "ONDA_AGUDA"
COMPLEJO_ESPIGA_ONDA = "COMPLEJO_ESPIGA_ONDA"
COMPLEJO_POLIESPIGA_ONDA = "COMPLEJO_POLIESPIGA_ONDA"
PUNTA_ONDA_LENTA = "PUNTA_ONDA_LENTA"
DESCARGA_RITMICA = "DESCARGA_RITMICA"
OTRO = "OTRO"
class DistribucionAnormalidad(str, Enum):
"""eeg_distribucion_anormalidad in table eeg_estudio."""
FOCAL = "FOCAL"
MULTIFOCAL = "MULTIFOCAL"
GENERALIZADA = "GENERALIZADA"
LATERALIZADA = "LATERALIZADA"
NO_ESPECIFICADA = "NO_ESPECIFICADA"
class Lentificacion(str, Enum):
"""eeg_lentificacion in table eeg_estudio."""
NINGUNA = "NINGUNA"
FOCAL = "FOCAL"
GENERALIZADA = "GENERALIZADA"
INTERMITENTE = "INTERMITENTE"
class RespuestaFotoestimulacion(str, Enum):
"""eeg_respuesta_fotoestimulacion in table eeg_estudio."""
NORMAL = "NORMAL"
RESPUESTA_FOTOPAROXISTICA = "RESPUESTA_FOTOPAROXISTICA"
SIN_RESPUESTA = "SIN_RESPUESTA"
NO_PRACTICADA = "NO_PRACTICADA"
class ConclusionEeg(str, Enum):
"""eeg_conclusion_categoria in table eeg_estudio."""
NORMAL_PARA_LA_EDAD = "NORMAL_PARA_LA_EDAD"
NORMAL_CON_VARIANTES = "NORMAL_CON_VARIANTES"
ANORMAL_EPILEPTIFORME = "ANORMAL_EPILEPTIFORME"
ANORMAL_NO_EPILEPTIFORME = "ANORMAL_NO_EPILEPTIFORME"
ANORMAL_MIXTO = "ANORMAL_MIXTO"
NO_CONCLUYENTE = "NO_CONCLUYENTE"
class FuenteAntecedenteMaterno(str, Enum):
"""amg_fuente_antecedente in table antecedentes_maternos_gestacion."""
EXPEDIENTE_MATERNO = "EXPEDIENTE_MATERNO"
INTERROGATORIO_NM11 = "INTERROGATORIO_NM11"
AMBAS = "AMBAS"
NO_LOCALIZADO = "NO_LOCALIZADO"
class CategoriaPesoMaterno(str, Enum):
"""amg_categoria_peso_materno in table antecedentes_maternos_gestacion."""
BAJO_PESO = "BAJO_PESO"
NORMAL = "NORMAL"
SOBREPESO = "SOBREPESO"
OBESIDAD_I = "OBESIDAD_I"
OBESIDAD_II = "OBESIDAD_II"
OBESIDAD_III = "OBESIDAD_III"
NO_REGISTRADA = "NO_REGISTRADA"
class TipoEmbarazo(str, Enum):
"""amg_embarazo_multiple in table antecedentes_maternos_gestacion."""
UNICO = "UNICO"
GEMELAR = "GEMELAR"
TRIPLE_O_MAS = "TRIPLE_O_MAS"
NO_REGISTRADO = "NO_REGISTRADO"
class TrastornoHipertensivoGestacion(str, Enum):
"""amg_hipertension_preeclampsia in table antecedentes_maternos_gestacion."""
NINGUNO = "NINGUNO"
HIPERTENSION_GESTACIONAL = "HIPERTENSION_GESTACIONAL"
PREECLAMPSIA = "PREECLAMPSIA"
ECLAMPSIA = "ECLAMPSIA"
SINDROME_HELLP = "SINDROME_HELLP"
NO_REGISTRADO = "NO_REGISTRADO"
class VolumenLiquidoAmniotico(str, Enum):
"""amg_liquido_amniotico in table antecedentes_maternos_gestacion."""
NORMAL = "NORMAL"
OLIGOHIDRAMNIOS = "OLIGOHIDRAMNIOS"
POLIHIDRAMNIOS = "POLIHIDRAMNIOS"
NO_REGISTRADO = "NO_REGISTRADO"
class FuenteAntecedenteNeonatal(str, Enum):
"""pnn_fuente_antecedente in table parto_neonatal."""
NOTA_RECIEN_NACIDO = "NOTA_RECIEN_NACIDO"
NOTA_RESOLUCION_OBSTETRICA = "NOTA_RESOLUCION_OBSTETRICA"
INTERROGATORIO_NM11 = "INTERROGATORIO_NM11"
AMBAS = "AMBAS"
NO_LOCALIZADA = "NO_LOCALIZADA"
class TipoParto(str, Enum):
"""pnn_tipo_parto in table parto_neonatal."""
VAGINAL_ESPONTANEO = "VAGINAL_ESPONTANEO"
VAGINAL_INSTRUMENTADO = "VAGINAL_INSTRUMENTADO"
CESAREA_ELECTIVA = "CESAREA_ELECTIVA"
CESAREA_URGENCIA = "CESAREA_URGENCIA"
NO_REGISTRADO = "NO_REGISTRADO"
class ComplicacionIntraparto(str, Enum):
"""pnn_complicacion_tipo in table parto_neonatal."""
NINGUNA = "NINGUNA"
HIPOXIA = "HIPOXIA"
ISQUEMIA = "ISQUEMIA"
TRAUMA_OBSTETRICO = "TRAUMA_OBSTETRICO"
CIRCULAR_DE_CORDON = "CIRCULAR_DE_CORDON"
SUFRIMIENTO_FETAL_AGUDO = "SUFRIMIENTO_FETAL_AGUDO"
OTRA = "OTRA"
class ClasificacionEdadGestacional(str, Enum):
"""pnn_clasificacion_eg in table parto_neonatal."""
PRETERMINO_EXTREMO = "PRETERMINO_EXTREMO"
MUY_PRETERMINO = "MUY_PRETERMINO"
PRETERMINO_TARDIO = "PRETERMINO_TARDIO"
TERMINO = "TERMINO"
POSTERMINO = "POSTERMINO"
NO_DETERMINADA = "NO_DETERMINADA"
class TamanoParaEdadGestacional(str, Enum):
"""pnn_tamano_para_eg in table parto_neonatal."""
PEQUENO = "PEQUENO"
ADECUADO = "ADECUADO"
GRANDE = "GRANDE"
NO_DETERMINADO = "NO_DETERMINADO"
# The electrodes of the 10-20 system an electrode value can name (mel_electrodo).
ELECTRODOS_10_20 = (
"Fp1", "Fp2", "F7", "F3", "Fz", "F4", "F8", "T3", "C3", "Cz", "C4", "T4",
"T5", "P3", "Pz", "P4", "T6", "O1", "O2",
)
+219
View File
@@ -0,0 +1,219 @@
"""Las tablas de indicadores_kit en el dominio TEA.
Viven en el registro de `TeaModel`, en la misma base que el staging de
TEA (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 `pacientes`.
"""
from core.indicadores.cohortes import (
CohorteArmadoBase,
CohorteExclusionBase,
CohorteMiembroBase,
CohorteVariableBase,
EvaluacionRiesgoBase,
EvaluacionRiesgoLoteBase,
armado_unico,
evaluacion_unica,
variable_con_un_valor,
)
from core.indicadores.catalogos import (
CatEstudioBase,
CatMapeoBase,
CatResultadoBase,
CatSistemaFuenteBase,
CatValorBase,
estado_de_valor_conocido,
reglas_de_mapeo,
tipo_de_valor_conocido,
vigencia_ordenada,
)
from core.indicadores.plata import (
ObservacionClinicaBase,
ProcedimientoClinicoBase,
clase_conocida,
indice_de_observacion,
indice_de_procedimiento,
observacion_en_catalogo,
llave_de_observacion,
llave_de_procedimiento,
)
from core.indicadores.comunes import CargaBase, PeriodoObservacionBase, PersonaBase
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,
)
from core.tea.base import TeaModel
from sqlmodel import Field
class Persona(TeaModel, PersonaBase, table=True):
"""La persona de TEA lleva además el sexo: los indicadores de TEA lo cuentan (M2)."""
__tablename__ = "persona"
sexo: str | None = None # código de `pac_sexo` (F, M, I), ya sin espacios y en mayúsculas
class PeriodoObservacion(TeaModel, PeriodoObservacionBase, table=True):
__tablename__ = "periodo_observacion"
class Carga(TeaModel, CargaBase, table=True):
__tablename__ = "carga"
class DefParametro(TeaModel, DefParametroBase, table=True):
__tablename__ = "def_parametro"
class DimPeriodo(TeaModel, DimPeriodoBase, table=True):
__tablename__ = "dim_periodo"
class DimFecha(TeaModel, DimFechaBase, table=True):
__tablename__ = "dim_fecha"
class DimGrupoEdad(TeaModel, DimGrupoEdadBase, table=True):
__tablename__ = "dim_grupo_edad"
class MeasureReport(TeaModel, MeasureReportBase, table=True):
__tablename__ = "measure_report"
# --- El oro por unidad y su catálogo (§6f, MD-19) ---
class CatMeasure(TeaModel, CatMeasureBase, table=True):
__tablename__ = "cat_measure"
__table_args__ = contrato_y_unidad_conocidos()
class CatMeasureResultado(TeaModel, CatMeasureResultadoBase, table=True):
__tablename__ = "cat_measure_resultado"
__table_args__ = (poblacion_conocida(), una_poblacion_por_indicador())
class CatMeasureValor(TeaModel, CatMeasureValorBase, table=True):
__tablename__ = "cat_measure_valor"
__table_args__ = (origen_conocido(),)
class CatMeasureGrupo(TeaModel, CatMeasureGrupoBase, table=True):
__tablename__ = "cat_measure_grupo"
class CatEstrato(TeaModel, CatEstratoBase, table=True):
__tablename__ = "cat_estrato"
__table_args__ = (unidad_de_estrato_conocida(),)
class CatEstratoValor(TeaModel, CatEstratoValorBase, table=True):
__tablename__ = "cat_estrato_valor"
class CatMeasureEstrato(TeaModel, CatMeasureEstratoBase, table=True):
__tablename__ = "cat_measure_estrato"
class MeasureReportUnidad(TeaModel, MeasureReportUnidadBase, table=True):
__tablename__ = "measure_report_unidad"
class MeasureReportUnidadEstrato(TeaModel, 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/tea.toml ---
class CatEstudio(TeaModel, CatEstudioBase, table=True):
__tablename__ = "cat_estudio"
class CatResultado(TeaModel, CatResultadoBase, table=True):
__tablename__ = "cat_resultado"
__table_args__ = (tipo_de_valor_conocido(),)
class CatValor(TeaModel, CatValorBase, table=True):
__tablename__ = "cat_valor"
__table_args__ = (estado_de_valor_conocido(),)
class CatSistemaFuente(TeaModel, CatSistemaFuenteBase, table=True):
__tablename__ = "cat_sistema_fuente"
__table_args__ = (vigencia_ordenada("cat_sistema_fuente"),)
class CatMapeo(TeaModel, CatMapeoBase, table=True):
__tablename__ = "cat_mapeo"
__table_args__ = reglas_de_mapeo()
# --- La plata de dos tablas (F5, ADR-MD-007) ---
class Procedimiento(TeaModel, ProcedimientoClinicoBase, table=True):
__tablename__ = "procedimiento"
__table_args__ = (clase_conocida(), llave_de_procedimiento(), indice_de_procedimiento())
class Observacion(TeaModel, 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(TeaModel, CohorteArmadoBase, table=True):
__tablename__ = "cohorte_armado"
__table_args__ = (armado_unico(),)
class CohorteMiembro(TeaModel, CohorteMiembroBase, table=True):
__tablename__ = "cohorte_miembro"
class CohorteExclusion(TeaModel, CohorteExclusionBase, table=True):
__tablename__ = "cohorte_exclusion"
class CohorteVariable(TeaModel, CohorteVariableBase, table=True):
__tablename__ = "cohorte_variable"
__table_args__ = (variable_con_un_valor(),)
class EvaluacionRiesgoLote(TeaModel, EvaluacionRiesgoLoteBase, table=True):
__tablename__ = "evaluacion_riesgo_lote"
class EvaluacionRiesgo(TeaModel, EvaluacionRiesgoBase, table=True):
__tablename__ = "evaluacion_riesgo"
__table_args__ = (evaluacion_unica(),)
+270 -298
View File
@@ -1,8 +1,12 @@
"""Modelos ORM del proyecto TEA. Capa Storage: permisiva. Todos los campos
de dominio son Optional para que el loader nunca rechace un renglón. Los
booleanos se guardan como INTEGER y los enums como TEXT; la coerción es
trabajo de una capa de validación (no incluida en Core). Generado desde
spec/tablas_TEA.md. No editar a mano.
"""TEA staging tables (data dictionary: spec/tablas_TEA.md).
One table per kind of study: the M-CHAT, the ADOS-2, the neuropediatrics note and the EEG, with the patients and
the orders. The EEG's verdict, quality checks, channels, duration, sleep, metrics and electrode values are written
by the EEG analysis (the `tea` library) from the stored EDF. The ADOS-2 association model's cohort odds ratios and
per-patient z and probability land in relacion_ados2 and relacion_ados2_paciente.
Permissive storage: every domain field is optional so a load never rejects a row; booleans are INTEGER and enums
TEXT. Coercion and validation happen in the import schemas (WebApi/webapi/imports/schemas/tea).
"""
import uuid
from datetime import date, datetime
@@ -11,322 +15,290 @@ from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
from core.tea.base import TeaModel
# The ADOS-2 items with an algorithm score: social affect (SA) and restricted and repetitive behaviour (RRB).
ADOS2_ITEMS = (
"sa_a2", "sa_a6", "sa_a7", "sa_a8", "sa_b1", "sa_b2", "sa_b3", "sa_b4", "sa_b5", "sa_b6", "sa_b7", "sa_b8",
"sa_b9", "sa_b10", "sa_b11", "sa_b12", "sa_b13", "sa_b14", "sa_b15", "sa_b16b", "sa_b18",
"rrb_a3", "rrb_a4", "rrb_a5", "rrb_d1", "rrb_d2", "rrb_d4", "rrb_d5",
)
# The ADOS-2 algorithm items by what they measure: one code per item, the same in every module, with its label,
# domain and its column code in each module that scores it. A column code is not one item across modules (`sa_b5` is
# gaze integration in the Toddler module, shared enjoyment in Module 1, showing in Module 2), so the association
# model's outcomes (`relacion_ados2.rel_resultado`) carry these codes, or `CSS` for the total severity score.
ADOS2_ITEM_MEANINGS = {
"ados2_item_01": ("Vocalización espontánea dirigida a otros", "SA", {"TODDLER": "sa_a2", "MODULO_1": "sa_a2"}),
"ados2_item_02": ("Señalar", "SA", {"TODDLER": "sa_a7", "MODULO_1": "sa_a7", "MODULO_2": "sa_a6"}),
"ados2_item_03": ("Gestos", "SA", {"TODDLER": "sa_a8", "MODULO_1": "sa_a8", "MODULO_2": "sa_a7"}),
"ados2_item_04": ("Contacto visual inusual", "SA", {"TODDLER": "sa_b1", "MODULO_1": "sa_b1", "MODULO_2": "sa_b1"}),
"ados2_item_05": ("Expresiones faciales dirigidas a otros", "SA", {"TODDLER": "sa_b4", "MODULO_1": "sa_b3", "MODULO_2": "sa_b2"}),
"ados2_item_06": ("Integración de la mirada con otras conductas", "SA", {"TODDLER": "sa_b5", "MODULO_1": "sa_b4"}),
"ados2_item_07": ("Disfrute compartido en la interacción", "SA", {"TODDLER": "sa_b6", "MODULO_1": "sa_b5", "MODULO_2": "sa_b3"}),
"ados2_item_08": ("Respuesta al nombre", "SA", {"TODDLER": "sa_b7"}),
"ados2_item_09": ("Búsqueda de atención cuando se le ignora", "SA", {"TODDLER": "sa_b8"}),
"ados2_item_10": ("Pedir", "SA", {"TODDLER": "sa_b9"}),
"ados2_item_11": ("Mostrar", "SA", {"TODDLER": "sa_b12", "MODULO_1": "sa_b9", "MODULO_2": "sa_b5"}),
"ados2_item_12": ("Iniciación espontánea de la atención conjunta", "SA", {"TODDLER": "sa_b13", "MODULO_1": "sa_b10", "MODULO_2": "sa_b6"}),
"ados2_item_13": ("Respuesta a la atención conjunta", "SA", {"TODDLER": "sa_b14", "MODULO_1": "sa_b11"}),
"ados2_item_14": ("Calidad de los acercamientos sociales", "SA", {"TODDLER": "sa_b15", "MODULO_1": "sa_b12", "MODULO_2": "sa_b8"}),
"ados2_item_15": ("Cantidad de acercamientos sociales al cuidador", "SA", {"TODDLER": "sa_b16b"}),
"ados2_item_16": ("Cantidad de comunicación social recíproca", "SA", {"MODULO_2": "sa_b11"}),
"ados2_item_17": ("Calidad general de la relación", "SA", {"TODDLER": "sa_b18", "MODULO_2": "sa_b12"}),
"ados2_item_18": ("Entonación de vocalizaciones o verbalizaciones", "RRB", {"TODDLER": "rrb_a3", "MODULO_1": "rrb_a3"}),
"ados2_item_19": ("Uso estereotipado o idiosincrático de palabras", "RRB", {"MODULO_1": "rrb_a5", "MODULO_2": "rrb_a4"}),
"ados2_item_20": ("Interés sensorial inusual", "RRB", {"TODDLER": "rrb_d1", "MODULO_1": "rrb_d1", "MODULO_2": "rrb_d1"}),
"ados2_item_21": ("Manierismos de manos y dedos", "RRB", {"TODDLER": "rrb_d2", "MODULO_1": "rrb_d2", "MODULO_2": "rrb_d2"}),
"ados2_item_22": ("Intereses repetitivos o conductas estereotipadas", "RRB", {"TODDLER": "rrb_d5", "MODULO_1": "rrb_d4", "MODULO_2": "rrb_d4"}),
}
ADOS2_CSS = "CSS"
def _uuid() -> str:
return str(uuid.uuid4())
def _id() -> Field:
return Field(default_factory=_uuid, sa_column=sa.Column(sa.String(36), primary_key=True))
def _text() -> Field:
return Field(default=None, sa_column=sa.Column(sa.Text))
def _int() -> Field:
return Field(default=None, sa_column=sa.Column(sa.Integer))
def _float() -> Field:
return Field(default=None, sa_column=sa.Column(sa.Float))
def _date() -> Field:
return Field(default=None, sa_column=sa.Column(sa.Date))
def _datetime() -> Field:
return Field(default=None, sa_column=sa.Column(sa.DateTime))
class Pacientes(TeaModel, table=True):
__tablename__ = "pacientes"
pac_id: Optional[str] = Field(
default_factory=lambda: str(uuid.uuid4()),
sa_column=sa.Column(sa.String(36), primary_key=True),
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id_hospital: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pac_id_titular: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pac_parentesco: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pac_fecha_nacimiento: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
pac_sexo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pac_codigo_postal_vigente: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pac_dependencia: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pac_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
pac_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
pac_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pac_id_hospital: Optional[str] = _text()
pac_fecha_nacimiento: Optional[date] = _date()
class OrdenesEstudio(TeaModel, table=True):
__tablename__ = "ordenes_estudio"
ord_id: Optional[str] = Field(
default_factory=lambda: str(uuid.uuid4()),
sa_column=sa.Column(sa.String(36), primary_key=True),
ord_id: Optional[str] = _id()
ord_pac_id: Optional[int] = _int()
# Bounded and indexed: the natural key the import layer merges orders on.
ord_id_hospital: Optional[str] = Field(
default=None, sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True)
)
ord_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_nota_medica_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_id_hospital: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_fecha: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
ord_medico_solicitante: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_especialidad: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_diagnostico_asignado: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_cie_asignado: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_dias_vigencia: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
ord_fecha_vencimiento: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
ord_tipo_estudio: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_estatus: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_fecha_realizacion: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
ord_fecha_resultado: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
ord_dias_espera: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
ord_proveedor: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_edad_meses: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
ord_ventana_madurativa: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_pdf_ruta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_observaciones: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
ord_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
ord_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
ord_tipo_estudio: Optional[str] = _text() # TipoEstudio: ADOS2, NEUROPEDIATRIA, EEG
ord_fecha: Optional[date] = _date()
ord_pdf_blob: Optional[bytes] = Field(default=None, sa_column=sa.Column(FileBlob)) # the study's report, as PDF
class NotaMedica(TeaModel, table=True):
__tablename__ = "nota_medica"
class Mchat(TeaModel, table=True):
__tablename__ = "mchat"
nm_id: Optional[str] = Field(
default_factory=lambda: str(uuid.uuid4()),
sa_column=sa.Column(sa.String(36), primary_key=True),
mch_id: Optional[str] = _id()
mch_pac_id: Optional[int] = _int()
mch_ord_id: Optional[str] = _text()
mch_fecha: Optional[date] = _date()
mch_puntaje: Optional[int] = _int() # 0 to 20
class Ados2(TeaModel, table=True):
__tablename__ = "ados2"
ado_id: Optional[str] = _id()
ado_pac_id: Optional[int] = _int()
ado_ord_id: Optional[str] = _text()
ado_fecha: Optional[date] = _date()
ado_modulo: Optional[str] = _text()
# Within a module the algorithm depends on the child's language level (item A1).
ado_algoritmo: Optional[str] = _text()
ado_css: Optional[int] = _int() # 1 to 10
ado_clasificacion: Optional[str] = _text()
# Item scores, 0 to 3. The domain subtotals and the total are sums of their algorithm scores.
ado_sa_a2: Optional[int] = _int()
ado_sa_a6: Optional[int] = _int()
ado_sa_a7: Optional[int] = _int()
ado_sa_a8: Optional[int] = _int()
ado_sa_b1: Optional[int] = _int()
ado_sa_b2: Optional[int] = _int()
ado_sa_b3: Optional[int] = _int()
ado_sa_b4: Optional[int] = _int()
ado_sa_b5: Optional[int] = _int()
ado_sa_b6: Optional[int] = _int()
ado_sa_b7: Optional[int] = _int()
ado_sa_b8: Optional[int] = _int()
ado_sa_b9: Optional[int] = _int()
ado_sa_b10: Optional[int] = _int()
ado_sa_b11: Optional[int] = _int()
ado_sa_b12: Optional[int] = _int()
ado_sa_b13: Optional[int] = _int()
ado_sa_b14: Optional[int] = _int()
ado_sa_b15: Optional[int] = _int()
ado_sa_b16b: Optional[int] = _int()
ado_sa_b18: Optional[int] = _int()
ado_rrb_a3: Optional[int] = _int()
ado_rrb_a4: Optional[int] = _int()
ado_rrb_a5: Optional[int] = _int()
ado_rrb_d1: Optional[int] = _int()
ado_rrb_d2: Optional[int] = _int()
ado_rrb_d4: Optional[int] = _int()
ado_rrb_d5: Optional[int] = _int()
class EvaluacionNeuropediatrica(TeaModel, table=True):
__tablename__ = "evaluacion_neuropediatrica"
neu_id: Optional[str] = _id()
neu_pac_id: Optional[int] = _int()
neu_ord_id: Optional[str] = _text()
neu_fecha: Optional[date] = _date()
neu_cie_codigo: Optional[str] = _text()
class Eeg(TeaModel, table=True):
__tablename__ = "eeg"
eeg_id: Optional[str] = _id()
eeg_pac_id: Optional[int] = _int()
eeg_ord_id: Optional[str] = _text()
# Bounded and indexed: the natural key several sources (a report, the EDF itself) land in the same row by.
eeg_id_registro_laboratorio: Optional[str] = Field(
default=None, sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True)
)
nm_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_id_hospital: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_nota_previa_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_tipo_nota: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_especialidad: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_fecha: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
nm_edad_meses: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
nm_ventana_madurativa: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_medico_tratante: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_motivo_consulta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_interrogatorio: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_regresion_referida: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
nm_antecedente_familiar_tea: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
nm_perimetro_cefalico: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
nm_diagnostico_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_cie_codigo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_cie_descripcion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_tratamiento_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_receta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_plan_estudios: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_pronostico: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_observaciones: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_masa_corporal: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
nm_talla: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
nm_imc_visita: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
nm_frecuencia_cardiaca: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
nm_frecuencia_respiratoria: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
nm_presion_arterial_sistolica: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
nm_presion_arterial_diastolica: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
nm_temperatura: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
nm_pdf_ruta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
nm_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
nm_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
nm_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_fecha_estudio: Optional[date] = _date()
# Written by the EEG analysis.
eeg_con_sueno: Optional[int] = _int()
eeg_canales: Optional[int] = _int()
eeg_duracion_min: Optional[float] = _float()
eeg_ruido_linea_db: Optional[float] = _float()
eeg_estudio: Optional[bytes] = Field(default=None, sa_column=sa.Column(FileBlob)) # the EDF
# The analysis's verdict: 1 valid, 0 not valid, null not analysed yet. Its checks are rows of eeg_criterio.
eeg_valido: Optional[int] = _int()
eeg_nivel: Optional[str] = _text() # triage level: completo, sin_referencia_auricular, parcial, no_analizable
eeg_fraccion_limpia: Optional[float] = _float()
eeg_canales_malos: Optional[int] = _int()
eeg_edad_meses: Optional[float] = _float() # the age the analysis compared the metrics at
# What produced the analysis, so a new plan or module version analyses the EEG again.
eeg_plan_hash: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(16)))
eeg_versiones: Optional[str] = _text()
eeg_analizado_en: Optional[datetime] = _datetime()
eeg_error: Optional[str] = _text()
class EvaluacionPsicologica(TeaModel, table=True):
__tablename__ = "evaluacion_psicologica"
class EegCriterio(TeaModel, table=True):
"""One quality check the EEG analysis evaluated on an EEG: a study rule, or a bad channel with its electrode."""
psi_id: Optional[str] = Field(
default_factory=lambda: str(uuid.uuid4()),
sa_column=sa.Column(sa.String(36), primary_key=True),
__tablename__ = "eeg_criterio"
cri_id: Optional[str] = _id()
cri_eeg_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(36), index=True))
cri_codigo: Optional[str] = _text() # CriterioEeg
cri_electrodo: Optional[str] = _text()
cri_valor: Optional[float] = _float()
cri_valor_texto: Optional[str] = _text()
cri_unidad: Optional[str] = _text()
cri_bajo: Optional[float] = _float() # out of range below this
cri_alto: Optional[float] = _float() # out of range above this
cri_decisivo: Optional[int] = _int() # this check alone can make the EEG not valid
cri_anormal: Optional[int] = _int()
class EegMetrica(TeaModel, table=True):
"""One metric the EEG analysis measured on an EEG. A null value is a metric that can't be evaluated."""
__tablename__ = "eeg_metrica"
met_id: Optional[str] = _id()
met_eeg_id: Optional[str] = _text()
met_codigo: Optional[str] = _text() # MetricaEeg
met_valor: Optional[float] = _float()
# Against the age baseline at eeg_edad_meses: z, -1/0/+1 below p5 / within / above p95, and the curve there.
met_z: Optional[float] = _float()
met_fuera: Optional[int] = _int()
met_p5: Optional[float] = _float()
met_mediana: Optional[float] = _float()
met_p95: Optional[float] = _float()
met_modelo: Optional[str] = _text() # the baseline's registered model version
class EegMetricaElectrodo(TeaModel, table=True):
"""A metric's value at one electrode of the 10-20 system."""
__tablename__ = "eeg_metrica_electrodo"
mel_id: Optional[str] = _id()
mel_met_id: Optional[str] = _text()
mel_electrodo: Optional[str] = _text()
mel_valor: Optional[float] = _float()
mel_z: Optional[float] = _float()
class EegMetricaZona(TeaModel, table=True):
"""A metric's value over one scalp zone (the `tea` library's zones), with its z against the zone's baseline."""
__tablename__ = "eeg_metrica_zona"
mez_id: Optional[str] = _id()
mez_met_id: Optional[str] = _text()
mez_zona: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32)))
mez_valor: Optional[float] = _float()
mez_z: Optional[float] = _float()
class RelacionAdos2(TeaModel, table=True):
"""One association of an EEG alteration in a scalp zone with an ADOS-2 outcome, per fitted model version."""
__tablename__ = "relacion_ados2"
__table_args__ = (
sa.UniqueConstraint("rel_version", "rel_biomarcador", "rel_zona", "rel_resultado", name="uq_relacion_ados2"),
)
psi_ord_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_fecha_evaluacion: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
psi_psicologo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_edad_meses: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
psi_ventana_madurativa: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_instrumento_tamizaje: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_tamizaje_puntaje: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_tamizaje_riesgo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_ados2_modulo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
# Columnas de item del ADOS-2 (Anexo B del diccionario de datos) — el rango
# valido y la pertenencia a modulo dependen de psi_ados2_modulo.
psi_ados2_sa_a2: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_a6: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_a7: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_a8: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b1: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b2: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b3: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b4: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b5: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b6: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b7: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b8: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b9: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b10: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b11: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b12: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b13: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b14: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b15: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b16b: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa_b18: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_rrb_a3: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_rrb_a4: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_rrb_a5: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_rrb_d1: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_rrb_d2: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_rrb_d4: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_rrb_d5: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_sa: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_rrb: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_total: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_css: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_css_sa: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_css_rrb: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_ados2_clasificacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_rgd: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_cociente_desarrollo: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
psi_css_umbral_aplicado: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_caso_confirmado: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_cars_total: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
psi_otros_instrumentos: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_regresion_desarrollo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
psi_diagnostico_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
psi_nlp_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
psi_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
psi_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
rel_id: Optional[str] = _id()
# Bounded: the natural key the import layer and the tea library merge model rows on is a unique index.
rel_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32), index=True))
rel_nivel: Optional[str] = _text() # NivelRelacionAdos2: the model's level
rel_validado: Optional[int] = _int() # 1 validated by the domain expert, 0 pending
rel_n_cohorte: Optional[int] = _int()
rel_biomarcador: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32))) # MetricaEeg
rel_zona: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32))) # scalp zone code from the tea library
rel_tipo: Optional[str] = _text() # NivelRelacionAdos2: the level this association relates
rel_resultado: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32))) # ADOS-2 item or domain code
rel_evento: Optional[str] = _text() # the outcome event, e.g. "score >= 2"
rel_or: Optional[float] = _float()
rel_ic_inf: Optional[float] = _float()
rel_ic_sup: Optional[float] = _float()
rel_q: Optional[float] = _float()
class PotencialesEvocadosAuditivos(TeaModel, table=True):
__tablename__ = "potenciales_evocados_auditivos"
class RelacionAdos2Paciente(TeaModel, table=True):
"""One patient's z and model probability for an association row: the EEG's metric z mapped through relacion_ados2."""
pea_id: Optional[str] = Field(
default_factory=lambda: str(uuid.uuid4()),
sa_column=sa.Column(sa.String(36), primary_key=True),
__tablename__ = "relacion_ados2_paciente"
__table_args__ = (
sa.UniqueConstraint("rap_rel_id", "rap_eeg_id", name="uq_relacion_ados2_paciente"),
)
pea_ord_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pea_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pea_fecha_estudio: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
pea_medico_interpreta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pea_umbral_od: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pea_umbral_oi: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pea_latencia_v_od: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pea_latencia_v_oi: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pea_interpico_i_v_od: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pea_interpico_i_v_oi: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pea_grado_hipoacusia: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pea_conclusion_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pea_flag_diferencial_auditivo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pea_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pea_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
pea_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
class EegEstudio(TeaModel, table=True):
__tablename__ = "eeg_estudio"
eeg_id: Optional[str] = Field(
default_factory=lambda: str(uuid.uuid4()),
sa_column=sa.Column(sa.String(36), primary_key=True),
)
eeg_ord_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_reporte_disponible: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_fuente_interpretacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_fecha_nacimiento_declarada: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
eeg_edad_meses: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
eeg_fecha_estudio: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
eeg_fecha_reporte: Optional[date] = Field(default=None, sa_column=sa.Column(sa.Date))
eeg_dias_respuesta: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_medico_interpreta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_estado_registro: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_privacion_sueno: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_sedacion: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_sedacion_farmaco: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_duracion_min: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_calidad_tecnica: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_descripcion_senal: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_ritmo_base_frecuencia: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
eeg_ritmo_base_amplitud: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_simetria: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_anormalidad_presente: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_actividad_epileptiforme: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_tipo_grafoelemento: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_distribucion_anormalidad: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_localizacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_activacion_sueno: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_lentificacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_crisis_registradas: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
eeg_respuesta_fotoestimulacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_conclusion_texto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_conclusion_categoria: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_id_registro_laboratorio: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_pdf_ruta: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
eeg_nlp_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
eeg_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
eeg_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
class AntecedentesMaternosGestacion(TeaModel, table=True):
__tablename__ = "antecedentes_maternos_gestacion"
amg_id: Optional[str] = Field(
default_factory=lambda: str(uuid.uuid4()),
sa_column=sa.Column(sa.String(36), primary_key=True),
)
amg_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_id_madre_seudonimo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_fuente_antecedente: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_flag_vinculo_verificado: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_imc_pregestacional: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
amg_categoria_peso_materno: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_tabaquismo_gestacion: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_acido_folico_preconcepcional: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_intervalo_intergenesico_meses: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_antecedente_aborto: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_embarazo_multiple: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_infeccion_gestacion: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_infeccion_tipo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_infeccion_hospitalizacion: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_diabetes_gestacional: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_hipertension_preeclampsia: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_hipotiroidismo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_hipertiroidismo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_incompatibilidad_rh: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_crisis_convulsivas: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_proceso_proinflamatorio: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_enfermedad_autoinmune: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_migrana: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_asma: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_hipoxia_materna: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_estres_agudo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_trastorno_neurologico: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_liquido_amniotico: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_medicamentos_gestacion: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_farmaco_riesgo_neurodesarrollo: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
amg_observaciones: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
amg_nlp_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
amg_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
amg_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
amg_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
class PartoNeonatal(TeaModel, table=True):
__tablename__ = "parto_neonatal"
pnn_id: Optional[str] = Field(
default_factory=lambda: str(uuid.uuid4()),
sa_column=sa.Column(sa.String(36), primary_key=True),
)
pnn_pac_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pnn_fuente_antecedente: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pnn_tipo_parto: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pnn_complicaciones_intraparto: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_complicacion_tipo: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pnn_peso_nacer_g: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_talla_nacer_cm: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pnn_perimetro_cefalico_nacer_cm: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pnn_edad_gestacional_sem: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pnn_clasificacion_eg: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pnn_tamano_para_eg: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pnn_peso_nacer_zscore: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pnn_apgar_1min: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_apgar_5min: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_ingreso_ucin: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_dias_ucin: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_encefalopatia_hipoxico_isquemica: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_hipotermia_nacer: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_hiperbilirrubinemia: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_fototerapia: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_hipoglucemia_neonatal: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_anoxia: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_sindrome_congenito: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_sindrome_congenito_desc: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pnn_flag_riesgo_neonatal: Optional[int] = Field(default=None, sa_column=sa.Column(sa.Integer))
pnn_observaciones: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pnn_ocr_confianza: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
pnn_nlp_version: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
pnn_created_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
pnn_updated_at: Optional[datetime] = Field(default=None, sa_column=sa.Column(sa.DateTime))
pnn_fuente_sistema: Optional[str] = Field(default=None, sa_column=sa.Column(sa.Text))
rap_id: Optional[str] = _id()
rap_rel_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(36), index=True))
rap_eeg_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(36), index=True))
rap_valor_z: Optional[float] = _float()
rap_probabilidad: Optional[float] = _float()
rap_probabilidad_referencia: Optional[float] = _float()
+8
View File
@@ -7,6 +7,14 @@ dependencies = [
"sqlmodel>=0.0.22",
]
[project.optional-dependencies]
# DB-API drivers for running the portability tests against MySQL/MariaDB or
# PostgreSQL instead of just SQLite.
drivers = [
"pymysql>=1.1",
"psycopg2-binary>=2.9",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
+148 -403
View File
@@ -1,8 +1,15 @@
# Diccionario de datos y reglas de validación — Proyecto TEA
Este documento describe la base de datos del proyecto. Para cada tabla se listan sus
variables, el tipo de dato, la unidad (cuando aplica) y la validación que debe
cumplir cada una.
Este documento describe el staging del proyecto: una tabla por tipo de estudio (M-CHAT, ADOS-2, nota de
neuropediatría y EEG), más los pacientes y las órdenes, y las dos del modelo de asociación con el ADOS-2
(`relacion_ados2` y `relacion_ados2_paciente`). Para cada tabla se listan sus variables, el tipo de dato,
la unidad (cuando aplica) y la validación que cumple cada una al importarse. El almacenamiento es permisivo: todo
campo es opcional y la validación ocurre en los esquemas de importación (`WebApi/webapi/imports/schemas/tea`).
Las columnas marcadas **(análisis del EEG)** las escribe el análisis del EEG (la biblioteca `tea`) a partir del EDF
guardado: veredicto, criterios de calidad, canales, duración, sueño, métricas y valores por electrodo y por zona. Las dos
tablas de asociación con el ADOS-2 las escribe el modelo de asociación (también la biblioteca `tea`), y mientras
este llega la API de importación carga renglones de desarrollo igual que el resto del staging.
---
@@ -10,19 +17,9 @@ cumplir cada una.
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `pac_id` | VARCHAR(36), llave primaria | — | — | — |
| `pac_id` | INTEGER, llave primaria, autoincremental | — | — | — |
| `pac_id_hospital` | TEXT | — | — | — |
| `pac_id_titular` | TEXT | — | — | — |
| `pac_parentesco` | TEXT | — | Catálogo cerrado `Parentesco`: `HIJO, HIJA, HIJASTRO, TUTELADO, OTRO`. | — |
| `pac_fecha_nacimiento` | DATE | — | No puede ser una fecha futura. | — |
| `pac_sexo` | TEXT | — | Catálogo cerrado `SexoBiologico`: `F, M, I`. | — |
| `pac_codigo_postal_vigente` | TEXT | — | Debe quedar en 5 dígitos numéricos exactos (se completa con ceros a la izquierda si llega con menos). | — |
| `pac_dependencia` | TEXT | — | — | — |
| `pac_created_at` | DATETIME | — | — | — |
| `pac_updated_at` | DATETIME | — | — | — |
| `pac_fuente_sistema` | TEXT | — | — | — |
Sin validaciones cruzadas.
---
@@ -31,443 +28,191 @@ Sin validaciones cruzadas.
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `ord_id` | VARCHAR(36), llave primaria | — | — | — |
| `ord_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
| `ord_nota_medica_id` | TEXT | — | — | → `nota_medica.nm_id` |
| `ord_id_hospital` | TEXT | — | — | — |
| `ord_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
| `ord_id_hospital` | VARCHAR(64), indexado | — | Llave natural para unir órdenes de varias fuentes al importar. | — |
| `ord_tipo_estudio` | TEXT | — | Catálogo `TipoEstudio`: `ADOS2, NEUROPEDIATRIA, EEG`. | — |
| `ord_fecha` | DATE | — | No puede ser una fecha futura. | — |
| `ord_medico_solicitante` | TEXT | — | — | — |
| `ord_especialidad` | TEXT | — | Catálogo `Especialidad`: `NEUROLOGIA_PEDIATRICA, PEDIATRIA, PSICOLOGIA, PSIQUIATRIA_INFANTIL, AUDIOLOGIA, MEDICINA_FAMILIAR, ENFERMERIA, OTRO`. | — |
| `ord_diagnostico_asignado` | TEXT | — | — | — |
| `ord_cie_asignado` | TEXT | — | Formato CIE: una letra mayúscula, dos dígitos, y opcionalmente un punto con uno o dos dígitos más (ejemplo: `A09.1`). | — |
| `ord_dias_vigencia` | INTEGER | días | Entre 1 y 365. | — |
| `ord_fecha_vencimiento` | DATE | — | Ver validación cruzada. | — |
| `ord_proveedor` | TEXT | — | — | — |
| `ord_tipo_estudio` | TEXT | — | Catálogo `TipoEstudio`: `ELECTROENCEFALOGRAMA, POTENCIALES_EVOCADOS_AUDITIVOS, EVALUACION_PSICOLOGICA_TEA, OTRO`. | — |
| `ord_estatus` | TEXT | — | Catálogo `EstatusEstudio`: `SOLICITADO, EN_PROCESO, REALIZADO, RESULTADO_DISPONIBLE, CANCELADO, NO_ACUDIO`. | — |
| `ord_fecha_realizacion` | DATE | — | No puede ser una fecha futura. Ver validación cruzada. | — |
| `ord_fecha_resultado` | DATE | — | No puede ser una fecha futura. Ver validación cruzada. | — |
| `ord_dias_espera` | INTEGER | días | Entre 0 y 180. | — |
| `ord_edad_meses` | FLOAT | meses | Entre 16.0 y 36.0. | — |
| `ord_ventana_madurativa` | TEXT | — | Catálogo `VentanaMadurativa`: `V1_16_23, V2_24_30, V3_31_36, FUERA_DE_RANGO`. Ver validación cruzada. | — |
| `ord_pdf_ruta` | TEXT | — | — | — |
| `ord_observaciones` | TEXT | — | — | — |
| `ord_created_at` | DATETIME | — | — | — |
| `ord_updated_at` | DATETIME | — | — | — |
| `ord_fuente_sistema` | TEXT | — | — | — |
**Validaciones cruzadas de `ordenes_estudio`:**
- `ord_fecha_vencimiento` debe ser igual a `ord_fecha + ord_dias_vigencia` días, cuando ambos valores existen.
- `ord_fecha_realizacion` no puede ser anterior a `ord_fecha`.
- `ord_fecha_resultado` no puede ser anterior a `ord_fecha_realizacion`.
- `ord_ventana_madurativa` debe corresponder a `ord_edad_meses` según la tabla de ventanas (Anexo A).
| `ord_pdf_blob` | BLOB (LONGBLOB en MySQL/MariaDB) | — | Informe del estudio en PDF, si la fuente lo trae. | — |
---
## 3. Tabla `nota_medica`
## 3. Tabla `mchat`
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `nm_id` | VARCHAR(36), llave primaria | — | — | — |
| `nm_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
| `nm_id_hospital` | TEXT | — | — | — |
| `nm_nota_previa_id` | TEXT | — | — | → `nota_medica.nm_id` (autorreferencia: nota previa del mismo paciente) |
| `nm_tipo_nota` | TEXT | — | Catálogo `TipoNota`: `PRIMERA_VEZ, TAMIZAJE, INTERPRETACION_EEG, TRATAMIENTO, SEGUIMIENTO, INTERCONSULTA, URGENCIA, OTRO`. | — |
| `nm_especialidad` | TEXT | — | Catálogo `Especialidad` (mismo que `ord_especialidad`). | — |
| `nm_fecha` | DATE | — | No puede ser una fecha futura. | — |
| `nm_edad_meses` | FLOAT | meses | Entre 16.0 y 36.0. | — |
| `nm_ventana_madurativa` | TEXT | — | Catálogo `VentanaMadurativa`. Ver validación cruzada. | — |
| `nm_medico_tratante` | TEXT | — | — | — |
| `nm_motivo_consulta` | TEXT | — | — | — |
| `nm_interrogatorio` | TEXT | — | — | — |
| `nm_regresion_referida` | BOOL | — | — | — |
| `nm_antecedente_familiar_tea` | BOOL | — | — | — |
| `nm_perimetro_cefalico` | FLOAT | cm | Entre 38.0 y 58.0. | — |
| `nm_diagnostico_texto` | TEXT | — | — | — |
| `nm_cie_codigo` | TEXT | — | Formato CIE: una letra mayúscula, dos dígitos, punto opcional con uno o dos dígitos más. | — |
| `nm_cie_descripcion` | TEXT | — | — | — |
| `nm_tratamiento_texto` | TEXT | — | — | — |
| `nm_receta` | TEXT | — | — | — |
| `nm_plan_estudios` | TEXT | — | — | — |
| `nm_pronostico` | TEXT | — | Catálogo `Pronostico`: `BUENO, RESERVADO, MALO, NO_ESPECIFICADO`. | — |
| `nm_observaciones` | TEXT | — | — | — |
| `nm_masa_corporal` | FLOAT | kg | Entre 2.0 y 40.0. | — |
| `nm_talla` | FLOAT | m | Entre 0.4 y 1.4. | — |
| `nm_imc_visita` | FLOAT | kg/m² | Entre 5.0 y 40.0. Ver validación cruzada con peso y talla. | — |
| `nm_frecuencia_cardiaca` | INTEGER | lpm | Entre 50 y 230. | — |
| `nm_frecuencia_respiratoria` | INTEGER | rpm | Entre 10 y 80. | — |
| `nm_presion_arterial_sistolica` | INTEGER | mmHg | Entre 45 y 160. Ver validación cruzada. | — |
| `nm_presion_arterial_diastolica` | INTEGER | mmHg | Entre 25 y 110. Ver validación cruzada. | — |
| `nm_temperatura` | FLOAT | °C | Entre 32.0 y 43.0. | — |
| `nm_pdf_ruta` | TEXT | — | — | — |
| `nm_created_at` | DATETIME | — | — | — |
| `nm_updated_at` | DATETIME | — | — | — |
| `nm_fuente_sistema` | TEXT | — | — | — |
**Validaciones cruzadas de `nota_medica`:**
- La presión sistólica debe ser mayor que la diastólica.
- `nm_imc_visita` debe ser aproximadamente igual a `nm_masa_corporal / nm_talla²` (tolerancia de 0.5).
- `nm_ventana_madurativa` debe corresponder a `nm_edad_meses` (Anexo A).
| `mch_id` | VARCHAR(36), llave primaria | — | — | — |
| `mch_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
| `mch_ord_id` | TEXT | — | Casi siempre nulo: el M-CHAT rara vez tiene orden. | → `ordenes_estudio.ord_id` |
| `mch_fecha` | DATE | — | No puede ser una fecha futura. | — |
| `mch_puntaje` | INTEGER | puntos | Entre 0 y 20. | — |
---
## 4. Tabla `evaluacion_psicologica`
## 4. Tabla `ados2`
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `psi_id` | VARCHAR(36), llave primaria | — | — | — |
| `psi_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
| `psi_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
| `psi_fecha_evaluacion` | DATE | — | No puede ser una fecha futura. | — |
| `psi_psicologo` | TEXT | — | — | — |
| `psi_edad_meses` | FLOAT | meses | Entre 16.0 y 36.0. | — |
| `psi_ventana_madurativa` | TEXT | — | Catálogo `VentanaMadurativa`. Ver validación cruzada. | — |
| `psi_instrumento_tamizaje` | TEXT | — | Catálogo `InstrumentoTamizaje`: `M_CHAT_R, M_CHAT_RF, OTRO, NO_REGISTRADO`. | — |
| `psi_tamizaje_puntaje` | INTEGER | — | Entre 0 y 20. | — |
| `psi_tamizaje_riesgo` | TEXT | — | Catálogo `NivelRiesgoTamizaje`: `BAJO, MEDIO, ALTO, NO_APLICA`. | — |
| `psi_ados2_modulo` | TEXT | — | Catálogo `ModuloAdos2`: `TODDLER, MODULO_1, MODULO_2, NO_REGISTRADO`. Define qué ítems del ADOS-2 aplican (Anexo B). | — |
| `psi_ados2_sa` | INTEGER | — | Entre 0 y 30. Ver validación cruzada. | — |
| `psi_ados2_rrb` | INTEGER | — | Entre 0 y 20. Ver validación cruzada. | — |
| `psi_ados2_total` | INTEGER | — | Entre 0 y 50. Debe ser igual a `psi_ados2_sa + psi_ados2_rrb`. | — |
| `psi_ados2_css` | INTEGER | — | Entre 1 y 10. | — |
| `psi_ados2_css_sa` | INTEGER | — | Entre 1 y 10. | — |
| `psi_ados2_css_rrb` | INTEGER | — | Entre 1 y 10. | — |
| `psi_ados2_clasificacion` | TEXT | — | Catálogo `ClasificacionAdos2`: `NO_TEA, ESPECTRO_AUTISTA, AUTISMO, PREOCUPACION_LEVE_MODERADA, PREOCUPACION_SEVERA`. | — |
| `psi_rgd` | BOOL | — | Ver validación cruzada (retraso global del desarrollo). | — |
| `psi_cociente_desarrollo` | FLOAT | — | Entre 20.0 y 160.0. | — |
| `psi_css_umbral_aplicado` | INTEGER | — | Entre 1 y 10. Ver validación cruzada. | — |
| `psi_caso_confirmado` | BOOL | — | Ver validación cruzada. | — |
| `psi_cars_total` | FLOAT | — | Entre 15.0 y 60.0. Solo válido a partir de los 24 meses (ver validación cruzada). | — |
| `psi_otros_instrumentos` | TEXT | — | — | — |
| `psi_regresion_desarrollo` | BOOL | — | — | — |
| `psi_diagnostico_texto` | TEXT | — | — | — |
| `psi_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
| `psi_nlp_version` | TEXT | — | — | — |
| `psi_created_at` | DATETIME | — | — | — |
| `psi_updated_at` | DATETIME | — | — | — |
| `ado_id` | VARCHAR(36), llave primaria | — | — | — |
| `ado_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
| `ado_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
| `ado_fecha` | DATE | — | No puede ser una fecha futura. | — |
| `ado_modulo` | TEXT | — | Catálogo `ModuloAdos2`: `TODDLER, MODULO_1, MODULO_2, MODULO_3`. | — |
| `ado_algoritmo` | TEXT | — | El algoritmo del módulo, que depende del nivel de lenguaje (reactivo A1). | — |
| `ado_css` | INTEGER | puntos | Entre 1 y 10. | — |
| `ado_clasificacion` | TEXT | — | Catálogo `ClasificacionAdos2`: `NO_ESPECTRO, ESPECTRO_AUTISTA, AUTISMO, PREOCUPACION_LEVE_MODERADA, PREOCUPACION_SEVERA`. | — |
| `ado_sa_a2` … `ado_sa_b18` (21) | INTEGER | puntos | Entre 0 y 3. Reactivos de afecto social. | — |
| `ado_rrb_a3` … `ado_rrb_d5` (7) | INTEGER | puntos | Entre 0 y 3. Reactivos de comportamiento restringido y repetitivo. | — |
**Columnas de ítem del ADOS-2** (mismo tipo y patrón de validación que los puntajes enteros de arriba):
| Variable | Tipo | Unidad | Validación |
|---|---|---|---|
| `psi_ados2_sa_a2`, `psi_ados2_sa_a6`, `psi_ados2_sa_a7`, `psi_ados2_sa_a8`, `psi_ados2_sa_b1` … `psi_ados2_sa_b16b`, `psi_ados2_sa_b18` | INTEGER | — | Rango permitido según el módulo (Anexo B); fuera de rango se rechaza. |
| `psi_ados2_rrb_a3`, `psi_ados2_rrb_a4`, `psi_ados2_rrb_a5`, `psi_ados2_rrb_d1`, `psi_ados2_rrb_d2`, `psi_ados2_rrb_d4`, `psi_ados2_rrb_d5` | INTEGER | — | Rango permitido según el módulo (Anexo B); fuera de rango se rechaza. |
El detalle exacto de rango por código y por módulo, la validación de completitud y
la validación de pertenencia a módulo están en el **Anexo B**.
**Validaciones cruzadas de `evaluacion_psicologica`:**
- `psi_ados2_total` debe ser igual a `psi_ados2_sa + psi_ados2_rrb`.
- `psi_css_umbral_aplicado` debe ser 6 si `psi_rgd` es verdadero, y 5 si es falso.
- `psi_caso_confirmado` debe ser igual a `psi_ados2_css >= psi_css_umbral_aplicado`.
- `psi_cars_total` solo es válido si la ventana madurativa no es `V1_16_23` (la escala CARS aplica desde los 24 meses).
- `psi_ventana_madurativa` debe corresponder a `psi_edad_meses` (Anexo A).
- `psi_rgd` debe ser verdadero cuando `psi_cociente_desarrollo` es menor o igual a 75.0, y falso en caso contrario.
Las validaciones cruzadas propias del Anexo B (completitud y pertenencia a módulo) se
suman a esta lista.
Los subtotales por dominio y el total no se guardan: son sumas de los puntajes de algoritmo de los reactivos.
---
## 5. Tabla `potenciales_evocados_auditivos`
## 5. Tabla `evaluacion_neuropediatrica`
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `pea_id` | VARCHAR(36), llave primaria | — | — | — |
| `pea_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
| `pea_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
| `pea_fecha_estudio` | DATE | — | No puede ser una fecha futura. | — |
| `pea_medico_interpreta` | TEXT | — | — | — |
| `pea_umbral_od` | INTEGER | dB | Entre 0 y 120 (oído derecho). | — |
| `pea_umbral_oi` | INTEGER | dB | Entre 0 y 120 (oído izquierdo). | — |
| `pea_latencia_v_od` | FLOAT | ms | Entre 3.5 y 12.0. | — |
| `pea_latencia_v_oi` | FLOAT | ms | Entre 3.5 y 12.0. | — |
| `pea_interpico_i_v_od` | FLOAT | ms | Entre 2.0 y 8.0. | — |
| `pea_interpico_i_v_oi` | FLOAT | ms | Entre 2.0 y 8.0. | — |
| `pea_grado_hipoacusia` | TEXT | — | Catálogo `GradoHipoacusia`: `NORMAL, LEVE, MODERADA, SEVERA, PROFUNDA, NO_CONCLUYENTE`. | — |
| `pea_conclusion_texto` | TEXT | — | — | — |
| `pea_flag_diferencial_auditivo` | BOOL | — | Ver validación cruzada. | — |
| `pea_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
| `pea_created_at` | DATETIME | — | — | — |
| `pea_updated_at` | DATETIME | — | — | — |
**Validación cruzada de `potenciales_evocados_auditivos`:**
- Si `pea_grado_hipoacusia` es `MODERADA`, `SEVERA` o `PROFUNDA`, entonces `pea_flag_diferencial_auditivo` debe ser verdadero.
| `neu_id` | VARCHAR(36), llave primaria | — | — | — |
| `neu_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
| `neu_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
| `neu_fecha` | DATE | — | No puede ser una fecha futura. | — |
| `neu_cie_codigo` | TEXT | — | Formato CIE-10: una letra, dos dígitos y opcionalmente un punto con uno o dos dígitos (`F84.0`). | — |
---
## 6. Tabla `eeg_estudio`
## 6. Tabla `eeg`
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `eeg_id` | VARCHAR(36), llave primaria | — | — | — |
| `eeg_pac_id` | INTEGER | — | — | → `pacientes.pac_id` |
| `eeg_ord_id` | TEXT | — | — | → `ordenes_estudio.ord_id` |
| `eeg_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
| `eeg_reporte_disponible` | BOOL | — | Ver validación cruzada. | — |
| `eeg_fuente_interpretacion` | TEXT | — | Catálogo `FuenteInterpretacionEeg`: `REPORTE_NEUROPEDIATRIA, NOTA_MEDICA, AMBAS, NINGUNA`. | — |
| `eeg_fecha_nacimiento_declarada` | DATE | — | No puede ser una fecha futura. | — |
| `eeg_edad_meses` | FLOAT | meses | Entre 16.0 y 36.0. | — |
| `eeg_id_registro_laboratorio` | VARCHAR(64), indexado | — | Llave natural: el reporte y el EDF del mismo estudio caen en la misma fila. | — |
| `eeg_fecha_estudio` | DATE | — | No puede ser una fecha futura. | — |
| `eeg_fecha_reporte` | DATE | — | No puede ser una fecha futura. Ver validación cruzada. | — |
| `eeg_dias_respuesta` | INTEGER | días | Entre 0 y 60. Ver validación cruzada. | — |
| `eeg_medico_interpreta` | TEXT | — | — | — |
| `eeg_estado_registro` | TEXT | — | Catálogo `EstadoRegistroEeg`: `VIGILIA, SUENO_ESPONTANEO, SUENO_INDUCIDO, MIXTO, NO_ESPECIFICADO`. | — |
| `eeg_privacion_sueno` | BOOL | — | — | — |
| `eeg_sedacion` | BOOL | — | Ver validación cruzada. | — |
| `eeg_sedacion_farmaco` | TEXT | — | Ver validación cruzada. | — |
| `eeg_duracion_min` | INTEGER | min | Entre 10 y 1440. | — |
| `eeg_calidad_tecnica` | TEXT | — | Catálogo `CalidadTecnicaEeg`: `SATISFACTORIA, LIMITADA_POR_ARTEFACTO, LIMITADA_POR_COLABORACION, NO_VALORABLE, NO_ESPECIFICADA`. | — |
| `eeg_descripcion_senal` | TEXT | — | — | — |
| `eeg_ritmo_base_frecuencia` | FLOAT | Hz | Entre 2.0 y 14.0. | — |
| `eeg_ritmo_base_amplitud` | INTEGER | µV | Entre 5 y 300. | — |
| `eeg_simetria` | TEXT | — | Catálogo `Simetria`: `SIMETRICO, ASIMETRICO_IZQUIERDO, ASIMETRICO_DERECHO, NO_ESPECIFICADA`. | — |
| `eeg_anormalidad_presente` | BOOL | — | Ver validación cruzada. | — |
| `eeg_actividad_epileptiforme` | BOOL | — | Ver validación cruzada. | — |
| `eeg_tipo_grafoelemento` | TEXT | — | Catálogo `TipoGrafoelemento`: `NINGUNO, ESPIGA, ONDA_AGUDA, COMPLEJO_ESPIGA_ONDA, COMPLEJO_POLIESPIGA_ONDA, PUNTA_ONDA_LENTA, DESCARGA_RITMICA, OTRO`. Ver validación cruzada. | — |
| `eeg_distribucion_anormalidad` | TEXT | — | Catálogo `DistribucionAnormalidad`: `FOCAL, MULTIFOCAL, GENERALIZADA, LATERALIZADA, NO_ESPECIFICADA`. | — |
| `eeg_localizacion` | TEXT | — | — | — |
| `eeg_activacion_sueno` | BOOL | — | — | — |
| `eeg_lentificacion` | TEXT | — | Catálogo `Lentificacion`: `NINGUNA, FOCAL, GENERALIZADA, INTERMITENTE`. | — |
| `eeg_crisis_registradas` | BOOL | — | — | — |
| `eeg_respuesta_fotoestimulacion` | TEXT | — | Catálogo `RespuestaFotoestimulacion`: `NORMAL, RESPUESTA_FOTOPAROXISTICA, SIN_RESPUESTA, NO_PRACTICADA`. | — |
| `eeg_conclusion_texto` | TEXT | — | Ver validación cruzada. | — |
| `eeg_conclusion_categoria` | TEXT | — | Catálogo `ConclusionEeg`: `NORMAL_PARA_LA_EDAD, NORMAL_CON_VARIANTES, ANORMAL_EPILEPTIFORME, ANORMAL_NO_EPILEPTIFORME, ANORMAL_MIXTO, NO_CONCLUYENTE`. Ver validación cruzada. | — |
| `eeg_id_registro_laboratorio` | TEXT | — | — | — |
| `eeg_pdf_ruta` | TEXT | — | — | — |
| `eeg_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
| `eeg_nlp_version` | TEXT | — | — | — |
| `eeg_created_at` | DATETIME | — | — | — |
| `eeg_updated_at` | DATETIME | — | — | — |
| `eeg_con_sueno` | INTEGER | — | 0 o 1. **(análisis del EEG)** | — |
| `eeg_canales` | INTEGER | canales | Entre 1 y 256. **(análisis del EEG)** | — |
| `eeg_duracion_min` | FLOAT | minutos | Mayor que 0. **(análisis del EEG)** | — |
| `eeg_ruido_linea_db` | FLOAT | dB | Mayor o igual que 0: la mediana del ruido de la línea eléctrica en el cuero cabelludo. **(análisis del EEG)** | — |
| `eeg_estudio` | BLOB (LONGBLOB en MySQL) | — | El archivo EDF. | — |
| `eeg_valido` | INTEGER | — | 1 válido, 0 no válido; nulo: sin analizar. **(análisis del EEG)** | — |
| `eeg_nivel` | TEXT | — | Nivel de triaje: `completo`, `sin_referencia_auricular`, `parcial` o `no_analizable`. **(análisis del EEG)** | — |
| `eeg_fraccion_limpia` | FLOAT | fracción | Entre 0 y 1: la parte del registro en ventanas limpias. **(análisis del EEG)** | — |
| `eeg_canales_malos` | INTEGER | canales | Mayor o igual que 0. **(análisis del EEG)** | — |
| `eeg_edad_meses` | FLOAT | meses | La edad a la fecha del estudio con que se compararon las métricas; nula sin fecha de nacimiento. **(análisis del EEG)** | — |
| `eeg_plan_hash` | VARCHAR(16) | — | El plan de preprocesamiento con que se analizó. **(análisis del EEG)** | — |
| `eeg_versiones` | TEXT | — | Las versiones de los módulos del análisis (`nombre=versión;…`). **(análisis del EEG)** | — |
| `eeg_analizado_en` | DATETIME | — | Cuándo se analizó. **(análisis del EEG)** | — |
| `eeg_error` | TEXT | — | Por qué el análisis no terminó; nulo si terminó. **(análisis del EEG)** | — |
**Validaciones cruzadas de `eeg_estudio`:**
- `eeg_fecha_reporte` no puede ser anterior a `eeg_fecha_estudio`.
- `eeg_dias_respuesta` debe ser igual a la diferencia en días entre `eeg_fecha_reporte` y `eeg_fecha_estudio`.
- Si `eeg_actividad_epileptiforme` es falso, `eeg_tipo_grafoelemento` debe quedar vacío o en `NINGUNO`.
- Si `eeg_actividad_epileptiforme` es verdadero, `eeg_anormalidad_presente` debe ser verdadero.
- Si `eeg_sedacion` es falso, `eeg_sedacion_farmaco` debe quedar vacío.
- Si `eeg_reporte_disponible` es verdadero, `eeg_conclusion_texto` no puede quedar vacío.
- Si `eeg_conclusion_categoria` es `NORMAL_PARA_LA_EDAD` o `NORMAL_CON_VARIANTES`, entonces `eeg_anormalidad_presente` debe ser falso.
Un EEG es válido cuando el análisis lo dice (`eeg_valido` = 1): ninguna regla decisiva de `eeg_criterio` fuera de su
umbral y el registro dentro de las condiciones del plan de preprocesamiento. Uno no válido no tiene resultado y sus
alteraciones no cuentan.
---
## 7. Tabla `antecedentes_maternos_gestacion`
## 7. Tabla `eeg_criterio` **(análisis del EEG)**
Un renglón por cada regla de calidad que el análisis evaluó sobre un EEG: las del estudio completo y, para cada canal
malo, el motivo con su electrodo.
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `amg_id` | VARCHAR(36), llave primaria | — | — | — |
| `amg_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
| `amg_id_madre_seudonimo` | TEXT | — | Ver validación cruzada. | — |
| `amg_fuente_antecedente` | TEXT | — | Catálogo `FuenteAntecedenteMaterno`: `EXPEDIENTE_MATERNO, INTERROGATORIO_NM11, AMBAS, NO_LOCALIZADO`. Ver validación cruzada. | — |
| `amg_flag_vinculo_verificado` | BOOL | — | — | — |
| `amg_imc_pregestacional` | FLOAT | kg/m² | Entre 12.0 y 70.0. Ver validación cruzada. | — |
| `amg_categoria_peso_materno` | TEXT | — | Catálogo `CategoriaPesoMaterno`: `BAJO_PESO, NORMAL, SOBREPESO, OBESIDAD_I, OBESIDAD_II, OBESIDAD_III, NO_REGISTRADA`. Ver validación cruzada. | — |
| `amg_tabaquismo_gestacion` | BOOL | — | — | — |
| `amg_acido_folico_preconcepcional` | BOOL | — | — | — |
| `amg_intervalo_intergenesico_meses` | INTEGER | meses | Entre 0 y 360. | — |
| `amg_antecedente_aborto` | BOOL | — | — | — |
| `amg_embarazo_multiple` | TEXT | — | Catálogo `TipoEmbarazo`: `UNICO, GEMELAR, TRIPLE_O_MAS, NO_REGISTRADO`. | — |
| `amg_infeccion_gestacion` | BOOL | — | Ver validación cruzada. | — |
| `amg_infeccion_tipo` | TEXT | — | Ver validación cruzada. | — |
| `amg_infeccion_hospitalizacion` | BOOL | — | Ver validación cruzada. | — |
| `amg_diabetes_gestacional` | BOOL | — | — | — |
| `amg_hipertension_preeclampsia` | TEXT | — | Catálogo `TrastornoHipertensivoGestacion`: `NINGUNO, HIPERTENSION_GESTACIONAL, PREECLAMPSIA, ECLAMPSIA, SINDROME_HELLP, NO_REGISTRADO`. | — |
| `amg_hipotiroidismo` | BOOL | — | — | — |
| `amg_hipertiroidismo` | BOOL | — | — | — |
| `amg_incompatibilidad_rh` | BOOL | — | — | — |
| `amg_crisis_convulsivas` | BOOL | — | — | — |
| `amg_proceso_proinflamatorio` | BOOL | — | — | — |
| `amg_enfermedad_autoinmune` | BOOL | — | — | — |
| `amg_migrana` | BOOL | — | — | — |
| `amg_asma` | BOOL | — | — | — |
| `amg_hipoxia_materna` | BOOL | — | — | — |
| `amg_estres_agudo` | BOOL | — | — | — |
| `amg_trastorno_neurologico` | BOOL | — | — | — |
| `amg_liquido_amniotico` | TEXT | — | Catálogo `VolumenLiquidoAmniotico`: `NORMAL, OLIGOHIDRAMNIOS, POLIHIDRAMNIOS, NO_REGISTRADO`. | — |
| `amg_medicamentos_gestacion` | TEXT | — | Ver validación cruzada. | — |
| `amg_farmaco_riesgo_neurodesarrollo` | BOOL | — | Ver validación cruzada. | — |
| `amg_observaciones` | TEXT | — | — | — |
| `amg_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
| `amg_nlp_version` | TEXT | — | — | — |
| `amg_created_at` | DATETIME | — | — | — |
| `amg_updated_at` | DATETIME | — | — | — |
| `amg_fuente_sistema` | TEXT | — | — | — |
**Validaciones cruzadas de `antecedentes_maternos_gestacion`:**
- Si `amg_fuente_antecedente` es `EXPEDIENTE_MATERNO` o `AMBAS`, `amg_id_madre_seudonimo` debe estar presente.
- `amg_categoria_peso_materno` debe corresponder al valor de `amg_imc_pregestacional` (Anexo A).
- Si `amg_infeccion_gestacion` es falso, `amg_infeccion_tipo` debe quedar vacío y `amg_infeccion_hospitalizacion` debe ser falso o vacío.
- Si `amg_farmaco_riesgo_neurodesarrollo` es verdadero, `amg_medicamentos_gestacion` no puede quedar vacío.
| `cri_id` | VARCHAR(36), llave primaria | — | — | — |
| `cri_eeg_id` | VARCHAR(36), indexado | — | — | → `eeg.eeg_id` |
| `cri_codigo` | TEXT | — | Catálogo `CriterioEeg`: del estudio `file, clean-windows, internal-coverage, bad-scalp-triage, usable-scalp, triage-level, line-noise`; de un canal `dead-channel, frozen, saturated, inf-values, own-gaps, bridge, amplitude, aux-amplitude, does-not-correlate, intermittent-contact, intermittent-bursts`. | — |
| `cri_electrodo` | TEXT | — | El canal del motivo; nulo en las reglas del estudio. | — |
| `cri_valor` | FLOAT | `cri_unidad` | El valor medido, si es un número. | — |
| `cri_valor_texto` | TEXT | — | El valor o el motivo, si es un texto (por ejemplo, el nivel de triaje). | — |
| `cri_unidad` | TEXT | — | `%`, `fraction`, `electrodes` o `dB`. | — |
| `cri_bajo` | FLOAT | `cri_unidad` | Fuera de rango por debajo de este valor. | — |
| `cri_alto` | FLOAT | `cri_unidad` | Fuera de rango por encima de este valor. | — |
| `cri_decisivo` | INTEGER | — | 0 o 1: la regla basta, por sí sola, para que el EEG no sea válido. | — |
| `cri_anormal` | INTEGER | — | 0 o 1. | — |
---
## 8. Tabla `parto_neonatal`
## 8. Tabla `eeg_metrica` **(análisis del EEG)**
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `pnn_id` | VARCHAR(36), llave primaria | — | — | — |
| `pnn_pac_id` | TEXT | — | — | → `pacientes.pac_id` |
| `pnn_fuente_antecedente` | TEXT | — | Catálogo `FuenteAntecedenteNeonatal`: `NOTA_RECIEN_NACIDO, NOTA_RESOLUCION_OBSTETRICA, INTERROGATORIO_NM11, AMBAS, NO_LOCALIZADA`. | — |
| `pnn_tipo_parto` | TEXT | — | Catálogo `TipoParto`: `VAGINAL_ESPONTANEO, VAGINAL_INSTRUMENTADO, CESAREA_ELECTIVA, CESAREA_URGENCIA, NO_REGISTRADO`. | — |
| `pnn_complicaciones_intraparto` | BOOL | — | Ver validación cruzada. | — |
| `pnn_complicacion_tipo` | TEXT | — | Catálogo `ComplicacionIntraparto`: `NINGUNA, HIPOXIA, ISQUEMIA, TRAUMA_OBSTETRICO, CIRCULAR_DE_CORDON, SUFRIMIENTO_FETAL_AGUDO, OTRA`. Ver validación cruzada. | — |
| `pnn_peso_nacer_g` | INTEGER | g | Entre 400 y 6000. | — |
| `pnn_talla_nacer_cm` | FLOAT | cm | Entre 25.0 y 60.0. | — |
| `pnn_perimetro_cefalico_nacer_cm` | FLOAT | cm | Entre 25.0 y 42.0. | — |
| `pnn_edad_gestacional_sem` | FLOAT | semanas | Entre 22.0 y 43.0. | — |
| `pnn_clasificacion_eg` | TEXT | — | Catálogo `ClasificacionEdadGestacional`: `PRETERMINO_EXTREMO, MUY_PRETERMINO, PRETERMINO_TARDIO, TERMINO, POSTERMINO, NO_DETERMINADA`. Ver validación cruzada. | — |
| `pnn_tamano_para_eg` | TEXT | — | Catálogo `TamanoParaEdadGestacional`: `PEQUENO, ADECUADO, GRANDE, NO_DETERMINADO`. | — |
| `pnn_peso_nacer_zscore` | FLOAT | — | Entre -5.0 y 5.0. | — |
| `pnn_apgar_1min` | INTEGER | — | Entre 0 y 10. Ver validación cruzada. | — |
| `pnn_apgar_5min` | INTEGER | — | Entre 0 y 10. Ver validación cruzada. | — |
| `pnn_ingreso_ucin` | BOOL | — | Ver validación cruzada. | — |
| `pnn_dias_ucin` | INTEGER | días | Entre 0 y 365. Ver validación cruzada. | — |
| `pnn_encefalopatia_hipoxico_isquemica` | BOOL | — | — | — |
| `pnn_hipotermia_nacer` | BOOL | — | — | — |
| `pnn_hiperbilirrubinemia` | BOOL | — | Ver validación cruzada. | — |
| `pnn_fototerapia` | BOOL | — | Ver validación cruzada. | — |
| `pnn_hipoglucemia_neonatal` | BOOL | — | — | — |
| `pnn_anoxia` | BOOL | — | — | — |
| `pnn_sindrome_congenito` | BOOL | — | Ver validación cruzada. | — |
| `pnn_sindrome_congenito_desc` | TEXT | — | Ver validación cruzada. | — |
| `pnn_flag_riesgo_neonatal` | BOOL | — | Ver validación cruzada. | — |
| `pnn_observaciones` | TEXT | — | — | — |
| `pnn_ocr_confianza` | FLOAT | — | Entre 0.0 y 1.0. | — |
| `pnn_nlp_version` | TEXT | — | — | — |
| `pnn_created_at` | DATETIME | — | — | — |
| `pnn_updated_at` | DATETIME | — | — | — |
| `pnn_fuente_sistema` | TEXT | — | — | — |
**Validaciones cruzadas de `parto_neonatal`:**
- `pnn_clasificacion_eg` debe corresponder a `pnn_edad_gestacional_sem` (Anexo A).
- `pnn_apgar_5min` no puede ser menor que `pnn_apgar_1min`.
- Si `pnn_dias_ucin` es mayor que 0, `pnn_ingreso_ucin` debe ser verdadero.
- Si `pnn_fototerapia` es verdadero, `pnn_hiperbilirrubinemia` debe ser verdadero.
- Si `pnn_complicaciones_intraparto` es falso, `pnn_complicacion_tipo` debe quedar vacío o en `NINGUNA`.
- Si `pnn_sindrome_congenito` es falso, `pnn_sindrome_congenito_desc` debe quedar vacío.
- `pnn_flag_riesgo_neonatal` debe ser verdadero si se cumple al menos una de estas cuatro condiciones: `pnn_apgar_5min < 7`, `pnn_ingreso_ucin` verdadero, `pnn_encefalopatia_hipoxico_isquemica` verdadero, o `pnn_anoxia` verdadero. Si no se cumple ninguna, debe ser falso.
| `met_id` | VARCHAR(36), llave primaria | — | — | — |
| `met_eeg_id` | TEXT | — | — | → `eeg.eeg_id` |
| `met_codigo` | TEXT | — | Catálogo `MetricaEeg`: `RITMO_POSTERIOR, HUSOS_SUENO_N2, HUSOS_SUENO_N3, PICOS_PAROXISTICOS, GRADIENTE_ANTEROPOSTERIOR`. | — |
| `met_valor` | FLOAT | la de la métrica | Nulo: la métrica no se puede evaluar (por ejemplo, husos sin registro de sueño). | — |
| `met_z` | FLOAT | puntaje z | Contra la curva de referencia de la métrica a `eeg_edad_meses`; nulo si la edad no está cubierta. | — |
| `met_fuera` | INTEGER | — | -1 debajo del percentil 5, 0 dentro, +1 arriba del percentil 95. | — |
| `met_p5` | FLOAT | la de la métrica | El percentil 5 de la curva a esa edad. | — |
| `met_mediana` | FLOAT | la de la métrica | La mediana de la curva a esa edad. | — |
| `met_p95` | FLOAT | la de la métrica | El percentil 95 de la curva a esa edad. | — |
| `met_modelo` | TEXT | — | La versión registrada de la curva de referencia. | — |
---
## Anexo A — Funciones de referencia usadas en varias validaciones cruzadas
## 9. Tabla `eeg_metrica_electrodo` **(análisis del EEG)**
**Ventana madurativa según edad en meses** (usada en `ordenes_estudio`, `nota_medica`, `evaluacion_psicologica`):
| Edad en meses | Ventana |
|---|---|
| 16.0 a 23.9 | `V1_16_23` |
| 24.0 a 30.9 | `V2_24_30` |
| 31.0 a 36.0 | `V3_31_36` |
| Cualquier otro valor | `FUERA_DE_RANGO` |
**Categoría de peso materno según IMC pregestacional** (usada en `antecedentes_maternos_gestacion`, clasificación estándar de adultos de la OMS):
| IMC (kg/m²) | Categoría |
|---|---|
| Menor a 18.5 | `BAJO_PESO` |
| 18.5 a 24.9 | `NORMAL` |
| 25.0 a 29.9 | `SOBREPESO` |
| 30.0 a 34.9 | `OBESIDAD_I` |
| 35.0 a 39.9 | `OBESIDAD_II` |
| 40.0 o más | `OBESIDAD_III` |
**Clasificación por edad gestacional al nacer** (usada en `parto_neonatal`):
| Semanas de gestación | Clasificación |
|---|---|
| Menos de 28.0 | `PRETERMINO_EXTREMO` |
| 28.0 a 31.9 | `MUY_PRETERMINO` |
| 32.0 a 36.9 | `PRETERMINO_TARDIO` |
| 37.0 a 41.9 | `TERMINO` |
| 42.0 o más | `POSTERMINO` |
---
## Anexo B — Validación de los códigos del ADOS-2 (`evaluacion_psicologica`)
El campo `psi_ados2_modulo` fija qué módulo del ADOS-2 se aplicó al paciente. Cada
módulo usa un subconjunto distinto de códigos, dentro de los dos dominios que ya
existen como columnas agregadas: `SA` (Interacción social recíproca / comunicación) y
`RRB` (Conductas restringidas y repetitivas). Equivalencia entre el catálogo
`ModuloAdos2` y los módulos del manual: `TODDLER` = Módulo T, `MODULO_1` = Módulo 1,
`MODULO_2` = Módulo 2.
### B.1 Rango válido de cada código, por módulo
| Código | Dominio | Módulo T | Módulo 1 | Módulo 2 |
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| a2 | SA | 0–3 | 0–3 | — |
| a6 | SA | — | — | 0–3 |
| a7 | SA | 0–3 | 0–3 | 0–3, 8 |
| a8 | SA | 0–3, 8 | 0–2, 8 | — |
| b1 | SA | 0–3 | 0, 2 | 0, 2 |
| b2 | SA | — | — | 0–2 |
| b3 | SA | — | 0–2 | 0–3 |
| b4 | SA | 0–3 | 0–3 | — |
| b5 | SA | 0–3 | 0–3 | 0–2 |
| b6 | SA | 0–3 | — | 0–2 |
| b7 | SA | 0–3 | — | — |
| b8 | SA | 0–3 | — | 0–3 |
| b9 | SA | 0–3 | 0–2 | — |
| b10 | SA | — | 0–2 | — |
| b11 | SA | — | 0–3 | 0–3 |
| b12 | SA | 0–3 | 0–3 | 0–3 |
| b13 | SA | 0–3 | — | — |
| b14 | SA | 0–3 | — | — |
| b15 | SA | 0–3 | — | — |
| b16b | SA | 0–3, 7, 8 | — | — |
| b18 | SA | 0–3 | — | — |
| a3 | RRB | 0–3, 8 | 0–2, 8 | — |
| a4 | RRB | — | — | 0–3 |
| a5 | RRB | — | 0–3, 8 | — |
| d1 | RRB | 0–3 | 0–3 | 0–3 |
| d2 | RRB | 0–3 | 0–3 | 0–3 |
| d4 | RRB | — | 0–3 | 0–3 |
| d5 | RRB | 0–3 | — | — |
Nota de lectura: "0–3, 8" significa que, además de los valores enteros 0 a 3, el
manual permite el código adicional 8 en ese ítem y módulo. Una celda con "—" quiere
decir que ese código no existe para ese módulo (ver regla de pertenencia, B.3).
**Validación de rango por código:** si la columna correspondiente al código no está
vacía, su valor debe ser un entero dentro del conjunto permitido para el módulo
indicado en `psi_ados2_modulo`. Cualquier valor fuera del conjunto (incluido un
entero "razonable" pero no listado, como un 4 donde el máximo es 3) se rechaza.
### B.2 Validación de completitud del módulo
Todos los códigos que pertenecen al módulo indicado en `psi_ados2_modulo` (columna
correspondiente en la tabla de B.1) deben tener un valor, es decir, no pueden quedar
vacíos. Si al menos uno de los códigos propios del módulo está vacío, el renglón se
considera incompleto y se rechaza.
Ejemplo: si `psi_ados2_modulo = MODULO_1`, deben estar llenas las columnas
`psi_ados2_sa_a2, sa_a7, sa_a8, sa_b1, sa_b3, sa_b4, sa_b5, sa_b9, sa_b10, sa_b11,
sa_b12, rrb_a3, rrb_a5, rrb_d1, rrb_d2, rrb_d4`.
### B.3 Validación de pertenencia a módulo
Los códigos que **no** pertenecen al módulo indicado (celda "—" en B.1 para ese
módulo) deben quedar vacíos. Si alguno de esos códigos trae un valor, el renglón se
rechaza, porque ese código no corresponde a la versión de la prueba aplicada.
Ejemplo: si `psi_ados2_modulo = TODDLER`, las columnas `psi_ados2_sa_b2,
sa_b3, sa_b10, sa_b11, rrb_a4, rrb_a5, rrb_d4` (propias de otros módulos) deben
quedar vacías.
| `mel_id` | VARCHAR(36), llave primaria | — | — | — |
| `mel_met_id` | TEXT | — | — | → `eeg_metrica.met_id` |
| `mel_electrodo` | TEXT | — | Un electrodo del sistema 10-20 (`Fp1` … `O2`). | — |
| `mel_valor` | FLOAT | la de la métrica | — | — |
| `mel_z` | FLOAT | puntaje z | Contra la curva de referencia del electrodo a `eeg_edad_meses`. | — |
---
## Anexo C — Llaves foráneas (resumen)
## 10. Tabla `eeg_metrica_zona` **(análisis del EEG)**
| Columna | Tabla y columna referenciada |
|---|---|
| `ordenes_estudio.ord_pac_id` | `pacientes.pac_id` |
| `ordenes_estudio.ord_nota_medica_id` | `nota_medica.nm_id` |
| `nota_medica.nm_pac_id` | `pacientes.pac_id` |
| `nota_medica.nm_nota_previa_id` | `nota_medica.nm_id` (autorreferencia) |
| `evaluacion_psicologica.psi_ord_id` | `ordenes_estudio.ord_id` |
| `evaluacion_psicologica.psi_pac_id` | `pacientes.pac_id` |
| `potenciales_evocados_auditivos.pea_ord_id` | `ordenes_estudio.ord_id` |
| `potenciales_evocados_auditivos.pea_pac_id` | `pacientes.pac_id` |
| `eeg_estudio.eeg_ord_id` | `ordenes_estudio.ord_id` |
| `eeg_estudio.eeg_pac_id` | `pacientes.pac_id` |
| `antecedentes_maternos_gestacion.amg_pac_id` | `pacientes.pac_id` |
| `parto_neonatal.pnn_pac_id` | `pacientes.pac_id` |
El valor de una métrica en una zona del cuero cabelludo y su z contra la curva de referencia de esa zona. Las zonas
son las de la biblioteca `tea` (`tea.contracts.ZONES`): `frontal_izq` (Fp1, F3, F7), `frontal_der` (Fp2, F4, F8),
`frontal_media` (Fz), `central` (C3, Cz, C4), `parietal` (P3, Pz, P4), `temporal_izq` (T3, T5), `temporal_der`
(T4, T6) y `occipital` (O1, O2). Es lo que lee el modelo de asociación con el ADOS-2.
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `mez_id` | VARCHAR(36), llave primaria | — | — | — |
| `mez_met_id` | TEXT | — | — | → `eeg_metrica.met_id` |
| `mez_zona` | VARCHAR(32) | — | El código de la zona. | — |
| `mez_valor` | FLOAT | la de la métrica por electrodo de la zona | — | — |
| `mez_z` | FLOAT | puntaje z | Contra la curva de referencia de la zona a `eeg_edad_meses`. | — |
---
## 11. Tabla `relacion_ados2`
Un renglón por versión del modelo y asociación: la razón de momios, en la cohorte, de una alteración del EEG en una
zona del cuero cabelludo contra el desenlace de un reactivo o dominio del ADOS-2. La llave natural
(`rel_version`, `rel_biomarcador`, `rel_zona`, `rel_resultado`) es única: es con la que la API de importación y la
biblioteca `tea` unen renglones al cargar una versión del modelo.
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `rel_id` | VARCHAR(36), llave primaria | — | — | — |
| `rel_version` | VARCHAR(32), indexado | — | La versión del modelo ajustado. | — |
| `rel_nivel` | TEXT | — | Catálogo `NivelRelacionAdos2`: `item, dominio`. El nivel del modelo. | — |
| `rel_validado` | INTEGER | — | 0 o 1: validado por el experto de dominio. | — |
| `rel_n_cohorte` | INTEGER | pacientes | Mayor que 0: el tamaño de la cohorte con que se ajustó el modelo. | — |
| `rel_biomarcador` | VARCHAR(32) | — | Catálogo `MetricaEeg`: la métrica del EEG asociada. | — |
| `rel_zona` | VARCHAR(32) | — | El código de la zona del cuero cabelludo, el de la biblioteca `tea` (los de `eeg_metrica_zona`), `posterior` para el ritmo posterior o `global` para el gradiente. | — |
| `rel_tipo` | TEXT | — | Catálogo `NivelRelacionAdos2`: `item, dominio`. El nivel que relaciona esta asociación. | — |
| `rel_resultado` | VARCHAR(32) | — | Un reactivo del ADOS-2 por lo que mide, el mismo en todos los módulos (`ados2_item_01` … `ados2_item_22`, `ADOS2_ITEM_MEANINGS`: un mismo código de reactivo es otro reactivo en otro módulo), o `CSS`, el puntaje de severidad calibrado total. | — |
| `rel_evento` | TEXT | — | El evento de desenlace como umbral legible por máquina sobre el puntaje del desenlace: `>=1` (el puntaje de algoritmo del reactivo en el módulo del niño) o `>=8` (el CSS). | — |
| `rel_or` | FLOAT | razón de momios | Mayor que 0. | — |
| `rel_ic_inf` | FLOAT | razón de momios | El límite inferior del intervalo de confianza; menor o igual que `rel_ic_sup`. | — |
| `rel_ic_sup` | FLOAT | razón de momios | El límite superior del intervalo de confianza. | — |
| `rel_q` | FLOAT | — | Entre 0 y 1: el valor q del ajuste por comparaciones múltiples. | — |
---
## 12. Tabla `relacion_ados2_paciente`
Un renglón por EEG y renglón del modelo: el z del paciente para la asociación y la probabilidad que el modelo le
asigna. La pareja (`rap_rel_id`, `rap_eeg_id`) es única. El desenlace observado no se guarda: se lee del ADOS-2 del
paciente (`ados2`).
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `rap_id` | VARCHAR(36), llave primaria | — | — | — |
| `rap_rel_id` | VARCHAR(36), indexado | — | — | → `relacion_ados2.rel_id` |
| `rap_eeg_id` | VARCHAR(36), indexado | — | — | → `eeg.eeg_id` |
| `rap_valor_z` | FLOAT | puntaje z | El z del paciente en la asociación. | — |
| `rap_probabilidad` | FLOAT | probabilidad | Entre 0 y 1: la probabilidad que da el modelo. | — |
| `rap_probabilidad_referencia` | FLOAT | probabilidad | Entre 0 y 1: la probabilidad de referencia. | — |
+108
View File
@@ -0,0 +1,108 @@
"""Portability tests for core.indicadores.fechas.
Checks the compiled SQL text for every supported dialect (no live
connection needed) plus live execution against SQLite always, and MySQL
when MYSQL_TEST_URL is set (see WebApi/tests/test_connectors_mysql.py for
the same convention).
"""
import os
from datetime import date
import pytest
import sqlalchemy as sa
from core.indicadores.fechas import dias_entre, edad_meses, meses_cumplidos, redondear
MYSQL_TEST_URL = os.environ.get("MYSQL_TEST_URL")
def _compiled(expr, dialect_name):
from sqlalchemy.dialects import mssql, mysql, postgresql, sqlite
dialects = {
"sqlite": sqlite.dialect(),
"postgresql": postgresql.dialect(),
"mysql": mysql.dialect(),
"mariadb": mysql.dialect(),
"mssql": mssql.dialect(),
}
return str(expr.compile(dialect=dialects[dialect_name], compile_kwargs={"literal_binds": True}))
def test_dias_entre_neutral_default_is_not_executable():
from sqlalchemy.dialects import oracle
compiled = str(
dias_entre(date(2026, 1, 1), date(2026, 3, 1)).compile(
dialect=oracle.dialect(), compile_kwargs={"literal_binds": True}
)
)
assert compiled.startswith("dias_entre(")
@pytest.mark.parametrize(
"dialect_name,expected",
[
("sqlite", "CAST(julianday('2026-03-01') - julianday('2026-01-01') AS INTEGER)"),
("postgresql", "(CAST('2026-03-01' AS DATE) - CAST('2026-01-01' AS DATE))"),
("mysql", "DATEDIFF('2026-03-01', '2026-01-01')"),
("mariadb", "DATEDIFF('2026-03-01', '2026-01-01')"),
("mssql", "DATEDIFF(day, '2026-01-01', '2026-03-01')"),
],
)
def test_dias_entre_compiles_per_dialect(dialect_name, expected):
expr = dias_entre(date(2026, 1, 1), date(2026, 3, 1))
assert _compiled(expr, dialect_name) == expected
@pytest.mark.parametrize(
"dialect_name,expected",
[
("sqlite", "ROUND(5.555, 1)"),
("mysql", "ROUND(5.555, 1)"),
("mariadb", "ROUND(5.555, 1)"),
("mssql", "ROUND(5.555, 1)"),
("postgresql", "CAST(ROUND(CAST(5.555 AS NUMERIC), 1) AS DOUBLE PRECISION)"),
],
)
def test_redondear_compiles_per_dialect(dialect_name, expected):
expr = redondear(5.555, 1)
assert _compiled(expr, dialect_name) == expected
def test_dias_entre_executes_on_sqlite():
engine = sa.create_engine("sqlite://")
with engine.connect() as conn:
result = conn.execute(sa.select(dias_entre(sa.literal(date(2026, 1, 1)), sa.literal(date(2026, 3, 1))))).scalar()
assert result == 59 # Jan (31) + Feb (28) in 2026, a non-leap year
def test_edad_meses_and_meses_cumplidos_on_sqlite():
engine = sa.create_engine("sqlite://")
nacimiento = date(2024, 1, 1)
fecha = date(2026, 1, 17) # 2 years and 16 days old
with engine.connect() as conn:
edad = conn.execute(sa.select(edad_meses(sa.literal(nacimiento), sa.literal(fecha), 30.44))).scalar()
cumplidos = conn.execute(sa.select(meses_cumplidos(sa.literal(edad)))).scalar()
dias = (fecha - nacimiento).days
assert edad == round(dias / 30.44, 1)
assert cumplidos == int(edad // 1)
@pytest.mark.skipif(not MYSQL_TEST_URL, reason="MYSQL_TEST_URL not set — no real MySQL server to test against")
def test_dias_entre_executes_on_real_mysql():
engine = sa.create_engine(MYSQL_TEST_URL)
with engine.connect() as conn:
result = conn.execute(sa.select(dias_entre(sa.literal(date(2026, 1, 1)), sa.literal(date(2026, 3, 1))))).scalar()
assert result == 59
@pytest.mark.skipif(not MYSQL_TEST_URL, reason="MYSQL_TEST_URL not set — no real MySQL server to test against")
def test_edad_meses_executes_on_real_mysql():
engine = sa.create_engine(MYSQL_TEST_URL)
nacimiento = date(2024, 1, 1)
fecha = date(2026, 1, 17)
with engine.connect() as conn:
edad = conn.execute(sa.select(edad_meses(sa.literal(nacimiento), sa.literal(fecha), 30.44))).scalar()
dias = (fecha - nacimiento).days
assert float(edad) == round(dias / 30.44, 1)
+102 -8
View File
@@ -3,32 +3,100 @@ own isolated metadata (no cross-domain table-name collisions)."""
from core.cacu.base import CaCuModel
from core.cama.base import CaMaModel
from core.tea.base import TeaModel
from core.governance.base import GovernanceModel
from core.cacu import models as cacu_models
from core.cacu.indicadores import models as cacu_indicadores_models
from core.cama import models as cama_models
from core.cama.indicadores import models as cama_indicadores_models
from core.tea import models as tea_models
from core.tea.indicadores import models as tea_indicadores_models
from core.governance import models as governance_models
INDICADORES_KIT_CDM = {
"persona",
"periodo_observacion",
"carga",
"def_parametro",
"dim_periodo",
"dim_fecha",
"dim_grupo_edad",
"cat_estudio",
"cat_resultado",
"cat_valor",
"cat_sistema_fuente",
"cat_mapeo",
"procedimiento",
"observacion_clinica",
"cat_measure",
"cat_measure_resultado",
"cat_measure_valor",
"cat_measure_grupo",
"cat_estrato",
"cat_estrato_valor",
"cat_measure_estrato",
"measure_report",
"measure_report_unidad",
"measure_report_unidad_estrato",
"cohorte_armado",
"cohorte_miembro",
"cohorte_exclusion",
"cohorte_variable",
"evaluacion_riesgo_lote",
"evaluacion_riesgo",
}
def test_cacu_tables_registered():
"""Staging (hospital-shaped) and indicadores_kit CDM tables share
CaCuModel's registry (same database, per the kit's ADR-004)."""
names = set(CaCuModel.metadata.tables.keys())
assert names == {"paciente", "ordenesestudio", "citologiacervical", "biopsiacervical", "notamedica", "biometriahematica"}
assert names == {
"paciente", "ordenesestudio", "citologiacervical", "biopsiacervical",
"notamedica", "biometriahematica", "episodioclinico",
*INDICADORES_KIT_CDM,
}
def test_cama_tables_registered():
"""Staging (hospital-shaped) and indicadores_kit CDM tables share
CaMaModel's registry (same database, per the kit's ADR-004)."""
names = set(CaMaModel.metadata.tables.keys())
assert names == {"paciente", "ordenesestudio", "mastografia", "biopsiamama", "notamedica", "biometriahematica"}
assert names == {
"paciente", "ordenesestudio", "mastografia", "biopsiamama",
"notamedica", "biometriahematica", "episodioclinico",
*INDICADORES_KIT_CDM,
}
def test_tea_tables_registered():
"""Staging (hospital-shaped) and indicadores_kit CDM tables share
TeaModel's registry (same database, per the kit's ADR-004), so both
module's tables are asserted together."""
names = set(TeaModel.metadata.tables.keys())
assert names == {
# Staging: fed by the hospital source via the import pipeline.
"pacientes",
"ordenes_estudio",
"nota_medica",
"evaluacion_psicologica",
"potenciales_evocados_auditivos",
"eeg_estudio",
"antecedentes_maternos_gestacion",
"parto_neonatal",
"mchat",
"ados2",
"evaluacion_neuropediatrica",
"eeg",
"eeg_metrica",
"eeg_metrica_electrodo",
"eeg_metrica_zona",
"eeg_criterio",
"relacion_ados2",
"relacion_ados2_paciente",
# indicadores_kit CDM, built from staging by the webapi.orquestacion graph.
*INDICADORES_KIT_CDM,
}
def test_governance_tables_registered():
names = set(GovernanceModel.metadata.tables.keys())
assert names == {
"extractionrun",
"modelprediction",
}
@@ -36,3 +104,29 @@ def test_domains_do_not_share_metadata():
assert CaCuModel.metadata is not CaMaModel.metadata
assert CaCuModel.metadata is not TeaModel.metadata
assert CaMaModel.metadata is not TeaModel.metadata
assert CaCuModel.metadata is not GovernanceModel.metadata
assert CaMaModel.metadata is not GovernanceModel.metadata
assert TeaModel.metadata is not GovernanceModel.metadata
def test_cat_mapeo_keeps_its_rules_in_the_schema():
"""Pins down: a mapping row needs a known class with the target that class needs, a value of the catalog, and
one row per form and start date; `cat_sistema_fuente` keeps its dates in order. Fails if a constraint is
dropped from `reglas_de_mapeo` or `vigencia_ordenada`, which every engine relies on."""
from core.cama.indicadores.models import CatMapeo, CatSistemaFuente
names = {c.name for c in CatMapeo.__table__.constraints}
assert {"ck_cat_mapeo_clase", "ck_cat_mapeo_destino", "ck_cat_mapeo_vigencia", "fk_cat_mapeo_valor",
"uq_cat_mapeo"} <= names
assert "ck_cat_sistema_fuente_vigencia" in {c.name for c in CatSistemaFuente.__table__.constraints}
def test_relacion_ados2_keeps_its_natural_keys_in_the_schema():
"""Pins down: the import merge and the `tea` library upsert one `relacion_ados2` row per
(rel_version, rel_biomarcador, rel_zona, rel_resultado), and one `relacion_ados2_paciente` row per
(rap_rel_id, rap_eeg_id). Fails if either unique constraint is dropped, which would let two imports of
the same model row or two probabilities for the same EEG and association both land."""
from core.tea.models import RelacionAdos2, RelacionAdos2Paciente
assert "uq_relacion_ados2" in {c.name for c in RelacionAdos2.__table__.constraints}
assert "uq_relacion_ados2_paciente" in {c.name for c in RelacionAdos2Paciente.__table__.constraints}
+8
View File
@@ -0,0 +1,8 @@
__pycache__/
*.pyc
.venv/
.pytest_cache/
.coverage
*.egg-info/
.env
uv.lock
+88
View File
@@ -0,0 +1,88 @@
# Extraction
Reads clinical documents (PDF with or without a text layer, images, plain text) and EEG files, and turns the
documents into records of the fields an import target has (VAR-01..03, VARM-01..04a). It has no dependency on the
rest of the platform: WebApi gives it the fields to look for and stores what it finds.
## From pages to values
| Step | Module | What it does |
|---|---|---|
| Reading | `readers/` | Text layer with word positions (`pdfplumber`), Tesseract OCR on pages without one, embedded images located. |
| Records | `segmentation.py`, `records.py` | Pages split into records (by patient key, by page count, whole document) and records of the same key merged; the most confident value wins and confident disagreements are kept as conflicts. |
| Letterhead | `template.py` | Margin lines that repeat across different patients' documents are the issuer's, and fill nothing. |
| Candidates | `nlp/extractors.py` | Every reading of every field, each with how it was found (`ExtractedValue.features`): `LabeledValueExtractor` (caption and value, in columns too), `PatternExtractor` (values with a known shape), `FreeTextMentionExtractor` (catalog terms in prose), `MeasurementExtractor` (a number with its unit after its concept). |
| Score tables | `nlp/score_tables.py` | Finds the ADOS-2 table, infers its variant from the item captions, and reads the positioned scores. |
| Context | `nlp/context.py` | Whether the report affirms, denies, supposes, quotes from history or from the clinical request each mention (ConText and NegEx), and which section it sits in. |
| Choice | `nlp/ranking.py` | One value per field: the most confident (`HeuristicRanker`) or a ranker learned from corrections (`LearnedRanker`). |
| Measurement | `nlp/evaluation.py` | Precision, recall and F1 per field against an answer key. |
Everything a field is looked for with lives in `nlp/vocabulary.py`: captions (`LABELS`), catalog terms as reports
write them (`CLINICAL_TERMS`), the concepts a generic answer must follow (`ANCHORS`), severity orders (`SEVERITY`),
what a denied mention means for a presence field (`NEGATED_VALUES`), units (`UNITS`), what each kind of report is
about (`SUBJECTS`), section headings and trigger phrases. A report format with a caption or a term the extractor
doesn't know is fixed there, without code changes.
Score-table layouts live in `SCORE_TABLES` in `nlp/vocabulary.py`. The extractor uses headings and item coverage
to locate the table, including a restricted-behavior block continued on the next page. Item captions determine
the module. Printed totals and the stated module are confidence checks. Ambiguous item sets leave the fields
empty and expose `modulo_ambiguo` on the extracted record.
## What the rules do
- **Assertions.** A mention preceded, within its clause, by a negation ("sin", "negativo para"), a hypothetical
("en caso de", "un resultado"), a historical ("antecedente de") or an uncertainty trigger ("probable") is qualified
accordingly. A form answer after it (`Carcinoma invasor: NO`) denies it, and a caption whose answer is elsewhere
asserts nothing. Negated mentions fill nothing, except a presence field's `negated_value` ("sin actividad
epileptiforme" is 0). Hypothetical ones fill nothing without a trained ranker.
- **Sections.** A heading alone on its line opens a section until the next one: clinical data (what was suspected,
presumed), history, description, result, and reference text (interpretation guides, reference intervals,
methods), whose mentions describe no patient. A caption with its content on the same line qualifies only that line.
- **Generic answers.** "POSITIVO", "NO", "NORMAL" in prose only count after their concept (`ANCHORS` or the field's
captions), so a form's other positives don't fill the HPV result.
- **Severity.** When a report affirms several values of an ordered field (one per specimen, one per breast), the most
severe is the finding.
- **Subject.** A record whose pages name another kind of study (`SUBJECTS` of the other targets) and not the
target's fills nothing, and is flagged in the review. A record that names no study at all is not judged.
- **OCR look-alikes.** On OCR pages, captions and terms also match with commonly confused characters collapsed
(`ocr_fold`: `l`/`I`/`!`, `0`/`O` inside words...), at a slightly lower confidence.
## The learned ranker
`LearnedRanker` is a logistic regression over the candidates' features: method, assertion, section, label score,
how many candidates agree, whether the document is on topic, crossed with the field and the method. It never sees
the document's words, so its weights can be read and shared. It learns online with AdaGrad and L2, one batch at a
time.
- It starts from the rules. Its score is blended with the heuristic's, and trusted fully after `TRUST_EXAMPLES`
examples. Until then, what the rules rule out (hypothetical mentions, off-topic documents) stays out.
- Each domain's ranker is versioned in the model registry as `<domain>-extraccion` (`models.io.extraction_ranker`),
with its five routine records like any model. Extraction uses the version in production, otherwise the latest.
- It learns in line: when an import whose documents a person corrected is written, the corrected records become
examples (WebApi, `review_learning.py`) and a new DEV version is registered in the background.
- It can also learn from an answer key: `python -m webapi.nlp train --documents <folder> --key <key.json>`, which
first estimates, leaving each document out in turn, how it does on documents it hasn't seen.
## Measuring it (VAR-04, VARM-05)
`python -m webapi.nlp evaluate --documents <folder> --key <key.json>` prints precision, recall and F1 per field and
overall, and which document and field each error is in (`--with-values` adds the values). The key gives, per
document and target, the right value of each field checked, with `null` for a field that must stay empty. Measure
on documents the vocabulary was not adjusted on: the score on the documents used to adjust it says how well it fits
them, not how it generalizes.
## References
- Chapman WW et al. A simple algorithm for identifying negated findings and diseases in discharge summaries.
J Biomed Inform 2001;34(5):301-310 (NegEx).
- Harkema H et al. ConText: an algorithm for determining negation, experiencer, and temporal status from clinical
reports. J Biomed Inform 2009;42(5):839-851.
- Duchi J, Hazan E, Singer Y. Adaptive subgradient methods for online learning and stochastic optimization.
J Mach Learn Res 2011;12:2121-2159 (AdaGrad).
- Nayar R, Wilbur DC (eds.). The Bethesda System for Reporting Cervical Cytology, 3rd ed. Springer, 2015.
- Darragh TM et al. The Lower Anogenital Squamous Terminology Standardization Project for HPV-associated lesions
(LAST). Arch Pathol Lab Med 2012;136(10):1266-1297.
- American College of Radiology. ACR BI-RADS Atlas, 5th ed., 2013.
- Hirsch LJ et al. American Clinical Neurophysiology Society's Standardized Critical Care EEG Terminology: 2021
version. J Clin Neurophysiol 2021;38(1):1-29.
- Smith R. An overview of the Tesseract OCR engine. ICDAR 2007.
+39
View File
@@ -0,0 +1,39 @@
"""Structured data out of clinical documents and biosignal files.
from extraction import DocumentExtractor, FieldKind, FieldSpec, read_document
document = read_document("reporte.pdf", raw)
records = DocumentExtractor(
[FieldSpec("pac_id_hospital", FieldKind.IDENTIFIER, labels=("expediente",))],
key_field="pac_id_hospital",
).extract([document])
"""
from extraction.document import BBox, Document, EmbeddedImage, Line, Page
from extraction.errors import ExtractionError
from extraction.nlp import ExtractedValue, FieldExtractor, FieldKind, FieldSpec
from extraction.readers import read_document, reader_for, supported_extensions
from extraction.records import DocumentExtractor, ExtractedRecord, FieldConflict, RecordMerger
from extraction.segmentation import SEGMENTERS, Segmenter, make_segmenter
__all__ = [
"BBox",
"Document",
"DocumentExtractor",
"EmbeddedImage",
"ExtractedRecord",
"ExtractedValue",
"ExtractionError",
"FieldConflict",
"FieldExtractor",
"FieldKind",
"FieldSpec",
"Line",
"Page",
"RecordMerger",
"SEGMENTERS",
"Segmenter",
"make_segmenter",
"read_document",
"reader_for",
"supported_extensions",
]
+107
View File
@@ -0,0 +1,107 @@
"""In-memory representation of a read document: pages, positioned text
lines and embedded images. Every reader produces this shape, so the
segmentation and NLP layers never care whether a page came from a PDF text
layer, Tesseract, or a scanned TIFF."""
from dataclasses import dataclass, field
from typing import Literal
PageSource = Literal["text", "ocr"]
@dataclass(frozen=True)
class BBox:
"""Normalized to the page (0..1, origin top-left), so coordinates are
comparable across renders at any DPI."""
x0: float
y0: float
x1: float
y1: float
@property
def area(self) -> float:
return max(0.0, self.x1 - self.x0) * max(0.0, self.y1 - self.y0)
def as_list(self) -> list[float]:
return [round(self.x0, 4), round(self.y0, 4), round(self.x1, 4), round(self.y1, 4)]
@dataclass(frozen=True)
class Word:
"""One word of a line with its horizontal extent on the page (0..1)."""
text: str
x0: float
x1: float
@property
def center(self) -> float:
return (self.x0 + self.x1) / 2
@dataclass(frozen=True)
class Line:
"""`words`, when the reader knows them, are the line's words in order;
`text` is then exactly their texts joined by single spaces, so a
character offset in `text` maps to a position on the page."""
text: str
bbox: BBox
confidence: float = 1.0
words: tuple[Word, ...] = ()
def x_at(self, offset: int) -> float | None:
"""Left edge of the word holding character `offset` of `text`."""
position = 0
for word in self.words:
end = position + len(word.text)
if offset < end + 1:
return word.x0
position = end + 1
return None
def text_between(self, x0: float, x1: float) -> str:
"""The words whose center falls in `[x0, x1)`: one column's share of a line."""
return " ".join(word.text for word in self.words if x0 <= word.center < x1)
@dataclass(frozen=True)
class EmbeddedImage:
page_number: int
bbox: BBox
width_px: int | None = None
height_px: int | None = None
@property
def kind(self) -> str:
"""`scan` when the image is the page itself (a scanned sheet), `figure` otherwise."""
return "scan" if self.bbox.area >= 0.8 else "figure"
@dataclass
class Page:
number: int # 1-indexed
lines: list[Line]
source: PageSource
images: list[EmbeddedImage] = field(default_factory=list)
@property
def text(self) -> str:
return "\n".join(line.text for line in self.lines)
@dataclass
class Document:
name: str
media_type: str
pages: list[Page]
raw: bytes = field(repr=False, default=b"")
@property
def page_count(self) -> int:
return len(self.pages)
def page(self, number: int) -> Page:
if not 1 <= number <= len(self.pages):
raise IndexError(f"page {number} out of range (1..{len(self.pages)})")
return self.pages[number - 1]
+2
View File
@@ -0,0 +1,2 @@
class ExtractionError(Exception):
"""Unreadable input: a corrupt PDF, an unsupported format, a malformed EDF header."""
+27
View File
@@ -0,0 +1,27 @@
from extraction.nlp.discovery import DiscoveredField, discover_captions
from extraction.nlp.extractors import (
DEFAULT_EXTRACTORS,
FieldExtractor,
FreeTextMentionExtractor,
LabeledValueExtractor,
PatternExtractor,
RecordExtractor,
SegmentLine,
)
from extraction.nlp.fields import Evidence, ExtractedValue, FieldKind, FieldSpec
__all__ = [
"DEFAULT_EXTRACTORS",
"DiscoveredField",
"Evidence",
"ExtractedValue",
"FieldExtractor",
"FieldKind",
"FieldSpec",
"FreeTextMentionExtractor",
"LabeledValueExtractor",
"PatternExtractor",
"RecordExtractor",
"SegmentLine",
"discover_captions",
]
+185
View File
@@ -0,0 +1,185 @@
"""What a report says about a mention: whether it affirms it, denies it, only
supposes it, or quotes it from somewhere else; and which section of the report
it sits in.
The approach is ConText (Harkema et al., 2009, J Biomed Inform 42:839), the
extension of NegEx (Chapman et al., 2001, J Biomed Inform 34:301) to
hypothetical, historical and uncertain mentions: trigger phrases before a
mention, within its clause, qualify it, and a clause ends at a terminator.
Two additions fit how forms and lab reports are laid out:
- form-style answers after the mention (`Carcinoma invasor: NO`);
- sections. A heading such as "Datos clínicos" or "Valores de referencia"
qualifies everything under it until the next heading: what the requesting
physician suspected is not the study's result, and an interpretation guide
printed on every report describes no patient.
Triggers and headings live in `extraction.nlp.vocabulary`.
"""
import re
from dataclasses import dataclass
from enum import Enum
from functools import lru_cache
from typing import Sequence
from extraction.nlp.text import fold
class Assertion(str, Enum):
AFIRMADO = "afirmado"
NEGADO = "negado"
INCIERTO = "incierto"
HIPOTETICO = "hipotetico"
HISTORICO = "historico"
PRESUNTIVO = "presuntivo"
class Section(str, Enum):
GENERAL = "general"
CLINICA = "clinica"
DESCRIPCION = "descripcion"
RESULTADO = "resultado"
ANTECEDENTES = "antecedentes"
REFERENCIA = "referencia"
# Sections whose content is about the patient's study as such.
REPORTING_SECTIONS = frozenset({Section.GENERAL, Section.DESCRIPCION, Section.RESULTADO})
# How far back, in characters, a trigger reaches within a clause.
TRIGGER_WINDOW = 60
@dataclass(frozen=True)
class Context:
assertion: Assertion
section: Section
trigger: str | None = None
def _alternatives(terms) -> str:
folded = sorted({" ".join(re.findall(r"[A-Z0-9]+", fold(t))) for t in terms if t.strip()}, key=len, reverse=True)
return "|".join(r"[\s.\-]+".join(re.escape(w) for w in term.split()) for term in folded)
@lru_cache(maxsize=1)
def _compiled():
from extraction.nlp.vocabulary import (
CLAUSE_TERMINATORS,
POST_AFFIRMATIONS,
POST_NEGATIONS,
PRE_TRIGGERS,
PSEUDO_TRIGGERS,
SECTION_HEADINGS,
)
pre = {
assertion: re.compile(rf"(?<![A-Z0-9])({_alternatives(terms)})(?![A-Z0-9])")
for assertion, terms in PRE_TRIGGERS.items()
}
pseudo = re.compile(rf"(?<![A-Z0-9])({_alternatives(PSEUDO_TRIGGERS)})(?![A-Z0-9])")
terminator = re.compile(rf"[.;:]|(?<![A-Z0-9])({_alternatives(CLAUSE_TERMINATORS)})(?![A-Z0-9])")
post_negation = re.compile(rf"^[\s.:=\-]*({_alternatives(POST_NEGATIONS)})(?![A-Z0-9])")
post_affirmation = re.compile(rf"^[\s.:=\-]*({_alternatives(POST_AFFIRMATIONS)})(?![A-Z0-9])")
headings = [
(section, re.compile(rf"^\s*(?:(?:\d{{1,3}}|[A-Z])\s*[.)][.\-]*\s*)?({_alternatives(terms)})(?![A-Z0-9])(?P<rest>.*)$"))
for section, terms in SECTION_HEADINGS.items()
]
return pre, pseudo, terminator, post_negation, post_affirmation, headings
def _heading(folded_line: str) -> tuple[Section, bool] | None:
"""The section a line's leading heading names, and whether the heading
stands alone (nothing but punctuation after it)."""
*_, headings = _compiled()
best: tuple[int, Section, bool] | None = None
for section, pattern in headings:
match = pattern.match(folded_line)
if not match:
continue
rest = match.group("rest")
if rest.strip() and not re.match(r"^\s*[:.\-]", rest):
continue
length = len(match.group(1))
if best is None or length > best[0]:
best = (length, section, not re.sub(r"[\s:.\-]", "", rest))
return (best[1], best[2]) if best else None
def heading_section(folded_line: str) -> Section | None:
"""The section a line's leading heading names: the heading alone, or
a caption followed by its content (`Metodología: PCR`)."""
found = _heading(folded_line)
return found[0] if found else None
def caption_section(folded_line: str, start: int) -> Section | None:
"""The section a caption earlier on the same line names (`... Diagnóstico
clínico: LIAG`), for a mention after it."""
before = folded_line[:start]
colon = before.rfind(":")
if colon < 0:
return None
caption_start = max(before.rfind(".", 0, colon), before.rfind(";", 0, colon), -1) + 1
return heading_section(before[caption_start : colon + 1])
def sections(folded_lines: Sequence[str]) -> list[Section]:
"""The section of each line: the last heading standing alone at or above
it. A caption with its content on the same line (`Metodología: PCR`)
qualifies only that line."""
current = Section.GENERAL
found = []
for line in folded_lines:
heading = _heading(line)
if heading is None:
found.append(current)
elif heading[1]:
current = heading[0]
found.append(current)
else:
found.append(heading[0])
return found
def assess(folded_line: str, start: int, end: int, section: Section = Section.GENERAL) -> Context:
"""The assertion of the mention at `folded_line[start:end]`."""
pre, pseudo, terminator, post_negation, post_affirmation, _ = _compiled()
named = caption_section(folded_line, start)
if named is not None:
section = named
clause_start = max((m.end() for m in terminator.finditer(folded_line, max(0, start - TRIGGER_WINDOW), start)), default=max(0, start - TRIGGER_WINDOW))
window = folded_line[clause_start:start]
for blocked in pseudo.finditer(window):
window = window[: blocked.start()] + " " * (blocked.end() - blocked.start()) + window[blocked.end() :]
for assertion in (Assertion.NEGADO, Assertion.HIPOTETICO, Assertion.HISTORICO, Assertion.INCIERTO):
pattern = pre.get(assertion)
found = pattern.search(window) if pattern else None
if found:
return Context(assertion, section, found.group(1))
after = folded_line[end : end + 30]
if re.match(r"^\s*:", after) and not post_affirmation.match(after):
# A caption asking about it (`Carcinoma invasor:`), answered elsewhere.
negated = post_negation.match(after)
return Context(Assertion.NEGADO if negated else Assertion.HIPOTETICO, section, negated.group(1) if negated else "rubro")
negated = post_negation.match(after)
if negated and not post_affirmation.match(after):
return Context(Assertion.NEGADO, section, negated.group(1))
if section is Section.REFERENCIA:
return Context(Assertion.HIPOTETICO, section, "seccion")
if section is Section.ANTECEDENTES:
return Context(Assertion.HISTORICO, section, "seccion")
if section is Section.CLINICA:
return Context(Assertion.PRESUNTIVO, section, "seccion")
return Context(Assertion.AFIRMADO, section)
# How much a mention's assertion leaves of the confidence of a value read from it.
ASSERTION_WEIGHT = {
Assertion.AFIRMADO: 1.0,
Assertion.INCIERTO: 0.75,
Assertion.PRESUNTIVO: 0.35,
Assertion.HISTORICO: 0.35,
Assertion.HIPOTETICO: 0.15,
Assertion.NEGADO: 0.0,
}
+112
View File
@@ -0,0 +1,112 @@
"""Captions a document carries that no registered `FieldSpec` claims.
`LabeledValueExtractor` only looks for the labels a caller already knows
about. A source whose documents carry fields outside today's vocabulary
(another report layout, a free-form note) still has captions in the
`"Campo: valor"` shape; this module finds them so a caller can use them as
values of their own, or decide whether each matches something in a catalog
closely enough to reuse, or is new (see
`webapi.imports.schemas.catalog_matching`).
Captions are found wherever a form puts them: alone on their line, several
on one line, after an item number, or heading a column whose value sits on
the line below. Each one found becomes a temporary `FieldSpec`, so its value
is read by the same extractor, with the same layout handling, as the known
fields'.
"""
import re
from dataclasses import dataclass
from typing import Sequence
from extraction.nlp.extractors import LabelIndex, RecordExtractor, SegmentLine, cell_starts
from extraction.nlp.fields import Evidence, FieldKind, FieldSpec
MAX_CAPTION_WORDS = 6
_ITEM_NUMBER = re.compile(r"(?:^|(?<=\s))(?:\d{1,3}|[A-Za-z])\s*[.)][.\-]*(?=\s|$)")
# Words a caption may carry between its first and last word.
_CONNECTORS = frozenset({"de", "del", "la", "el", "los", "las", "en", "para", "por", "al", "y", "a", "que", "con", "se"})
@dataclass(frozen=True)
class DiscoveredField:
"""One `caption: value` a known `FieldSpec` didn't already claim."""
caption: str
value: str
evidence: Evidence
def discover_captions(lines: Sequence[SegmentLine], specs: Sequence[FieldSpec]) -> list[DiscoveredField]:
"""Every caption no spec claims, with its value, in the order the
captions first appear."""
known = LabelIndex(lines, specs)
captions: list[str] = []
for line_index, line in enumerate(lines):
for start, end, caption in find_captions(line):
if any(hit.start < end and start < hit.end for hit in known.hits[line_index]):
continue
if caption.casefold() not in (seen.casefold() for seen in captions):
captions.append(caption)
if not captions:
return []
adhoc = [FieldSpec(f"caption:{caption}", FieldKind.TEXT, labels=(caption,)) for caption in captions]
values = RecordExtractor([*specs, *adhoc]).extract(lines)
found = []
for caption, spec in zip(captions, adhoc):
value = values.get(spec.name)
if value is not None and str(value.value).strip():
found.append(DiscoveredField(caption, str(value.value).strip(), value.evidence))
return found
def find_captions(line: SegmentLine) -> list[tuple[int, int, str]]:
"""`(start, end, caption)` for every caption on the line, in order;
offsets are into the line's text and `end` is past the colon."""
text = line.text
boundaries = sorted({0, *cell_starts(line), *(match.end() for match in _ITEM_NUMBER.finditer(text))})
found: list[tuple[int, int, str]] = []
previous_colon = -1
for colon in (match.start() for match in re.finditer(r":(?=\s|$)", text)):
start = max([b for b in boundaries if b <= colon] + [previous_colon + 1])
words = text[start:colon].split()
if not words:
previous_colon = colon
continue
in_sentence = start == previous_colon + 1 and previous_colon >= 0 or len(words) > MAX_CAPTION_WORDS
if in_sentence:
words = _trailing_caption(words)
if not words[0][:1].isupper():
previous_colon = colon
continue
caption = " ".join(words).strip(" .-")
if caption and any(ch.isalpha() for ch in caption) and len(caption) <= 60:
found.append((text.rindex(words[0], start, colon), colon + 1, caption))
previous_colon = colon
return found
def _trailing_caption(words: list[str]) -> list[str]:
"""The caption at the end of a run of words that also holds the value
before it: the last word, plus words joined to it by connectors or
abbreviations (`Fecha de nacimiento`, `Fech. solicitud`) and the
capitalized words of a title-case caption (`Motivo Principal`)."""
caption = [words[-1]]
position = len(words) - 2
while position >= 0 and len(caption) < MAX_CAPTION_WORDS:
word = words[position]
if word.casefold() in _CONNECTORS and position > 0:
caption[:0] = [words[position - 1], word]
position -= 2
elif word.endswith(".") and len(word) <= 6 and word[0].isalpha():
caption.insert(0, word)
position -= 1
elif _title_case(word) and _title_case(caption[0]):
caption.insert(0, word)
position -= 1
else:
break
return caption
def _title_case(word: str) -> bool:
return len(word) > 1 and word[0].isupper() and word[1:].islower()
+112
View File
@@ -0,0 +1,112 @@
"""How well extraction does against an answer key (VAR-04, VARM-05).
An answer key maps each document to the right value of each field it was
checked for; `None` means the field must stay empty, and a field left out
of a document's answers is not scored for it. Per field, a value equal to
the key is a true positive, a value where the key has another or none is a
false positive, and a key value not extracted (or extracted wrong) is a
false negative: a wrong value counts as both, as is usual for slot filling.
"""
from dataclasses import dataclass, field
from typing import Any, Mapping
from extraction.nlp.ranking import same_value
@dataclass
class FieldScore:
true_positives: int = 0
false_positives: int = 0
false_negatives: int = 0
true_negatives: int = 0
@property
def precision(self) -> float | None:
found = self.true_positives + self.false_positives
return self.true_positives / found if found else None
@property
def recall(self) -> float | None:
expected = self.true_positives + self.false_negatives
return self.true_positives / expected if expected else None
@property
def f1(self) -> float | None:
p, r = self.precision, self.recall
if p is None or r is None or p + r == 0:
return None
return 2 * p * r / (p + r)
def add(self, extracted: Any, expected: Any) -> bool:
"""Scores one value; returns whether it was right."""
if expected is None:
if extracted is None:
self.true_negatives += 1
return True
self.false_positives += 1
return False
if extracted is not None and same_value(extracted, expected):
self.true_positives += 1
return True
self.false_negatives += 1
if extracted is not None:
self.false_positives += 1
return False
def merge(self, other: "FieldScore") -> None:
self.true_positives += other.true_positives
self.false_positives += other.false_positives
self.false_negatives += other.false_negatives
self.true_negatives += other.true_negatives
def to_dict(self) -> dict[str, Any]:
return {
"verdaderos_positivos": self.true_positives,
"falsos_positivos": self.false_positives,
"falsos_negativos": self.false_negatives,
"verdaderos_negativos": self.true_negatives,
"precision": _round(self.precision),
"exhaustividad": _round(self.recall),
"f1": _round(self.f1),
}
@dataclass
class Evaluation:
fields: dict[str, FieldScore] = field(default_factory=dict)
# Per document and field, what was extracted where it differs from the key.
errors: list[dict[str, Any]] = field(default_factory=list)
@property
def overall(self) -> FieldScore:
total = FieldScore()
for score in self.fields.values():
total.merge(score)
return total
def to_dict(self, *, with_values: bool = False) -> dict[str, Any]:
"""`with_values` includes the wrong and expected values of each error;
without it, only which document and field, so a report on real
documents can be shared without what they say."""
errors = self.errors if with_values else [{"documento": e["documento"], "campo": e["campo"]} for e in self.errors]
return {
"global": self.overall.to_dict(),
"campos": {name: score.to_dict() for name, score in sorted(self.fields.items())},
"errores": errors,
}
def evaluate(extracted: Mapping[str, Mapping[str, Any]], key: Mapping[str, Mapping[str, Any]]) -> Evaluation:
"""`extracted` and `key`: per document, per field, a value."""
result = Evaluation()
for document, expected_fields in key.items():
found = extracted.get(document, {})
for name, expected in expected_fields.items():
value = found.get(name)
if not result.fields.setdefault(name, FieldScore()).add(value, expected):
result.errors.append({"documento": document, "campo": name, "extraido": value, "esperado": expected})
return result
def _round(value: float | None) -> float | None:
return None if value is None else round(value, 3)
+747
View File
@@ -0,0 +1,747 @@
"""Field extraction strategies. Each `FieldExtractor` proposes candidates
for a field, each with the features of how it was found; `RecordExtractor`
keeps them all and lets a `CandidateRanker` (`extraction.nlp.ranking`) pick
one per field. Without a trained ranker, the most confident candidate wins.
To add a strategy (a dictionary lookup, a statistical NER model, an LLM
call), subclass `FieldExtractor`, give it a `method` name and pass an
instance to `RecordExtractor(extractors=[...])`.
"""
import re
from abc import ABC, abstractmethod
from collections import Counter
from dataclasses import dataclass
from functools import lru_cache
from typing import Any, ClassVar, Iterable, Sequence
from rapidfuzz import fuzz
from extraction.document import Line
from extraction.nlp.context import ASSERTION_WEIGHT, Assertion, Context, Section, assess, heading_section, sections
from extraction.nlp.fields import Evidence, ExtractedValue, FieldKind, FieldSpec
from extraction.nlp.text import (
SEPARATOR,
find_date,
find_decimal,
find_identifier,
find_integer,
fold,
is_negated,
label_pattern,
ocr_fold,
)
FUZZY_LABEL_THRESHOLD = 0.86
MAX_TEXT_LENGTH = 1000
MAX_CONTINUATION_LINES = 8
# A choice whose label stands alone may state its value a few lines down,
# after a subheading.
MAX_CHOICE_LOOKAHEAD = 3
# Values in a column may start slightly left of the label heading it.
COLUMN_MARGIN = 0.02
# What an OCR look-alike match is worth next to an exact one.
OCR_MATCH_SCORE = 0.92
@dataclass(frozen=True)
class SegmentLine:
"""`ocr`: the line was read by OCR, so look-alike characters may stand in
for each other (`extraction.nlp.text.ocr_fold`)."""
document: str
page_number: int
line: Line
ocr: bool = False
@property
def text(self) -> str:
return self.line.text
@property
def folded(self) -> str:
return fold(self.line.text)
@property
def ocr_folded(self) -> str:
return ocr_fold(self.line.text)
@property
def ocr_confidence(self) -> float:
return self.line.confidence if self.line.confidence > 0 else 0.5
def evidence(self, text: str | None = None) -> Evidence:
return Evidence(self.document, self.page_number, text or self.line.text, self.line.bbox.as_list())
@dataclass(frozen=True)
class LabelHit:
field: str
start: int
end: int
score: float
class LabelIndex:
"""Every label occurrence of every field, per line. Knowing where *all*
labels sit is what lets one form line such as
`Nombre: ANA Sexo: F C.P.: 64000` be split into three values.
Captions no field knows (`Cualquier otra cosa:`) are tracked too, as
boundaries: they end the value before them and the text under the
label before them, without being read themselves."""
def __init__(self, lines: Sequence[SegmentLine], specs: Iterable[FieldSpec]):
self.score_tables: dict[str, dict[str, ExtractedValue]] = {}
self.flags: set[str] = set()
self.lines = list(lines)
self.folded = [line.folded for line in self.lines]
self.hits: list[list[LabelHit]] = [_label_hits(line, tuple(specs)) for line in self.lines]
self.boundaries: list[list[int]] = [
_boundaries(folded, hits) for folded, hits in zip(self.folded, self.hits)
]
self.sections: list[Section] = sections([line.ocr_folded if line.ocr else line.folded for line in self.lines])
def context(self, line_index: int, start: int, end: int) -> Context:
"""The assertion of the mention at `start:end` of a line."""
line = self.lines[line_index]
return assess(line.ocr_folded if line.ocr else line.folded, start, end, self.sections[line_index])
def label_context(self, line_index: int, hit: "LabelHit") -> Context:
"""A label's value is the answer to it, so only where the label sits
qualifies it: its section, or a caption that names one
("Diagnóstico clínico:" is what was suspected, not found). A caption
inside reference text (a report date in the footer under an
interpretation guide) is still the document's own."""
folded = self.folded[line_index]
section = heading_section(folded[_caption_start(folded, hit.start) :]) or self.sections[line_index]
assertion = {
Section.CLINICA: Assertion.PRESUNTIVO,
Section.ANTECEDENTES: Assertion.HISTORICO,
}.get(section, Assertion.AFIRMADO)
return Context(assertion, section)
def position(self, line_index: int) -> float:
return line_index / max(1, len(self.lines) - 1)
def for_field(self, name: str) -> Iterable[tuple[int, LabelHit]]:
for index, hits in enumerate(self.hits):
for hit in hits:
if hit.field == name:
yield index, hit
def next_start(self, index: int, after: int) -> int | None:
starts = [start for start in self.boundaries[index] if start >= after]
return min(starts) if starts else None
def column(self, index: int, hit: LabelHit) -> tuple[float, float] | None:
"""Horizontal extent of the column a label heads, when its line
carries other captions too: from the label's left edge to the next
caption's. `None` for a label alone on its line or without word
positions."""
starts = self.boundaries[index]
line = self.lines[index].line
own = max((start for start in starts if start <= hit.start), default=None)
if len(starts) < 2 or not line.words or own is None:
return None
position = starts.index(own)
left = line.x_at(own) if position else 0.0
right = line.x_at(starts[position + 1]) if position + 1 < len(starts) else 1.0
if left is None or right is None or right <= left:
return None
return left - COLUMN_MARGIN if position else 0.0, right - COLUMN_MARGIN if position + 1 < len(starts) else 1.0
def label_in_column(self, index: int, column: tuple[float, float]) -> bool:
line = self.lines[index].line
return any(column[0] <= (line.x_at(start) or -1.0) < column[1] for start in self.boundaries[index])
def starts_with_label(self, index: int) -> bool:
text = self.lines[index].folded
offset = len(text) - len(text.lstrip())
return any(start <= offset + 2 for start in self.boundaries[index])
# A caption no field knows: a few words and a colon, at the start of the
# line or after an item number (`7.- `, `b) `).
_ITEM_NUMBER = r"(?:\d{1,3}|[A-Z])\s*[.)][.\-]*\s*"
_ANY_CAPTION = re.compile(rf"(?:^|(?<=\s))(?P<item>{_ITEM_NUMBER})?[A-Z][A-Z0-9./\-]*(?:\s+[A-Z0-9][A-Z0-9./\-]*){{0,5}}\s*:")
_TRAILING_ITEM_NUMBER = re.compile(rf"(?:^|(?<=\s)){_ITEM_NUMBER}$")
# An item number in the middle of a line (`... 3.- SIGUIENTE`) starts the next item.
_INLINE_ITEM = re.compile(r"(?<=\s)(?:\d{1,3}\.-|\d{1,3}\)|[A-Z]\))(?=\s)")
# A horizontal gap wider than this (fraction of the page) between two words
# separates two cells of a form line.
CELL_GAP = 0.02
def cell_starts(line: SegmentLine) -> list[int]:
"""Character offsets where a word starts after a wide horizontal gap;
without word positions, after a run of spaces or a tab."""
words = line.line.words
if not words:
return [match.end() for match in re.finditer(r"\s{2,}|\t", line.text)]
starts, offset = [], 0
for previous, word in zip((None, *words), words):
if previous is not None and word.x0 - previous.x1 > CELL_GAP:
starts.append(offset)
offset += len(word.text) + 1
return starts
def _within_cell(line: SegmentLine, start: int, tail: str) -> str:
"""A value ends where the next cell of the line begins, once it has
started: the gap between a caption and its value doesn't cut it."""
cuts = [cut for cut in cell_starts(line) if cut > start]
if not cuts or cuts[0] >= start + len(tail):
return tail
return line.text[start : cuts[0]].rstrip()
def _caption_start(folded: str, start: int) -> int:
"""Where a caption begins, counting the item number printed before it."""
item = _TRAILING_ITEM_NUMBER.search(folded[:start])
return item.start() if item else start
def _boundaries(folded: str, hits: list[LabelHit]) -> list[int]:
starts = {hit: _caption_start(folded, hit.start) for hit in hits}
extra: set[int] = {
match.start() for match in _INLINE_ITEM.finditer(folded) if not any(hit.start <= match.start() < hit.end for hit in hits)
}
line_start = len(folded) - len(folded.lstrip())
for match in _ANY_CAPTION.finditer(folded):
if match.start() != line_start and not match.group("item"):
continue
inside = [hit for hit in hits if match.start() <= hit.start < match.end()]
for hit in inside:
starts[hit] = min(starts[hit], match.start())
if not inside and not any(hit.start <= match.start() < hit.end for hit in hits):
extra.add(match.start())
return sorted(set(starts.values()) | extra)
_AFTER_CAPTION = re.compile(r"\s*[:=#]|\s{2,}|\s*$")
def _is_caption(folded: str, start: int, end: int) -> bool:
"""A caption starts its line or is followed by a separator; the same
words inside a sentence ("...muestra adecuada...") are just text."""
return not folded[:start].strip() or bool(_AFTER_CAPTION.match(folded, end))
# A caption may run on for a few words before its colon.
_CAPTION_RUN_ON = re.compile(r"(?:\s+[A-Z]{1,15}\.?){1,4}\s*:")
# Words a run-on caption may have before its label, counted from the start
# of the line, an item number or the previous colon; more is a sentence.
MAX_CAPTION_LEAD_WORDS = 2
_CONNECTOR_BEFORE = re.compile(r"(?<![A-Z0-9])(DE|DEL|PARA|POR|EN|CON|SIN|A|AL)\s+$")
def _names_something_else(folded: str, start: int) -> bool:
"""A label right after a connector is the tail of a longer caption
that names something else: `FECHA DE INTERPRETACION` is a date, not
the interpretation."""
return bool(_CONNECTOR_BEFORE.search(folded[max(0, start - 8) : start]))
def _near_segment_start(folded: str, start: int) -> bool:
segment = re.split(r":|(?:^|\s)(?:\d{1,3}|[A-Z])\s*[.)][.\-]*\s", folded[:start])[-1]
return len(segment.split()) <= MAX_CAPTION_LEAD_WORDS
def _label_hits(line: SegmentLine, specs: tuple[FieldSpec, ...]) -> list[LabelHit]:
folded = line.folded
canonical = line.ocr_folded if line.ocr else None
found: list[LabelHit] = []
for spec in specs:
for label in spec.labels:
exact = [LabelHit(spec.name, m.start(), m.end(), 1.0) for m in label_pattern(label).finditer(folded)]
if not exact and canonical is not None:
exact = [
LabelHit(spec.name, m.start(), m.end(), OCR_MATCH_SCORE)
for m in label_pattern(ocr_fold(label)).finditer(canonical)
]
found.extend(exact or _fuzzy_hits(canonical or folded, spec.name, ocr_fold(label) if canonical else label))
hits: list[LabelHit] = []
for hit in found:
if _names_something_else(folded, hit.start):
continue
if _is_caption(folded, hit.start, hit.end):
hits.append(hit)
continue
run_on = _CAPTION_RUN_ON.match(folded, hit.end)
if (
run_on
and _near_segment_start(folded, hit.start)
and not any(other is not hit and other.start < run_on.end() and other.end > hit.end for other in found)
):
hits.append(LabelHit(hit.field, hit.start, run_on.end(), hit.score))
# A label inside a longer one ("FECHA" inside "FECHA DE NACIMIENTO") is not a label.
hits.sort(key=lambda h: (h.start, -(h.end - h.start)))
kept: list[LabelHit] = []
for hit in hits:
if any(other.start <= hit.start and hit.end <= other.end and (other.end - other.start) > (hit.end - hit.start) for other in hits):
continue
kept.append(hit)
return kept
@lru_cache(maxsize=4096)
def _folded_label(label: str) -> str:
return " ".join(re.findall(r"[A-Z0-9]+", fold(label)))
def _fuzzy_hits(folded: str, field_name: str, label: str) -> list[LabelHit]:
"""Tolerates OCR misreads in long labels (`FECHA DE NAC1MIENTO`)."""
target = _folded_label(label)
if len(target) < 6:
return []
tokens = [(m.group(), m.start(), m.end()) for m in re.finditer(r"[A-Z0-9]+", folded)]
width = len(target.split())
hits = []
for i in range(len(tokens) - width + 1):
window = tokens[i : i + width]
candidate = " ".join(token for token, _, _ in window)
ratio = fuzz.ratio(candidate, target) / 100.0
if ratio >= FUZZY_LABEL_THRESHOLD:
hits.append(LabelHit(field_name, window[0][1], window[-1][2], round(ratio, 3)))
return hits
@dataclass(frozen=True)
class Parsed:
value: Any
raw: str
quality: float
def parse_value(spec: FieldSpec, text: str, *, ocr: bool = False) -> Parsed | None:
"""Reads a value of `spec.kind` out of the text found next to a label;
`ocr` also accepts choices written with OCR look-alikes."""
text = text.strip()
if not text:
return None
if spec.kind is FieldKind.DATE:
found = find_date(text)
return Parsed(found[0], text[slice(*found[1])], 1.0 if found[1][0] <= 3 else 0.85) if found else None
if spec.kind is FieldKind.INTEGER:
found = find_integer(text)
dated = find_date(text)
if found and dated and dated[1][0] <= found[1][0] < dated[1][1]:
return None
return Parsed(found[0], text[slice(*found[1])], 1.0 if found[1][0] <= 3 else 0.8) if found else None
if spec.kind is FieldKind.DECIMAL:
found = find_decimal(text)
return Parsed(found[0], text[slice(*found[1])], 1.0 if found[1][0] <= 3 else 0.8) if found else None
if spec.kind is FieldKind.IDENTIFIER:
found = find_identifier(text, spec.pattern)
return Parsed(found[0], found[0], 1.0 if found[1][0] <= 3 else 0.85) if found else None
if spec.kind is FieldKind.CHOICE:
found = find_choice(spec, fold(text))
quality = 1.0
if found is None and ocr:
found = find_choice(spec, ocr_fold(text), canonical=True)
quality = OCR_MATCH_SCORE
if found is None:
return None
value, surface, start = found
return Parsed(value, text[start : start + len(surface)], quality * (1.0 if start <= 3 else 0.85))
if spec.pattern:
match = re.search(spec.pattern, text, re.I)
return Parsed(match.group(), match.group(), 1.0 if match.start() <= 3 else 0.85) if match else None
return Parsed(text[:MAX_TEXT_LENGTH], text[:MAX_TEXT_LENGTH], 0.9)
def find_choice(spec: FieldSpec, folded: str, *, min_length: int = 1, canonical: bool = False) -> tuple[Any, str, int] | None:
"""Leftmost, then longest, non-negated surface form of `spec` in `folded`
(`canonical`: `folded` went through `ocr_fold`, and so do the surfaces)."""
best: tuple[Any, str, int] | None = None
for surface in spec.surface_forms:
if len(surface) < min_length:
continue
for match in _choice_pattern(ocr_fold(surface) if canonical else surface).finditer(folded):
if not _negates_itself(surface) and is_negated(folded, match.start()):
continue
if best is None or match.start() < best[2] or (match.start() == best[2] and len(surface) > len(best[1])):
best = (spec.choices[surface], surface, match.start())
break
return best
@lru_cache(maxsize=8192)
def _choice_pattern(surface: str) -> re.Pattern:
body = r"[\s.\-]+".join(re.escape(token) for token in surface.split())
return re.compile(rf"(?<![A-Z0-9]){body}(?![A-Z0-9])")
def _negates_itself(surface: str) -> bool:
return bool(re.search(r"(?<![A-Z])(NO|NEGATIV[OA]|SIN|AUSENCIA)(?![A-Z])", surface))
class FieldExtractor(ABC):
method: ClassVar[str]
@abstractmethod
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterable[ExtractedValue]: ...
class LabeledValueExtractor(FieldExtractor):
"""`Etiqueta: valor` on the same line, or the value on the line(s)
under the label — the layout of forms and of report section headers
(`DIAGNÓSTICO:` followed by a paragraph)."""
method = "etiqueta"
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterable[ExtractedValue]:
for line_index, hit in index.for_field(spec.name):
line = index.lines[line_index]
end = index.next_start(line_index, hit.end)
tail = line.text[hit.end : end]
tail = tail[len(SEPARATOR.match(tail).group()) :]
tail = _within_cell(line, line.text.index(tail, hit.end) if tail else hit.end, tail)
source_line = line
below = False
if not tail.strip() or (spec.multiline and spec.kind is FieldKind.TEXT):
continuation = self._continuation(spec, index, line_index, index.column(line_index, hit))
if continuation is not None:
tail, source_line = (f"{tail.strip()} {continuation[0]}".strip(), continuation[1])
below = True
parsed = parse_value(spec, tail, ocr=line.ocr or source_line.ocr)
if parsed is None:
continue
context = index.label_context(line_index, hit)
confidence = 0.95 * hit.score * parsed.quality * min(line.ocr_confidence, source_line.ocr_confidence)
confidence *= max(ASSERTION_WEIGHT[context.assertion], 0.1)
features = {
"assertion": context.assertion.value,
"section": context.section.value,
"label_score": hit.score,
"parse_quality": parsed.quality,
"value_below_label": below,
"position": index.position(line_index),
"ocr": line.ocr,
}
yield ExtractedValue(parsed.value, confidence, self.method, parsed.raw, source_line.evidence(line.text), features)
@staticmethod
def _continuation(
spec: FieldSpec, index: LabelIndex, line_index: int, column: tuple[float, float] | None = None
) -> tuple[str, SegmentLine] | None:
"""The text under a label. When the label shares its line with
other labels (a form laid out in columns, captions on one row and
values on the next), only the words under this label's column
count, and lines with nothing in that column are passed over."""
limit = MAX_CONTINUATION_LINES if spec.multiline else (MAX_CHOICE_LOOKAHEAD if spec.kind is FieldKind.CHOICE else 1)
collected: list[tuple[str, SegmentLine]] = []
for following in range(line_index + 1, min(len(index.lines), line_index + 1 + limit)):
candidate = index.lines[following]
if candidate.page_number != index.lines[line_index].page_number or not candidate.text.strip():
break
if index.starts_with_label(following):
break
text = candidate.text.strip()
if column is not None and candidate.line.words:
if index.label_in_column(following, column):
break
text = candidate.line.text_between(*column)
if not text:
continue
collected.append((text, candidate))
if spec.kind is FieldKind.CHOICE and parse_value(spec, text, ocr=candidate.ocr) is not None:
break
if not collected:
return None
return " ".join(text for text, _ in collected), collected[0][1]
class PatternExtractor(FieldExtractor):
"""Values with a recognizable shape (`EXP-0042`, a CIE-10 code) found
anywhere in the text, for fields with `scan_free_text` and a `pattern`.
Lines that also carry one of the field's labels score higher."""
method = "patron"
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterable[ExtractedValue]:
if not spec.pattern or not spec.scan_free_text:
return
regex = re.compile(spec.pattern, re.I)
labelled_lines = {line_index for line_index, _ in index.for_field(spec.name)}
for line_index, line in enumerate(index.lines):
for match in regex.finditer(line.text):
parsed = parse_value(spec, match.group())
if parsed is None:
continue
context = index.context(line_index, match.start(), match.end())
base = 0.85 if line_index in labelled_lines else 0.7
features = {
"assertion": context.assertion.value,
"section": context.section.value,
"labelled_line": line_index in labelled_lines,
"position": index.position(line_index),
"ocr": line.ocr,
}
confidence = base * line.ocr_confidence * max(ASSERTION_WEIGHT[context.assertion], 0.1)
yield ExtractedValue(parsed.value, confidence, self.method, match.group(), line.evidence(), features)
@dataclass(frozen=True)
class Mention:
value: Any
raw: str
line_index: int
context: Context
anchored: bool
generic: bool
@property
def weight(self) -> float:
return ASSERTION_WEIGHT[self.context.assertion]
def _anchor_terms(spec: FieldSpec) -> tuple[str, ...]:
return tuple(dict.fromkeys(fold(term).strip() for term in (*spec.anchors, *spec.labels) if term.strip()))
@lru_cache(maxsize=2048)
def _anchor_pattern(terms: tuple[str, ...]) -> re.Pattern | None:
if not terms:
return None
body = "|".join(r"[\s.\-]+".join(re.escape(token) for token in term.split()) for term in sorted(terms, key=len, reverse=True))
return re.compile(rf"(?<![A-Z0-9])(?:{body})(?![A-Z0-9])")
# How far before a mention, on its line, its anchor may be.
ANCHOR_REACH = 80
def is_generic(surface: str) -> bool:
from extraction.nlp.vocabulary import GENERIC_TERMS
return " ".join(surface.split()) in GENERIC_TERMS
class FreeTextMentionExtractor(FieldExtractor):
"""Catalog terms mentioned in narrative text ("...compatible con NIC
II...") without a label in front, each judged in its context
(`extraction.nlp.context`): denied, hypothetical, historical or
clinically presumed mentions count for little or nothing, a generic
answer ("POSITIVO") only counts after its concept (`FieldSpec.anchors`),
and a denied mention of a presence field gives its `negated_value`.
Every value mentioned is a candidate. The one proposed first is, for a
field with a `severity` order, the most severe value the report
affirms; otherwise the most repeated, ties going to the last mention,
since reports state their conclusion at the end."""
method = "texto_libre"
MIN_SURFACE_LENGTH = 4
def mentions(self, spec: FieldSpec, index: LabelIndex) -> list[Mention]:
anchors = _anchor_pattern(_anchor_terms(spec))
found: list[Mention] = []
for line_index, line in enumerate(index.lines):
texts = [(line.folded, False)]
if line.ocr:
texts.append((line.ocr_folded, True))
seen: set[tuple[int, int]] = set()
for text, canonical in texts:
taken: list[tuple[int, int]] = []
for surface in spec.surface_forms:
if len(surface) < self.MIN_SURFACE_LENGTH:
continue
pattern = _choice_pattern(ocr_fold(surface) if canonical else surface)
for match in pattern.finditer(text):
span = (match.start(), match.end())
# A longer surface already covers this one ("NIC III" over "NIC II").
if span in seen or any(s <= span[0] and span[1] <= e for s, e in taken):
continue
taken.append(span)
seen.add(span)
context = index.context(line_index, *span)
negates_itself = _negates_itself(surface)
if negates_itself and context.assertion is Assertion.NEGADO:
continue
value = spec.choices[surface]
if context.assertion is Assertion.NEGADO and not negates_itself:
if spec.negated_value is None:
continue
value = spec.negated_value
context = Context(Assertion.AFIRMADO, context.section, context.trigger)
reach = text[max(0, span[0] - ANCHOR_REACH) : span[0]]
anchored = bool(anchors and anchors.search(reach))
generic = is_generic(surface)
if generic and not anchored:
continue
found.append(Mention(value, line.text[span[0] : span[1]], line_index, context, anchored, generic))
return found
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterable[ExtractedValue]:
if spec.kind is not FieldKind.CHOICE or not spec.scan_free_text:
return
mentions = [m for m in self.mentions(spec, index) if m.weight > 0]
if not mentions:
return
total = sum(m.weight for m in mentions)
by_value: dict[Any, list[Mention]] = {}
for mention in mentions:
by_value.setdefault(mention.value, []).append(mention)
support = {value: sum(m.weight for m in group) for value, group in by_value.items()}
affirmed = [m for m in mentions if m.context.assertion is Assertion.AFIRMADO]
if spec.severity and affirmed:
winner_value = max((m.value for m in affirmed), key=lambda v: (spec.severity_rank(v), support[v]))
else:
top = max(support.values())
winner_value = [m for m in mentions if support[m.value] == top][-1].value
most_severe = max(by_value, key=spec.severity_rank) if spec.severity else None
def confidence_of(value: Any, best: Mention) -> float:
share = support[value] / total
return 0.65 * max(share, 0.5) * index.lines[best.line_index].ocr_confidence * best.weight
best_of = {value: max(group, key=lambda m: (m.weight, m.line_index)) for value, group in by_value.items()}
winner_confidence = confidence_of(winner_value, best_of[winner_value])
for value, group in by_value.items():
best = best_of[value]
line = index.lines[best.line_index]
share = support[value] / total
confidence = winner_confidence
if value != winner_value:
# The others stay below the winner, so ranking by confidence picks it.
confidence = min(0.8 * confidence_of(value, best), 0.9 * winner_confidence)
features = {
"assertion": best.context.assertion.value,
"section": best.context.section.value,
"share": share,
"mentions": len(group),
"anchored": best.anchored,
"generic": best.generic,
"most_severe": spec.severity and value == most_severe,
"last_mention": best.line_index == max(m.line_index for m in mentions),
"position": index.position(best.line_index),
"ocr": line.ocr,
}
yield ExtractedValue(value, confidence, self.method, best.raw, line.evidence(), features)
class MeasurementExtractor(FieldExtractor):
"""A number written with its unit after the field's concept, in the same
clause ("ritmo de fondo de 8 a 9 Hz"), for fields with a `unit`. A range
gives its midpoint."""
method = "medicion"
_NUMBER = r"\d+(?:[.,]\d+)?"
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterable[ExtractedValue]:
if not spec.unit or spec.kind not in (FieldKind.DECIMAL, FieldKind.INTEGER):
return
anchors = _anchor_pattern(_anchor_terms(spec))
measure = re.compile(
rf"(?<![\w.,])(?P<low>{self._NUMBER})(?:\s*(?:-|A|Y|AL)\s*(?P<high>{self._NUMBER}))?\s*(?:{spec.unit})(?![A-Z])"
)
for line_index, line in enumerate(index.lines):
folded = line.folded
for match in measure.finditer(folded):
reach = folded[max(0, match.start() - ANCHOR_REACH) : match.start()]
anchor = anchors.search(reach) if anchors else None
if anchor is None:
continue
if re.search(r"[.;]", reach[anchor.end() :]):
continue
low = float(match.group("low").replace(",", "."))
high = float(match.group("high").replace(",", ".")) if match.group("high") else low
value: float | int = (low + high) / 2
if spec.kind is FieldKind.INTEGER:
value = int(round(value))
context = index.context(line_index, match.start(), match.end())
if context.assertion is Assertion.NEGADO:
continue
features = {
"assertion": context.assertion.value,
"section": context.section.value,
"anchored": True,
"range": match.group("high") is not None,
"position": index.position(line_index),
"ocr": line.ocr,
}
confidence = 0.8 * line.ocr_confidence * ASSERTION_WEIGHT[context.assertion]
yield ExtractedValue(value, confidence, self.method, line.text[match.start() : match.end()], line.evidence(), features)
from extraction.nlp.score_tables import ScoreTableExtractor
DEFAULT_EXTRACTORS: tuple[FieldExtractor, ...] = (
LabeledValueExtractor(),
PatternExtractor(),
FreeTextMentionExtractor(),
MeasurementExtractor(),
ScoreTableExtractor(),
)
class RecordExtractor:
"""Every candidate of every field, then one per field: the ranker's pick
(`extraction.nlp.ranking`), by default the most confident."""
def __init__(self, specs: Sequence[FieldSpec], *, extractors: Sequence[FieldExtractor] = DEFAULT_EXTRACTORS, ranker=None):
from extraction.nlp.ranking import HeuristicRanker
self.specs = list(specs)
self.extractors = list(extractors)
self.ranker = ranker or HeuristicRanker()
def candidates(
self, lines: Sequence[SegmentLine], *, flags: set[str] | None = None
) -> dict[str, list[ExtractedValue]]:
index = LabelIndex(lines, self.specs)
found: dict[str, list[ExtractedValue]] = {}
for spec in self.specs:
proposed = [candidate for extractor in self.extractors for candidate in extractor.candidates(spec, index)]
if proposed:
found[spec.name] = describe_candidates(proposed)
if flags is not None:
flags.update(index.flags)
return found
def choose(self, candidates: dict[str, list[ExtractedValue]]) -> dict[str, ExtractedValue]:
specs = {spec.name: spec for spec in self.specs}
chosen = {}
for name, proposed in candidates.items():
best = self.ranker.choose(specs[name], proposed)
if best is not None:
chosen[name] = best
return chosen
def extract(self, lines: Sequence[SegmentLine]) -> dict[str, ExtractedValue]:
return self.choose(self.candidates(lines))
def describe_candidates(proposed: list[ExtractedValue]) -> list[ExtractedValue]:
"""Adds what only the set of a field's candidates tells: how each ranks
by confidence, how many there are and how many others agree with it."""
ordered = sorted(proposed, key=lambda c: -c.confidence)
values = Counter(_comparable(c.value) for c in proposed)
methods: dict[Any, set[str]] = {}
for candidate in proposed:
methods.setdefault(_comparable(candidate.value), set()).add(candidate.method)
return [
candidate.with_confidence(
candidate.confidence,
rank=rank,
candidates=len(proposed),
distinct_values=len(values),
agreeing=values[_comparable(candidate.value)] - 1,
agreeing_methods=len(methods[_comparable(candidate.value)]) - 1,
)
for rank, candidate in enumerate(ordered)
]
def _comparable(value: Any) -> Any:
return fold(value).strip() if isinstance(value, str) else value
+101
View File
@@ -0,0 +1,101 @@
from dataclasses import dataclass, field
from datetime import date
from enum import Enum
from typing import Any, Mapping
from extraction.nlp.text import fold
class FieldKind(str, Enum):
TEXT = "text"
IDENTIFIER = "identifier"
INTEGER = "integer"
DECIMAL = "decimal"
DATE = "date"
CHOICE = "choice"
@dataclass(frozen=True)
class FieldSpec:
"""What to look for in a document to fill one column.
`labels` are the captions a form or report prints before the value
("Fecha de nacimiento", "F. Nac."). `choices` maps surface forms to the
value stored (`"NO DETECTADO" -> 0`, `"NIC II" -> "LIEAG"`); matching is
accent- and case-insensitive and prefers the longest form.
`pattern` is the shape of a valid value (the match is what's kept).
`scan_free_text` lets the field be found anywhere in the narrative, not
only after one of its labels: as a mention for CHOICE fields, by
`pattern` for the rest.
In narrative text a generic answer ("POSITIVO") only counts next to one
of `anchors` or `labels`; `severity` orders the choice values from least
to most severe, and the most severe one a report affirms is its finding;
`negated_value` is what a denied mention means ("sin actividad
epileptiforme" -> 0); `unit` is a pattern for the unit a measurement is
written in (`HZ`).
"""
name: str
kind: FieldKind = FieldKind.TEXT
labels: tuple[str, ...] = ()
choices: Mapping[str, Any] = field(default_factory=dict)
pattern: str | None = None
scan_free_text: bool = False
multiline: bool = False
required: bool = False
anchors: tuple[str, ...] = ()
severity: tuple[Any, ...] = ()
negated_value: Any = None
unit: str | None = None
def __post_init__(self):
folded = {fold(str(surface)).strip(): value for surface, value in self.choices.items() if str(surface).strip()}
object.__setattr__(self, "choices", folded)
@property
def surface_forms(self) -> list[str]:
return sorted(self.choices, key=len, reverse=True)
def severity_rank(self, value: Any) -> int:
return self.severity.index(value) if value in self.severity else -1
@dataclass(frozen=True)
class Evidence:
document: str
page_number: int
line: str
bbox: list[float] | None = None
@dataclass(frozen=True)
class ExtractedValue:
"""One reading of a field. `features` describe how it was found (the
mention's assertion and section, the label's score...), for
`extraction.nlp.ranking`; they never hold the document's text."""
value: Any
confidence: float
method: str
raw: str
evidence: Evidence
features: Mapping[str, Any] = field(default_factory=dict, compare=False, hash=False)
def with_confidence(self, confidence: float, **features: Any) -> "ExtractedValue":
return ExtractedValue(self.value, confidence, self.method, self.raw, self.evidence, {**self.features, **features})
def to_dict(self) -> dict[str, Any]:
value = self.value.isoformat() if isinstance(self.value, date) else self.value
return {
"value": value,
"confidence": round(self.confidence, 3),
"method": self.method,
"raw": self.raw,
"document": self.evidence.document,
"page_number": self.evidence.page_number,
"line": self.evidence.line,
"bbox": self.evidence.bbox,
"assertion": self.features.get("assertion"),
**{flag: True for flag in ("totales_no_cuadran", "modulo_no_coincide") if self.features.get(flag)},
}
+224
View File
@@ -0,0 +1,224 @@
"""Choosing one reading per field among the candidates the extractors
propose, and learning to choose better from the corrections people make.
`HeuristicRanker` keeps the most confident candidate. `LearnedRanker` is a
logistic regression over how each candidate was found (its method, the
assertion and section of its mention, the label's score, how many other
candidates agree with it...), never over the document's words: its weights
can be read, and it holds nothing a patient wrote or was written about.
It learns online, one batch of reviewed records at a time (AdaGrad with L2,
Duchi et al., 2011), so a correction made today improves tomorrow's
extraction without retraining from scratch.
While it has seen few examples its score is blended with the heuristic
one (`HeuristicRanker`, rules included), trusting it more as examples
accumulate (`TRUST_EXAMPLES`).
"""
import math
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from datetime import date, datetime
from typing import Any, Iterable, Mapping, Sequence
from extraction.nlp.fields import ExtractedValue, FieldSpec
from extraction.nlp.text import fold
# Examples after which the learned score is trusted fully over the heuristic.
TRUST_EXAMPLES = 200
# Below this score, a field is left empty rather than filled with its best
# guess; a trusted learned ranker leaves it empty below even odds.
MIN_SCORE = 0.05
LEARNED_MIN_SCORE = 0.5
class CandidateRanker(ABC):
version: str | None = None
@property
def min_score(self) -> float:
return MIN_SCORE
@abstractmethod
def score(self, spec: FieldSpec, candidate: ExtractedValue) -> float: ...
def choose(self, spec: FieldSpec, candidates: Sequence[ExtractedValue]) -> ExtractedValue | None:
"""The best candidate, its confidence replaced by its score."""
scored = [(self.score(spec, candidate), candidate) for candidate in candidates]
if not scored:
return None
score, best = max(scored, key=lambda pair: (pair[0], pair[1].confidence))
if score < self.min_score:
return None
return best.with_confidence(score)
class HeuristicRanker(CandidateRanker):
"""The most confident candidate, except that a document about something
else than the target, or a mention the report only supposes, fills
nothing: those are left for a person, and for a learned ranker to weigh."""
def score(self, spec: FieldSpec, candidate: ExtractedValue) -> float:
if candidate.features.get("on_topic") is False or candidate.features.get("assertion") == "hipotetico":
return 0.0
return candidate.confidence
def features(spec: FieldSpec, candidate: ExtractedValue) -> dict[str, float]:
"""A candidate as named features: categorical ones one-hot, numeric ones
as they are; field and method crossed with the rest, so each field can
weigh each kind of evidence its own way."""
out: dict[str, float] = {"bias": 1.0, f"kind={spec.kind.value}": 1.0}
prefixes = (f"method={candidate.method}", f"field={spec.name}", f"field={spec.name}|method={candidate.method}")
out.update({prefix: 1.0 for prefix in prefixes})
numeric = {"heuristic": candidate.confidence}
categorical: dict[str, str] = {}
for key, value in candidate.features.items():
if isinstance(value, bool):
numeric[key] = float(value)
elif isinstance(value, (int, float)):
numeric[key] = float(value)
elif isinstance(value, str):
categorical[key] = value
numeric["log_candidates"] = math.log1p(numeric.pop("candidates", 0.0))
numeric["first"] = float(numeric.pop("rank", 1.0) == 0)
for key, value in numeric.items():
out[key] = value
out[f"method={candidate.method}|{key}"] = value
for key, value in categorical.items():
out[f"{key}={value}"] = 1.0
out[f"method={candidate.method}|{key}={value}"] = 1.0
out[f"field={spec.name}|{key}={value}"] = 1.0
return out
@dataclass
class LearnedRanker(CandidateRanker):
weights: dict[str, float] = field(default_factory=dict)
squared_gradients: dict[str, float] = field(default_factory=dict)
examples: int = 0
positives: int = 0
learning_rate: float = 0.3
l2: float = 1e-4
version: str | None = None
def probability(self, x: Mapping[str, float]) -> float:
z = sum(self.weights.get(name, 0.0) * value for name, value in x.items())
return 1.0 / (1.0 + math.exp(-max(-30.0, min(30.0, z))))
@property
def trust(self) -> float:
return min(1.0, self.examples / TRUST_EXAMPLES)
@property
def min_score(self) -> float:
return self.trust * LEARNED_MIN_SCORE + (1.0 - self.trust) * MIN_SCORE
def score(self, spec: FieldSpec, candidate: ExtractedValue) -> float:
heuristic = HeuristicRanker().score(spec, candidate)
if heuristic == 0.0 and self.trust < 1.0:
# What the rules rule out stays out until the ranker is fully trusted.
return 0.0
learned = self.probability(features(spec, candidate))
return self.trust * learned + (1.0 - self.trust) * heuristic
def learn(self, examples: Iterable["Example"], *, epochs: int = 1) -> None:
"""One pass (or `epochs`) of AdaGrad over the examples. Positives are
weighted by how rare they are among them, so a field with many wrong
candidates per right one still learns what right looks like."""
batch = list(examples)
if not batch:
return
positives = sum(1 for e in batch if e.label)
negatives = len(batch) - positives
positive_weight = min(5.0, negatives / positives) if positives else 1.0
for _ in range(epochs):
for example in batch:
x = example.x
error = self.probability(x) - (1.0 if example.label else 0.0)
scale = positive_weight if example.label else 1.0
for name, value in x.items():
gradient = scale * error * value + self.l2 * self.weights.get(name, 0.0)
accumulated = self.squared_gradients.get(name, 0.0) + gradient * gradient
self.squared_gradients[name] = accumulated
self.weights[name] = self.weights.get(name, 0.0) - self.learning_rate * gradient / (math.sqrt(accumulated) + 1e-8)
self.examples += len(batch)
self.positives += positives
def to_dict(self) -> dict[str, Any]:
return {
"weights": self.weights,
"squared_gradients": self.squared_gradients,
"examples": self.examples,
"positives": self.positives,
"learning_rate": self.learning_rate,
"l2": self.l2,
}
@classmethod
def from_dict(cls, data: Mapping[str, Any], *, version: str | None = None) -> "LearnedRanker":
return cls(
weights=dict(data.get("weights", {})),
squared_gradients=dict(data.get("squared_gradients", {})),
examples=int(data.get("examples", 0)),
positives=int(data.get("positives", 0)),
learning_rate=float(data.get("learning_rate", 0.3)),
l2=float(data.get("l2", 1e-4)),
version=version,
)
def copy(self) -> "LearnedRanker":
return LearnedRanker.from_dict(self.to_dict(), version=self.version)
def strongest(self, count: int = 15) -> list[tuple[str, float]]:
return sorted(self.weights.items(), key=lambda item: -abs(item[1]))[:count]
@dataclass(frozen=True)
class Example:
field: str
x: Mapping[str, float]
label: bool
def same_value(left: Any, right: Any) -> bool:
"""Whether an extracted value is the one a person said is right:
dates by day, numbers by value, text without case or accents."""
if left is None or right is None:
return left is None and right is None
if isinstance(left, (date, datetime)) or isinstance(right, (date, datetime)):
return _as_date(left) is not None and _as_date(left) == _as_date(right)
if isinstance(left, (int, float)) and not isinstance(left, bool) or isinstance(right, (int, float)) and not isinstance(right, bool):
try:
return abs(float(left) - float(right)) < 1e-6
except (TypeError, ValueError):
return False
return " ".join(fold(str(left)).split()) == " ".join(fold(str(right)).split())
def _as_date(value: Any) -> date | None:
if isinstance(value, datetime):
return value.date()
if isinstance(value, date):
return value
try:
return date.fromisoformat(str(value)[:10])
except ValueError:
return None
def examples_for(
specs: Sequence[FieldSpec], candidates: Mapping[str, Sequence[ExtractedValue]], truth: Mapping[str, Any]
) -> list[Example]:
"""Labelled examples from one record: every candidate of a field whose
right value is known is right (it equals that value) or wrong. A field
known to be empty makes all its candidates wrong; a field not in
`truth` teaches nothing."""
by_name = {spec.name: spec for spec in specs}
found = []
for name, value in truth.items():
spec = by_name.get(name)
if spec is None:
continue
for candidate in candidates.get(name, ()):
found.append(Example(name, features(spec, candidate), value is not None and same_value(candidate.value, value)))
return found
+258
View File
@@ -0,0 +1,258 @@
"""Read item scores from positioned rows in clinical tables."""
import re
from collections.abc import Iterator
from dataclasses import dataclass
from functools import cached_property
from itertools import groupby
from extraction.nlp.extractors import FieldExtractor, LabelIndex, SegmentLine, _folded_label, _fuzzy_hits
from extraction.nlp.fields import Evidence, ExtractedValue, FieldSpec
from extraction.nlp.text import fold
from extraction.nlp.vocabulary import SCORE_TABLES
COLUMN_TOLERANCE = 0.025
@dataclass(frozen=True)
class ScoreTable:
"""Captions, score syntax, and variant-specific column mappings."""
anchors: tuple[str, ...]
continuation_anchors: tuple[str, ...]
end_markers: tuple[str, ...]
variants: dict[str, dict[str, str]]
totals: dict[str, tuple[str, ...]]
value_pattern: str
missing_token: str
metadata: dict[str, dict[str, str]]
printed_metadata: dict[str, tuple[str, str]]
unmapped_items: dict[str, dict[str, str]]
aliases: dict[str, tuple[str, ...]]
@cached_property
def total_groups(self) -> dict[str, tuple[str, ...]]:
return {_folded_label(label): prefixes for label, prefixes in self.totals.items()}
@cached_property
def captions(self) -> dict[str, dict[str, str]]:
return {
variant: {
_folded_label(caption): name
for label, name in fields.items()
for caption in (label, *self.aliases.get(label, ()))
}
for variant, fields in self.variants.items()
}
@cached_property
def descriptions(self) -> frozenset[str]:
return frozenset(label for captions in self.captions.values() for label in captions)
@cached_property
def fields(self) -> frozenset[str]:
items = {name for fields in self.variants.values() for name in fields.values()}
return frozenset(items.union(*(fields.keys() for fields in self.metadata.values())))
def match(self, caption: str) -> frozenset[str]:
if caption in self.descriptions:
return frozenset((caption,))
scores = {
label: hit.score
for label in self.descriptions
for hit in _fuzzy_hits(caption, label, label)
if hit.start == 0 and hit.end == len(caption)
}
best = max(scores.values(), default=0.0)
return frozenset(label for label, score in scores.items() if score == best)
@dataclass(frozen=True)
class _Row:
caption: str
token: str
evidence: Evidence
labels: frozenset[str]
@dataclass(frozen=True)
class _Page:
lines: list[SegmentLine]
rows: list[_Row]
anchored: bool
restricted: bool
ended: bool
class ScoreTableExtractor(FieldExtractor):
"""Propose scores from the item set that best explains a table."""
method = "tabla_puntajes"
def __init__(self):
self.tables = {name: ScoreTable(**config) for name, config in SCORE_TABLES.items()}
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterator[ExtractedValue]:
for name, table in self.tables.items():
if spec.name not in table.fields:
continue
if name not in index.score_tables:
values, flags = self._read(table, index.lines)
index.score_tables[name] = values
index.flags.update(flags)
candidate = index.score_tables[name].get(spec.name)
if candidate is not None:
yield candidate
def _read(self, table: ScoreTable, lines: list[SegmentLine]) -> tuple[dict[str, ExtractedValue], set[str]]:
pages = [_read_page(table, list(group)) for _, group in
groupby(lines, key=lambda line: (line.document, line.page_number))]
best = None
ambiguous = False
for position, page in enumerate(pages):
following = pages[position + 1] if position + 1 < len(pages) else None
rows = page.rows
if (
following and page.rows and not page.restricted and not page.ended
and following.restricted and following.lines[0].document == page.lines[0].document
and following.lines[0].page_number == page.lines[0].page_number + 1
):
rows = rows + following.rows
if not any(row.labels for row in rows):
continue
ranked = sorted(
((_coverage(table, variant, rows), variant) for variant in table.variants),
reverse=True,
)
score, variant = ranked[0]
tied = len(ranked) > 1 and score == ranked[1][0]
if score < (0.5 if page.anchored else 0.75):
ambiguous |= tied or score < 0.5
continue
priority = (score, page.anchored)
if best is None or priority > best[0]:
best = priority, variant, tied, page, rows
if best is None:
return {}, {"modulo_ambiguo"} if ambiguous else set()
_, variant, tied, page, rows = best
if tied:
return {}, {"modulo_ambiguo"}
return self._values(table, variant, page, rows)
def _values(
self, table: ScoreTable, variant: str, page: _Page, rows: list[_Row]
) -> tuple[dict[str, ExtractedValue], set[str]]:
scores = {}
subtotal_items = {}
totals = {}
features = {}
for row in rows:
if row.token == table.missing_token:
continue
value = int(row.token)
if row.caption in table.total_groups:
totals.setdefault(table.total_groups[row.caption], []).append(value)
continue
if field := _field_for(table, variant, row):
scores.setdefault(field, (value, row.token, row.evidence))
elif prefix := _unmapped_prefix(table, variant, row):
subtotal_items[row.caption] = (prefix, value)
expected = set(table.total_groups.values())
totals_match = bool(totals) and expected == totals.keys()
for prefixes, printed in totals.items():
actual = sum(value for field, (value, _, _) in scores.items() if field.startswith(prefixes))
actual += sum(value for prefix, value in subtotal_items.values() if prefix in prefixes)
totals_match &= all(value == actual for value in printed)
confidence = 0.95 if totals_match else 0.6
if not totals_match:
features["totales_no_cuadran"] = True
evidence = next(row.evidence for row in rows if _field_for(table, variant, row))
for field, value in table.metadata.get(variant, {}).items():
if field in table.printed_metadata:
pattern, format_value = table.printed_metadata[field]
printed = next((match for line in page.lines if (match := re.search(pattern, line.folded))), None)
if printed and format_value.format(printed[1]) != value:
features["modulo_no_coincide"] = True
scores[field] = (value, str(value), evidence)
if features.get("modulo_no_coincide"):
confidence *= 0.8
return {
field: ExtractedValue(value, confidence, self.method, raw, source, features)
for field, (value, raw, source) in scores.items()
}, set(features)
def _field_for(table: ScoreTable, variant: str, row: _Row) -> str | None:
captions = table.captions[variant]
matches = {captions[label] for label in row.labels if label in captions}
return matches.pop() if len(matches) == 1 else None
def _unmapped_prefix(table: ScoreTable, variant: str, row: _Row) -> str | None:
return next((prefix for label, prefix in table.unmapped_items.get(variant, {}).items()
if _folded_label(label) in row.labels), None)
def _coverage(table: ScoreTable, variant: str, rows: list[_Row]) -> float:
matched = set()
foreign = 0
count = 0
for row in rows:
if row.caption in table.total_groups or _unmapped_prefix(table, variant, row):
continue
count += 1
if field := _field_for(table, variant, row):
matched.add(field)
else:
foreign += 1
return len(matched) / len(set(table.variants[variant].values())) - foreign / max(count, 1)
def _read_page(table: ScoreTable, lines: list[SegmentLine]) -> _Page:
anchors = {_folded_label(label) for label in table.anchors}
continuation = {_folded_label(label) for label in table.continuation_anchors}
end = {_folded_label(label) for label in table.end_markers}
headings = [_folded_label(line.text) for line in lines]
start = next((i for i, label in enumerate(headings) if label in anchors - continuation), 0)
cells = []
ended = False
for line, heading in zip(lines[start:], headings[start:]):
words = line.line.words
if len(words) >= 2:
token = fold(words[-1].text)
caption = _folded_label(" ".join(word.text for word in words[:-1]))
if token == table.missing_token or re.fullmatch(table.value_pattern, token) or (
token.isdecimal() and caption in table.total_groups
):
cells.append((line, words[-1].center, caption, token))
if caption in end:
ended = True
break
continue
cells.append((line, None, heading, ""))
if heading in end:
ended = True
break
positions = [x for _, x, _, _ in cells if x is not None]
if not positions:
return _Page(lines, [], bool(anchors.intersection(headings)), bool(continuation.intersection(headings)), ended)
column = max(positions, key=lambda x: (sum(abs(x - other) <= COLUMN_TOLERANCE for other in positions), x))
rows = []
previous = None
for line, x, caption, token in cells:
if x is None or abs(x - column) > COLUMN_TOLERANCE:
previous = line if x is None and caption not in anchors else None
continue
evidence = line.evidence()
labels = table.match(caption) if caption not in table.total_groups else frozenset()
if not labels and caption not in table.total_groups and previous is not None:
joined = f"{_folded_label(previous.text)} {caption}"
if joined_labels := table.match(joined):
caption, labels = joined, joined_labels
first, last = previous.line.bbox, line.line.bbox
bbox = [min(first.x0, last.x0), first.y0, max(first.x1, last.x1), last.y1]
evidence = Evidence(line.document, line.page_number, f"{previous.text} {line.text}",
[round(position, 4) for position in bbox])
rows.append(_Row(caption, token, evidence, labels))
previous = None
return _Page(lines, rows, bool(anchors.intersection(headings)), bool(continuation.intersection(headings)), ended)

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