Compare commits

..

272 Commits

Author SHA1 Message Date
ulises 4e7ae436c8 Submodule URLs relative to this repository's remote 2026-11-23 20:02:10 -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
Roberto Treviño Cervantes a82767605a [schema revision] fix disconnected work, half-edits and metadata collisions at CaCu/CaMa; added ADOS-2 columns to TEA 2026-09-24 10:31:06 -06:00
Klingsor0 3c181d9f24 alias de enums corregidos 2026-09-21 15:22:06 -06:00
Klingsor0 e71054c712 enums central 2026-09-21 15:21:25 -06:00
Klingsor0 dcf3b2f8a6 alias de enums 2026-09-21 15:21:03 -06:00
Klingsor0 a9e52a4968 readme de modelos orm 2026-09-21 15:20:30 -06:00
Klingsor0 db6b8894b4 modelos orm para cama 2026-09-21 15:19:20 -06:00
Klingsor0 ef03bb4a3d enums por entidad, cacu/enums.py los importa 2026-09-21 14:07:14 -06:00
Klingsor0 8da1bfa807 herencia de clase base para resolver nombres compartidos de tabalas de distintos proyectos 2026-09-21 13:54:04 -06:00
Klingsor0 fdb5323e6c primera version de modelos limpios, iguales a los del repo original, solo que con los opcionales corregidos 2026-09-21 13:32:04 -06:00
Klingsor0 187d060b71 Readmes de los docs del repo, fuente de verdad para los modelos 2026-09-21 13:15:07 -06:00
Roberto Treviño Cervantes 6fd7792e69 add persistance's and models' readme 2026-09-21 10:38:47 -06:00
Roberto Treviño Cervantes 474f72c08a initial commit 2026-09-21 10:24:06 -06:00
561 changed files with 26560 additions and 113138 deletions
+16 -7
View File
@@ -1,7 +1,16 @@
.venv
data
**/__pycache__
**/target
**/logs
WebApp
.git
# Read by the webapi build, whose context is the repo root.
.git/
WebApp/
**/__pycache__/
**/*.pyc
**/.venv/
**/*.egg-info/
**/.pytest_cache/
**/*.db
**/uv.lock
!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
-106
View File
@@ -1,106 +0,0 @@
name: ci
on:
push:
branches: [rebuild]
pull_request:
branches: [rebuild]
env:
# Submodule URLs are SSH; the runner reaches the same repos over the server's HTTP.
GIT_CONFIG_COUNT: 1
GIT_CONFIG_KEY_0: url.${{ github.server_url }}/ISSSTELEON/.insteadOf
GIT_CONFIG_VALUE_0: ssh://git@10.0.10.41:2222/ISSSTELEON/
jobs:
python: # the whole suite, nothing skipped: SQLite and PostgreSQL, OCR included
runs-on: ubuntu-latest
services:
postgres:
image: postgres:17
env:
POSTGRES_PASSWORD: postgres
POSTGRES_DB: platform
options: >-
--health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10
sqlserver: # the hospital's test source (synthetic.site): ArchivosUni and ResultadosSubrogados
image: mcr.microsoft.com/mssql/server:2022-CU20-ubuntu-22.04
env:
ACCEPT_EULA: "Y"
MSSQL_PID: Developer
MSSQL_SA_PASSWORD: Test-only-Site-1
options: >-
--health-cmd "/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P Test-only-Site-1 -Q 'select 1' -b"
--health-interval 5s --health-timeout 10s --health-retries 30
env:
POSTGRES_TEST_URL: postgresql://postgres:postgres@postgres:5432/platform
SITE_SQL_SERVER: mssql+pymssql://sa:Test-only-Site-1@sqlserver:1433
PGHOST: postgres
FHIR_VALIDATOR_JAR: /opt/fhir/validator_cli.jar
SYNTHEA_JAR: /opt/synthea/synthea.jar
steps:
- uses: actions/checkout@v4
- run: git submodule update --init
- run: |
apt-get update
apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-spa ghostscript \
default-jre-headless
- name: HL7 validator, pinned
run: |
mkdir -p /opt/fhir
curl -sLo /opt/fhir/validator_cli.jar https://github.com/hapifhir/org.hl7.fhir.core/releases/download/7.0.5/validator_cli.jar
echo "9dfe9f305b0f9389eceade2a4a1c9a2740d7b0e614066fdf07a78b571c76d92f /opt/fhir/validator_cli.jar" | sha256sum -c
- name: Synthea, pinned
run: |
mkdir -p /opt/synthea
curl -sLo /opt/synthea/synthea.jar https://github.com/synthetichealth/synthea/releases/download/v4.0.0/synthea-with-dependencies.jar
echo "ed43c20ad40ba5c3bc724503a5af032715fe3c491620b766148e7c2361e6ecc1 /opt/synthea/synthea.jar" | sha256sum -c
- uses: astral-sh/setup-uv@v5
- run: uv sync --locked
- run: uv run ruff check
- run: uv run ruff format --check
- run: uv run lint-imports
- run: uv run pytest -q -rs -m "not webapp" # the pages run in the web job
web:
runs-on: ubuntu-latest
services:
sqlserver: # the hospital's test source (synthetic.site): ArchivosUni and ResultadosSubrogados
image: mcr.microsoft.com/mssql/server:2022-CU20-ubuntu-22.04
env:
ACCEPT_EULA: "Y"
MSSQL_PID: Developer
MSSQL_SA_PASSWORD: Test-only-Site-1
options: >-
--health-cmd "/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P Test-only-Site-1 -Q 'select 1' -b"
--health-interval 5s --health-timeout 10s --health-retries 30
env:
SITE_SQL_SERVER: mssql+pymssql://sa:Test-only-Site-1@sqlserver:1433
SYNTHEA_JAR: /opt/synthea/synthea.jar
steps:
- uses: actions/checkout@v4
- run: git submodule update --init
- uses: astral-sh/setup-uv@v5
- uses: actions/setup-node@v4
with:
node-version: '24'
- name: Generated API client matches the API
run: |
uv sync --locked
uv run python -m webapi.openapi > WebApp/openapi.json
cd WebApp && npm ci && npm run api
git diff --exit-code -- . || { echo 'Run: npm run api (after exporting openapi.json)'; exit 1; }
- working-directory: WebApp
run: npx ng build
- working-directory: WebApp
run: npx ng test --watch=false
- name: Every page loads from the API (Playwright over a loaded platform)
run: |
apt-get update
apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-spa ghostscript \
default-jre-headless
mkdir -p /opt/synthea
curl -sLo /opt/synthea/synthea.jar https://github.com/synthetichealth/synthea/releases/download/v4.0.0/synthea-with-dependencies.jar
echo "ed43c20ad40ba5c3bc724503a5af032715fe3c491620b766148e7c2361e6ecc1 /opt/synthea/synthea.jar" | sha256sum -c
(cd WebApp && npx playwright install --with-deps chromium)
uv run pytest -q -rs -m webapp
+16 -9
View File
@@ -1,10 +1,17 @@
.venv/
__pycache__/
data/
*.db
.dlt/
.pytest_cache/
.ruff_cache/
compose.override.yml
!tests/fixtures/**/*.db
# 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/
+5 -8
View File
@@ -1,12 +1,9 @@
[submodule "WebApi"]
path = WebApi
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApi.git
branch = rebuild
[submodule "WebApp"]
path = WebApp
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApp.git
branch = rebuild
url = ../WebApp.git
[submodule "WebApi"]
path = WebApi
url = ../WebApi.git
[submodule "models"]
path = models
url = ssh://git@10.0.10.41:2222/ISSSTELEON/models.git
branch = rebuild
url = ../models.git
-26
View File
@@ -1,26 +0,0 @@
[importlinter]
root_packages =
core
persistance
models
webapi
synthetic
[importlinter:contract:layers]
name = WebApi and models sit on Persistance, which sits on Core
type = layers
layers =
webapi | models
persistance
core
[importlinter:contract:synthetic]
name = Product packages never import the synthetic hospital
type = forbidden
source_modules =
core
persistance
models
webapi
forbidden_modules =
synthetic
-1
View File
@@ -1 +0,0 @@
3.12
+8
View File
@@ -0,0 +1,8 @@
__pycache__/
*.pyc
.venv/
.pytest_cache/
.coverage
*.egg-info/
.env
uv.lock
-92
View File
@@ -1,92 +0,0 @@
"""CaCu clinical parameters: the one place they are set. dbt reads them as vars, the models
import them. Codes are the platform's (core.schema)."""
# Biopsy grades that count as CIN2+ (the outcome) and as invasive cancer.
CIN2_PLUS = ["HSIL", "CIS", "carcinoma"]
CANCER = ["carcinoma"]
CASE = ["CIS", "carcinoma"] # a biopsy this grade makes her a case: she has cancer
# The follow-up list: patients with a cytology sampled within the window before the cut-off.
FOLLOW_UP_WINDOWS = [1, 3, 6, 12] # months
FOLLOW_UP_WINDOW = 3
# Index cytology in the six KPNC categories, least to most severe.
KPNC = {
"NILM": ["NILM"],
"ASC-US": ["ASC-US"],
"LSIL": ["LSIL"],
"ASC-H": ["ASC-H"],
"AGC": ["AGC"],
"HSIL+": ["HSIL", "CIS", "adenocarcinoma"],
}
# The three categories used after colposcopy and after treatment.
KPNC_3 = {
"NILM": ["NILM"],
"ASC-US/LSIL": ["ASC-US", "LSIL"],
"High Grade": ["ASC-H", "AGC", "HSIL", "CIS", "adenocarcinoma"],
}
# The referral PPVs (core.cacu.measures.ReferralPPV). Cytology groups overlap: each holds its
# grade and every more severe squamous one. Histology levels are numerators over one
# denominator; the first is the measure's score.
PPV_CYTOLOGY = {
"ASCUS+": ["ASC-US", "LSIL", "ASC-H", "HSIL", "CIS"],
"LSIL+": ["LSIL", "ASC-H", "HSIL", "CIS"],
"HSIL+": ["HSIL", "CIS"],
}
PPV_HISTOLOGY = {"LIEBG+": ["LSIL", *CIN2_PLUS], "LIEAG+": CIN2_PLUS, "invasive": CANCER}
PREVIOUS_SCREENING = ["1_year_or_less", "2_years", "3_years_or_more"] # screening_history
REFERRAL_CYTOLOGY_DAYS = 365 # the referring cytology's report is at most this old
# Results that show a patient free of CIN2+ at a visit: a negative co-test (both within
# INDEX_SAMPLE_DAYS of each other), or a biopsy below the outcome grades.
KNOWN_NEGATIVE = {"bethesda": ["NILM", "ASC-US"], "hpv": ["negative"]}
INDEX_SAMPLE_DAYS = 30 # results this many days after the index sample still describe it
PREVALENT_WINDOW_DAYS = 6 * 365.25 / 12 # an outcome this soon was there at the index
DAYS_PER_YEAR = 365.25
# Recruitment windows (start inclusive, end exclusive).
RECRUITMENT = ("2018-01-01", "2027-01-01")
POST_TREATMENT_RECRUITMENT = ("2024-01-01", "2027-01-01")
POST_TREATMENT_INDEX_AFTER_DAYS = 90 # the index cytology comes this long after treatment
POST_TREATMENT_LOOKBACK_DAYS = 365 # a biopsy result this long before treatment is required
POST_COLPOSCOPY_VISIT = 1 # index: the k-th surveillance cytology after the colposcopy result
REFERRAL_LOOKBACK_DAYS = 365 # results this long before colposcopy are why she was referred
HYSTERECTOMY_ICD10 = ["Z907"]
# Inferred procedures, from clinical notes (ICD-10 without the dot).
# Specialties are the platform's codes; each site's pipeline maps its own names to them.
DIAGNOSIS_SPECIALTIES = ["colposcopy", "oncology_surgery"]
COLPOSCOPY_SPECIALTIES = ["colposcopy"]
SAMPLE_TO_DIAGNOSIS_DAYS = 120 # a diagnosis note this soon after a sample assesses it
DIAGNOSIS_ICD10 = [
"Z014", "Z124", "B977", "R876", "N87", "N870", "N871", "N872", "N879",
"D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539",
] # fmt: skip
HISTORY_ICD10 = ["D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539"]
TREATMENT_ICD10 = ["D06", "D060", "D061", "D067", "D069"]
COLPOSCOPY_ICD10 = ["R876", "N87", "N870", "N871", "N872", "N879", "B977"]
COLPOSCOPY_REASONS = ["ACUDE A COLPOSCOPIA", "COLPOSCOPIA"]
COLPOSCOPY_DIAGNOSES = ["VIRUS DEL PAPILOMA HUMANO"]
SURVEILLANCE_SPECIALTIES = ["family_medicine", "colposcopy"]
# Measures (core.measures): the horizons of the screening route, in days; an interval
# that hasn't ended after its horizon counts as not ended.
HORIZONS = {
"sample_to_report": 60, "sample_to_treatment": 180, "diagnosis_to_treatment": 60,
"sample_to_colposcopy": 60, "sample_to_biopsy": 60, "result_to_colposcopy": 60,
"colposcopy_to_biopsy": 60, "biopsy_to_diagnosis": 60,
} # fmt: skip
ABNORMAL = ["ASC-US", "ASC-H", "LSIL", "HSIL", "CIS"] # IND1
HIGH_GRADE = ["ASC-H", "HSIL", "CIS"] # cytology that should be confirmed by biopsy
DETECTION = ["HSIL", "CIS", "carcinoma"] # biopsy grades counted as detected (EU13)
BIOPSY_SEVERITY = ["normal", "LSIL", "HSIL", "CIS", "carcinoma"] # least to most severe
AGE_GROUPS = [(25, 34), (35, 44), (45, 54), (55, 64)] # plus "<25" and "65+"
RISK_BAND_MODEL = "cacu.cin2_pim" # whose risk at the index visit is banded (surveillance)
RISK_BANDS = [("low", 0.04), ("intermediate", 0.25), ("high", None)] # below each cut
def dbt_vars() -> dict:
"""What dbt reads (`var('cacu')`)."""
return {k.lower(): v for k, v in globals().items() if k.isupper()}
+12
View File
@@ -0,0 +1,12 @@
import sqlalchemy.orm as orm
from sqlmodel import SQLModel
registry = orm.registry()
class CaCuModel(SQLModel, registry=registry):
"""Base class for every CaCu table.
Uses its own SQLAlchemy registry so table names such as `notamedica`
don't collide with CaMa's tables of the same name.
"""
@@ -0,0 +1,34 @@
## biometria_hematica
Tabla de resultados de laboratorio, 1 fila por reporte de biometría hemática.
Fuente: extracción OCR y NLP sobre PDF vinculado en Estudios Laboratorio (BH1).
Join hacia ordenes_estudio por ord_numero_hospital (lógico, sin FK constraint). Join hacia paciente por pac_id_hospital (resuelto en carga).
| Columna | Fuente | Descripción |
| ------------------------------ | -------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `bh_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | Join lógico hacia paciente.pac_id, resuelto en carga, nulo si no hay match al momento de ingesta |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, obligatorio para el join lógico hacia paciente |
| `ord_numero_hospital` | Hospital, BH4 | Número de orden HIS, join lógico hacia ordenes_estudio.ord_numero_hospital |
| `bh_fecha` | Hospital, BH2 | Fecha de solicitud del estudio; pendiente de distinción con BH3 (fecha resultado) según ETL |
| `eritrocitos_mill_ul` | Derivado, OCR sobre PDF BH1 | Conteo de eritrocitos (millones/µL) |
| `hemoglobina_g_dl` | Derivado, OCR sobre PDF BH1 | Concentración de hemoglobina (g/dL) |
| `hematocrito_pct` | Derivado, OCR sobre PDF BH1 | Hematocrito como porcentaje del volumen sanguíneo |
| `vcm_fl` | Derivado, OCR sobre PDF BH1 | Volumen corpuscular medio (fL) |
| `hcm_pg` | Derivado, OCR sobre PDF BH1 | Hemoglobina corpuscular media (pg) |
| `chcm_g_dl` | Derivado, OCR sobre PDF BH1 | Concentración de hemoglobina corpuscular media (g/dL) |
| `rdw_pct` | Derivado, OCR sobre PDF BH1 | Amplitud de distribución eritrocitaria (%) |
| `leucocitos_mil_ul` | Derivado, OCR sobre PDF BH1 | Conteo total de leucocitos (miles/µL) |
| `neutrofilos_pct` | Derivado, OCR sobre PDF BH1 | Neutrófilos totales como porcentaje del diferencial leucocitario |
| `linfocitos_pct` | Derivado, OCR sobre PDF BH1 | Linfocitos como porcentaje del diferencial leucocitario |
| `monocitos_pct` | Derivado, OCR sobre PDF BH1 | Monocitos como porcentaje del diferencial leucocitario |
| `eosinofilos_pct` | Derivado, OCR sobre PDF BH1 | Eosinófilos como porcentaje del diferencial leucocitario |
| `basofilos_pct` | Derivado, OCR sobre PDF BH1 | Basófilos como porcentaje del diferencial leucocitario |
| `neutrofilos_segmentados_pct` | Derivado, OCR sobre PDF BH1 | Neutrófilos segmentados, desglose del diferencial neutrofílico (%) |
| `neutrofilos_banda_pct` | Derivado, OCR sobre PDF BH1 | Neutrófilos en banda, desglose del diferencial neutrofílico (%) |
| `metamielocitos_pct` | Derivado, OCR sobre PDF BH1 | Metamielocitos, desglose del diferencial neutrofílico (%) |
| `mielocitos_pct` | Derivado, OCR sobre PDF BH1 | Mielocitos, desglose del diferencial neutrofílico (%) |
| `plaquetas_mil_ul` | Derivado, OCR sobre PDF BH1 | Conteo de plaquetas (miles/µL) |
| `vpm_fl` | Derivado, OCR sobre PDF BH1 | Volumen plaquetario medio (fL) |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
@@ -0,0 +1 @@
from core.cacu.biometria_hematica.model import BiometriaHematica
@@ -0,0 +1,60 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import HOSPITAL_ID_LENGTH
class BiometriaHematica(CaCuModel, table=True):
"""
Modelo ORM para biometría hemática.
No hay validación en esta capa, se almacena laxamente.
"""
bh_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# Logical join, resolved on import by looking up paciente.pac_id_hospital
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
# Hospital patient id: links studies to patients
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# Logical join to ordenes_estudio.ord_numero_hospital, no FK constraint
ord_numero_hospital: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
bh_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
eritrocitos_mill_ul: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
hemoglobina_g_dl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
hematocrito_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
vcm_fl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
hcm_pg: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
chcm_g_dl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
rdw_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
leucocitos_mil_ul: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
linfocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
monocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
basofilos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
eosinofilos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
neutrofilos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
mielocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
metamielocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
neutrofilos_banda_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
neutrofilos_segmentados_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
plaquetas_mil_ul: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
vpm_fl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
+21
View File
@@ -0,0 +1,21 @@
## biopsia_cervical
Tabla de resultados histopatológicos, 1 fila por reporte de biopsia cervical.
Fuente: extracción OCR y NLP sobre PDF vinculado en ordenes_estudio.
Join hacia ordenes_estudio por ord_numero_hospital (lógico, sin FK constraint). Join hacia paciente por pac_id_hospital (resuelto en carga).
| Columna | Fuente | Descripción |
| -------------------- | -------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `bx_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | Join lógico hacia paciente.pac_id, resuelto en carga, nulo si no hay match al momento de ingesta |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, obligatorio para el join lógico hacia paciente |
| `ord_numero_hospital`| Hospital, HPC1, TVPH1 | Número de orden HIS, join lógico hacia ordenes_estudio.ord_numero_hospital |
| `cit_id` | Derivado, FK citologiacervical | Citología cervical previa asociada, nulo si no documentada en el sistema |
| `bx_fecha_solicitud` | Hospital, HPC2 | Fecha de solicitud de la biopsia |
| `bx_fecha_reporte` | Derivado, OCR regex fecha | Fecha de emisión del reporte histopatológico por el patólogo |
| `bx_cin_grado` | Derivado, NLP regex PDF HPC1 | Grado CIN extraído del diagnóstico histopatológico, variable objetivo principal para modelos de riesgo |
| `bx_observaciones` | Hospital, — | Observaciones del reporte |
| `bx_ocr_confianza` | Derivado, pipeline OCR | Score de confianza global del motor OCR sobre el documento |
| `bx_pdf_blob` | Derivado, extracción ETL HPC1 | Contenido binario del PDF del reporte histopatológico |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
@@ -0,0 +1 @@
from core.cacu.biopsia_cervical.model import BiopsiaCervical
+22
View File
@@ -0,0 +1,22 @@
from enum import Enum
class GradoCIN(str, Enum):
NORMAL = "NORMAL"
LIEBG = "LIEBG" # histological low-grade — CIN1 equivalent
LIEAG = "LIEAG" # histological high-grade — CIN2/3 equivalent
CIS = "CIS" # carcinoma in situ
CARCINOMA = "CARCINOMA" # invasive
DESCONOCIDO = "DESCONOCIDO"
GRADO_CIN_ALIAS: dict[str, str] = {
"LESIÓN INTRAEPITELIAL ESCAMOSA DE BAJO GRADO": "LIEBG",
"LESION INTRAEPITELIAL ESCAMOSA DE BAJO GRADO": "LIEBG",
"LESIÓN INTRAEPITELIAL ESCAMOSA DE ALTO GRADO": "LIEAG",
"LESION INTRAEPITELIAL ESCAMOSA DE ALTO GRADO": "LIEAG",
"CARCINOMA IN SITU": "CIS",
"CARCINOMA INVASOR": "CARCINOMA",
# CIN/NIC grades as reports write them; CIN2 and CIN3 are both LIEAG.
"CIN1": "LIEBG", "CIN 1": "LIEBG", "CIN-1": "LIEBG", "NIC1": "LIEBG", "NIC 1": "LIEBG", "NIC-1": "LIEBG",
"CIN2": "LIEAG", "CIN 2": "LIEAG", "CIN-2": "LIEAG", "NIC2": "LIEAG", "NIC 2": "LIEAG", "NIC-2": "LIEAG",
"CIN3": "LIEAG", "CIN 3": "LIEAG", "CIN-3": "LIEAG", "NIC3": "LIEAG", "NIC 3": "LIEAG", "NIC-3": "LIEAG",
}
+82
View File
@@ -0,0 +1,82 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
class BiopsiaCervical(CaCuModel, table=True):
"""
Modelo ORM para biopsia cervical.
No hay validación en esta capa, se almacena laxamente.
"""
bx_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# Logical join, resolved on import by looking up paciente.pac_id_hospital
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
# Hospital patient id, required: links studies to patients
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# Logical join to ordenes_estudio.ord_numero_hospital, no FK constraint
ord_numero_hospital: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
cit_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("citologiacervical.cit_id"), index=True),
)
bx_fecha_solicitud: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
bx_fecha_reporte: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
bx_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Observaciones",
)
bx_cin_grado: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_pdf_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(FileBlob),
)
bx_ocr_confianza: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
# VAR-03
bx_ocr_estatus: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="valor de core.ocr.OcrEstatus guardado como texto",
)
bx_ocr_requiere_revision: Optional[bool] = Field(
default=None,
sa_column=sa.Column(sa.Boolean),
)
bx_ocr_metodo_principal: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_ocr_metodo_alternativo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
@@ -0,0 +1,29 @@
## citologia_cervical
Tabla de resultados, 1 fila por reporte citológico. Fuente: TC1-TC10, resultado VPH integrado (TVPH1).
Join hacia ordenes_estudio por ord_numero_hospital (lógico, sin FK constraint). Join hacia paciente por pac_id_hospital (resuelto en carga).
| Columna | Fuente | Descripción |
| --------------------------- | ------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `cit_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | Join lógico hacia paciente.pac_id, resuelto en carga, nulo si no hay match al momento de ingesta |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, obligatorio para el join lógico hacia paciente |
| `ord_numero_hospital` | Hospital, TC1, TVPH1 | Número de orden HIS, join lógico hacia ordenes_estudio.ord_numero_hospital |
| `cit_fecha_toma` | Hospital, TC1 | Fecha en que se realizó la toma de muestra |
| `cit_fecha_reporte` | Derivado, reporte VPH u otro | Fecha de disponibilidad del resultado para el paciente |
| `cit_calidad_especimen` | Hospital, TC5 | Calidad del espécimen según criterios del sistema Bethesda 2014 |
| `cit_dx_lesion` | Hospital, TC6 | Diagnóstico citológico general para lesión intraepitelial o malignidad |
| `cit_celulas_escamosas` | Hospital, TC7 | Categoría de anomalía en células escamosas según Bethesda |
| `cit_carcinoma_invasor` | Hospital, TC8 | Presencia de carcinoma epidermoide invasor |
| `cit_celulas_glandulares` | Hospital, TC9 | Categoría de anomalía en epitelio glandular según Bethesda |
| `cit_condiciones_ginecoobs` | Hospital, TC2 | Condiciones gineco-obstétricas al momento de la toma (embarazo, DIU, menopausia, etc.) |
| `cit_exploracion` | Hospital, TC4 | Hallazgos a la exploración: aspecto del cérvix, flujo, lesiones visibles |
| `cit_observaciones` | Hospital, TC10 | Observaciones libres del citólogo no capturadas en los campos estructurados |
| `cit_vph_resultado` | Derivado, OCR sobre PDF TVPH1 | Resultado cualitativo del tamizaje VPH co-solicitado con la citología |
| `cit_vph_genotipo_16` | Derivado, OCR sobre PDF TVPH1 | Detección específica de genotipo VPH-16 |
| `cit_vph_genotipo_18` | Derivado, OCR sobre PDF TVPH1 | Detección específica de genotipo VPH-18 |
| `cit_vph_ocr_confianza` | Derivado, pipeline OCR | Score de confianza global del motor OCR sobre el PDF VPH |
| `cit_pdf_blob` | Derivado, extracción ETL | Contenido binario del PDF del resultado citológico |
| `cit_vph_pdf_blob` | Derivado, extracción ETL TVPH1 | Contenido binario del PDF del resultado VPH, su presencia distingue VPH no solicitado de extracción fallida |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
@@ -0,0 +1 @@
from core.cacu.citologia_cervical.model import CitologiaCervical
@@ -0,0 +1,46 @@
from enum import Enum
class CelulasEscamosas(str, Enum):
"""
Resultado de celulas escamosas.
Los resultados de celulas escamosas estan en el sistema de terminos Bethesda.
Se normalizan para usar sus abreviaturas.
"""
NORMAL = "NORMAL"
ASC_US = "ASC-US"
ASC_H = "ASC-H"
LIEBG = "LIEBG"
LIEAG = "LIEAG"
CIS = "CIS"
class CelulasGlandulares(str, Enum):
"""Resultado de células glandulares (Bethesda): atípicas o adenocarcinoma."""
AGC = "AGC"
ADENOCARCINOMA = "ADENOCARCINOMA"
CELULAS_ESCAMOSAS_ALIAS: dict[str,str] = {
# Long forms, as the hospital platform is expected to write them
"LESIÓN INTRAEPITELIAL ESCAMOSA DE BAJO GRADO (DISPLASIA LEVE Y/O VPH)": "LIEBG",
"LESION INTRAEPITELIAL ESCAMOSA DE BAJO GRADO (DISPLASIA LEVE Y/O VPH)": "LIEBG", # without accent
"LESIÓN INTRAEPITELIAL ESCAMOSA DE ALTO GRADO (DISPLASIA MODERADA Y GRAVE)": "LIEAG",
"LESION INTRAEPITELIAL ESCAMOSA DE ALTO GRADO (DISPLASIA MODERADA Y GRAVE)": "LIEAG",
"CARCINOMA IN SITU": "CIS",
# Bethesda "negative for intraepithelial lesion or malignancy" (NILM).
"NEGATIVO": "NORMAL",
"NILM": "NORMAL",
"NEGATIVO PARA LESION INTRAEPITELIAL O MALIGNIDAD": "NORMAL",
"NEGATIVO PARA LESIÓN INTRAEPITELIAL O MALIGNIDAD": "NORMAL",
}
CITO_CALIDAD_ESPECIMEN_ALIAS: dict[str,bool] = {
# String forms the source platforms are expected to send
"SATISFACTORIO": True,
"INSATISFACTORIO": False,
"1": True, # from JSON bool serialization
"0": False,
}
class ResultadoVPH(str, Enum):
POSITIVO = "POSITIVO"
NEGATIVO = "NEGATIVO"
INDETERMINADO = "INDETERMINADO" # extracted but ambiguous — not same as NULL
+122
View File
@@ -0,0 +1,122 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
class CitologiaCervical(CaCuModel, table=True):
cit_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# Logical join, resolved on import by looking up paciente.pac_id_hospital
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
# Hospital patient id, required: links studies to patients
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# Logical join to ordenes_estudio.ord_numero_hospital, no FK constraint
ord_numero_hospital: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
cit_fecha_toma: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha de toma de muestra",
)
cit_fecha_reporte: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha de disponibilidad de resultado para el paciente",
)
cit_calidad_especimen: Optional[str] = Field(
default=None
)
cit_pdf_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(FileBlob),
description="PDF de resultado",
)
cit_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Observaciones",
)
cit_condiciones_ginecoobs: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Condiciones gineco-obstétricas: embarazo, DIU, etc.",
)
cit_exploracion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Hallazgos en exploración",
)
cit_dx_lesion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="TC6 Diagnóstico citológico para lesión",
)
cit_celulas_glandulares: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="TC9 Anomalías del epitelio glandular",
)
cit_carcinoma_invasor: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="TC8 Carcinoma epidermoide invasor",
)
cit_celulas_escamosas: Optional[str] = Field(
default=None,
description="TC7 Anomalías de células escamosas"
)
cit_vph_pdf_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(FileBlob)
)
cit_vph_ocr_confianza: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float)
)
cit_vph_resultado: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text)
)
cit_vph_genotipo_16: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer)
)
cit_vph_genotipo_18: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer)
)
# VAR-03: besides the confidence, the status, the manual-review flag and the
# method (main or fallback) that produced the value.
cit_vph_ocr_estatus: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="valor de core.ocr.OcrEstatus guardado como texto",
)
cit_vph_ocr_requiere_revision: Optional[bool] = Field(
default=None,
sa_column=sa.Column(sa.Boolean),
)
cit_vph_ocr_metodo_principal: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
cit_vph_ocr_metodo_alternativo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
+6
View File
@@ -0,0 +1,6 @@
from core.cacu.paciente.enums import SexoBiologico, SEXO_BIOLOGICO_ALIAS
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),
)
-55
View File
@@ -1,55 +0,0 @@
"""CaCu's follow-up list (pure): who is on it at a cut-off day, her status then, and the order
it is read in. The list holds every patient with a cytology sampled within the window
(`cacu.FOLLOW_UP_WINDOWS` months) up to the cut-off."""
from collections.abc import Iterable
from datetime import date
from core import cacu
from core.cacu.measures import follow_up_status
# Risk outcomes the list can be ordered by: a model counts for the outcome its name starts.
OUTCOMES = {"cin2": "cacu.cin2", "cancer": "cacu.cancer"}
SORTS = ("-recent", *(f"-risk-{o}" for o in OUTCOMES))
DEFAULT_HORIZON = 5.0
WINDOWS = cacu.FOLLOW_UP_WINDOWS
STATUS_SYSTEM = "cacu-follow-up-status"
PROCEDURES = ("colposcopy", "treatment")
REPORT_FACTS = {"cervical_cytology": "diagnosis_days"} # days from the sample to its diagnosis
def status(row: dict, cutoff: date) -> str:
"""Her follow-up status by the end of the cut-off day."""
return follow_up_status(row, cutoff, through=True)
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
"""The rows (whoever had a cytology sampled in the window, most recent first), each with
her status."""
return [{**r, "status": status(r, cutoff)} for r in rows]
def current_risk(risks: Iterable[dict], outcome: str, horizon: float) -> float | None:
"""Her current risk of an outcome at a horizon (years): from the latest index date any
of the outcome's models scored her at; the highest when several did."""
prefix = OUTCOMES[outcome]
mine = [r for r in risks if r["model"].startswith(prefix) and r["horizon_years"] == horizon]
if not mine:
return None
latest = max(str(r["index_date"]) for r in mine)
return max(r["probability"] for r in mine if str(r["index_date"]) == latest)
def ordered(rows: list[dict], sort: str, risks: dict[str, list[dict]],
horizon: float) -> list[dict]: # fmt: skip
"""The list in reading order. `rows` come most recent first; by risk, highest first,
unscored patients last, ties kept most recent first."""
if sort == "-recent":
return rows
outcome = sort.removeprefix("-risk-")
def key(row: dict):
found = current_risk(risks.get(row["person_id"], []), outcome, horizon)
return (found is None, -(found or 0.0))
return sorted(rows, key=key)
+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(),)
-386
View File
@@ -1,386 +0,0 @@
"""CaCu's measures (`core.measures` evaluates them) and the follow-up status they stratify by."""
from dataclasses import dataclass
from datetime import date
import statistics
from core import cacu
from core.measures import (
NO_BIOPSY,
NO_DATA,
Composition,
Duration,
Measure,
Period,
Proportion,
Result,
RiskBand,
Result,
age_group,
as_day,
desc,
wilson,
)
def follow_up_status(row: dict, at: date, through: bool = False) -> str:
"""Where the patient was in her follow-up just before `at` (`through`: by the end of
`at`), from the first day of each step (`gold.cacu_follow_up`). A case already has
cancer; what follows her is survival."""
def by(first: str) -> bool:
day = as_day(row.get(first))
return day is not None and (day <= at if through else day < at)
for first, status in (("first_case", "case"), ("first_treatment", "post_treatment"),
("first_colposcopy", "post_colposcopy")): # fmt: skip
if by(first):
return status
return "pre_colposcopy"
def valid(row: dict) -> bool:
"""A cytology with a result, reported, of satisfactory (or unknown) adequacy."""
return row["result_date"] is not None and row.get("adequacy") != "unsatisfactory"
def latest(row: dict) -> tuple:
"""A patient's latest valid sample ranks highest."""
return valid(row), as_day(row["sample_date"]), row["sample_id"]
def latest_most_severe_biopsy(row: dict) -> tuple:
"""Her latest valid sample, then its most severe reported biopsy, the latest first."""
reported = row.get("biopsy_report_date") is not None
return (*latest(row), reported, row.get("severity") or 0,
desc(as_day(row.get("biopsy_report_date"))), desc(row.get("biopsy_id"))) # fmt: skip
def result(row: dict) -> str:
return row["result"] if valid(row) else NO_DATA
def histology(row: dict) -> str:
"""The chosen biopsy's histology (NO_BIOPSY without one reported)."""
if not valid(row):
return NO_DATA
if row.get("biopsy_report_date") is None:
return NO_BIOPSY
return row.get("histology") or NO_DATA
@dataclass(frozen=True)
class BiopsyRequests:
"""Recorded request units, classified at the event cutoff, not all HIS referrals."""
kind: str = "composition"
def evaluate(self, rows, period, cutoff):
chosen = {}
severity = {grade: i for i, grade in enumerate(cacu.BIOPSY_SEVERITY, 1)}
for row in rows:
request = as_day(row.get("request_date"))
if request not in period or request > cutoff:
continue
reported = as_day(row.get("report_date"))
if (row.get("rows_merged") or 0) > 1:
category, rank = "ambiguous", (4, 0, date.min)
elif reported is None or reported > cutoff:
category, rank = "pending", (0, 0, date.min)
elif reported < request:
category, rank = "inconsistent", (1, 0, reported)
elif row.get("histology") is None:
category, rank = "no_grade", (2, 0, reported)
elif row["histology"] not in severity:
category, rank = "unclassified", (2, 0, reported)
else:
grade = row["histology"]
category = "high_grade" if grade in cacu.CIN2_PLUS else "below_high_grade"
rank = (3, severity[grade], reported)
key = row["request_id"]
if key not in chosen or rank > chosen[key][0]:
chosen[key] = (rank, category)
categories = {}
for _, category in chosen.values():
cell = categories.setdefault(category, {"initial-population": 0})
cell["initial-population"] += 1
count = len(chosen)
return Result({"initial-population": count, "measure-observation": count},
strata={"category": categories})
@dataclass(frozen=True)
class DiagnosisDurations:
kind: str = "continuous-variable"
strata: tuple = (("diagnosis_code", None),)
def evaluate(self, rows, period, cutoff):
rule = Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=lambda r: r["history"] == 0)
overall = rule.evaluate(rows, period, cutoff)
grouped = {}
for row in {r["sample_id"]: r for r in rows}.values():
if (row["sample_date"] not in period or row["history"] != 0
or row.get("days_sample_diagnosis") is None
or as_day(row.get("diagnosis_date")) is None
or as_day(row["diagnosis_date"]) > cutoff):
continue
code = row.get("diagnosis_code") or "sin_codigo"
grouped.setdefault(code, []).append(row)
cells, scores = {}, {}
for code, group in grouped.items():
values = sorted(float(r["days_sample_diagnosis"]) for r in group)
median = statistics.median(values)
q1, q3 = (values[0], values[0]) if len(values) == 1 else (statistics.quantiles(values, n=4, method="inclusive")[0], statistics.quantiles(values, n=4, method="inclusive")[2])
descriptions = {r.get("diagnosis_description") for r in group if r.get("diagnosis_description")}
label = code + (" | " + next(iter(descriptions)) if len(descriptions) == 1 else "")
cells[label] = {"measure-observation": len(values)}
scores[label] = {"value": median, "unit": "d", "extension": [
{"url": "https://isssteleon.org/fhir/StructureDefinition/q1", "valueDecimal": q1},
{"url": "https://isssteleon.org/fhir/StructureDefinition/q3", "valueDecimal": q3}]}
return Result(overall.populations, overall.score, overall.score_extensions, overall.unit,
{"diagnosis_code": cells}, {"diagnosis_code": scores})
def referring_cytology(cytologies: list[dict], day: date) -> dict | None:
"""Her latest valid cytology sampled and reported before `day` (a result of that same
day doesn't count: dates can't say which came first), its report at most
REFERRAL_CYTOLOGY_DAYS old."""
found = [
c for c in cytologies
if valid(c) and c.get("result") is not None
and as_day(c["date"]) < day and as_day(c["result_date"]) < day
and (day - as_day(c["result_date"])).days <= cacu.REFERRAL_CYTOLOGY_DAYS
] # fmt: skip
return max(found, key=lambda c: (as_day(c["date"]), as_day(c["result_date"]),
c["sample_id"]), default=None) # fmt: skip
def screening_round(cytology: dict | None) -> str:
"""`subsequent`: screened before (as her form says) or already past colposcopy or
treatment at the sample; `initial`: the first screening of her life, before colposcopy."""
if cytology is None:
return NO_DATA
# a referral fact is dated `date`; a gold sample `sample_date`
status = follow_up_status(cytology, as_day(cytology.get("date") or cytology["sample_date"]))
history = cytology.get("screening_history")
if history in cacu.PREVIOUS_SCREENING or status in ("post_colposcopy", "post_treatment"):
return "subsequent"
return "initial" if history == "first_time" else NO_DATA
def hpv_result(row: dict) -> str | None:
"""Her high-risk HPV result on a sample; none when it has none."""
return None if row.get("hpv") is None else "positive" if row["hpv"] else "negative"
def hpv_groups(cytology: dict | None) -> list[str]:
"""The referral PPVs' HPV groups of a referring cytology: its result and, apart, each
genotype it was positive for (they overlap with `positive`, and may with each other)."""
row = cytology or {}
found = [name for name in (hpv_result(row),) if name]
found += [name for name in ("hpv_16", "hpv_18") if row.get(name)]
return found or [NO_DATA]
@dataclass(frozen=True)
class ReferralPPV:
"""Of the patients with a procedure in the period, those whose histology confirms the
first level of PPV_HISTOLOGY. Rows are facts (`gold.cacu_referral_facts`: `fact` is
cytology, colposcopy or biopsy, each dated `date`), so the referring cytology is chosen
among those known at the evaluation's `as_of`.
A patient counts once, with her first procedure of the period that qualifies: she wasn't
a case already (at her referring sample, or at the procedure without one) and, for the
biopsy PPV, a biopsy requested that day has a histology. Its histology is that of the
biopsies requested that day and reported by the cut-off; with none, not confirmed."""
procedure: str # "colposcopy" or "biopsy"
kind: str = "proportion"
strata: tuple[tuple[str, None], ...] = (
("referral_cytology", None), ("referral_hpv", None), ("histology_level", None),
("screening_round", None),
) # fmt: skip
def _units(self, rows: list[dict], period: Period, cutoff: date):
"""Per patient counted: the histologies of her procedure and its referring cytology."""
mine: dict[str, dict[str, list[dict]]] = {}
for row in rows:
mine.setdefault(row["person_id"], {}).setdefault(row["fact"], []).append(row)
for facts in mine.values():
procedures: dict[date, list[dict]] = {}
for row in facts.get(self.procedure, []):
day = as_day(row["date"])
if day in period and day <= cutoff:
procedures.setdefault(day, []).append(row)
for day in sorted(procedures):
found = {
b["histology"] for b in facts.get("biopsy", [])
if as_day(b["date"]) == day and b.get("histology") is not None
and b.get("report_date") is not None
and day <= as_day(b["report_date"]) <= cutoff
} # fmt: skip
if self.procedure == "biopsy" and not found:
continue
cytology = referring_cytology(facts.get("cytology", []), day)
at = day if cytology is None else as_day(cytology["date"])
if follow_up_status(cytology or procedures[day][0], at) == "case":
continue
yield found, cytology
break
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
units = list(self._units(rows, period, cutoff))
def cell(members: list, level: list[str]) -> dict[str, int]:
n = len(members)
return {"initial-population": n, "denominator": n,
"numerator": sum(bool(found & set(level)) for found, _ in members)} # fmt: skip
score_level = next(iter(cacu.PPV_HISTOLOGY.values()))
total = cell(units, score_level)
strata: dict[str, dict] = {name: {} for name, _ in self.strata}
if not units:
return Result(total, strata=strata)
groups: dict[str, list] = {}
for unit in units:
cytology = unit[1]
names = (
[NO_DATA]
if cytology is None
else [g for g, codes in cacu.PPV_CYTOLOGY.items() if cytology["result"] in codes]
)
for name in names:
groups.setdefault(name, []).append(unit)
strata["referral_cytology"] = {g: cell(u, score_level) for g, u in groups.items()}
by_hpv: dict[str, list] = {}
for unit in units:
for name in hpv_groups(unit[1]):
by_hpv.setdefault(name, []).append(unit)
strata["referral_hpv"] = {g: cell(u, score_level) for g, u in by_hpv.items()}
strata["histology_level"] = {
name: cell(units, level) for name, level in cacu.PPV_HISTOLOGY.items()
}
rounds: dict[str, list] = {}
for unit in units:
rounds.setdefault(screening_round(unit[1]), []).append(unit)
strata["screening_round"] = {g: cell(u, score_level) for g, u in rounds.items()}
k, n = total["numerator"], total["denominator"]
low, high = wilson(k, n)
return Result(total, k / n, {"ic-bajo": low, "ic-alto": high}, strata=strata)
H = cacu.HORIZONS
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no cervical cancer note before
AGE = ("age_group", lambda row, p: age_group(row.get("birth_date"), p.start, cacu.AGE_GROUPS))
STATUS = ("follow_up_status", lambda row, p: follow_up_status(row, p.start))
RESULT = ("result", lambda row, p: row["result"])
SCREENING = ("screening_round", lambda row, p: screening_round(row))
def results_of(wanted: str):
"""The results of the patients in one screening round (the others are in no group)."""
return (f"result_{wanted}",
lambda row, p: result(row) if screening_round(row) == wanted else None) # fmt: skip
def genotype(name: str):
"""A genotype's result on the chosen sample (in no group when not reported)."""
return (name, lambda row, p: None if row.get(name) is None
else "positive" if row[name] else "negative") # fmt: skip
def hpv_of(wanted: str):
"""The HPV results of the patients in one screening round."""
return (f"hpv_{wanted}",
lambda row, p: hpv_result(row) if screening_round(row) == wanted else None) # fmt: skip
MEASURES = {m.id: m for m in [
Measure("IND1", "Pacientes con citología anormal", "samples",
Proportion(lambda r: r["result"] in cacu.ABNORMAL), "decrease", group="principal"),
Measure("CACU_EU13", "Tasa de detección histopatológica", "sample_biopsies",
Proportion(lambda r: r.get("histology") in cacu.DETECTION
and r.get("biopsy_report_date") is not None,
strata=(AGE, STATUS)), group="principal"),
Measure("CACU_EU7", "Pacientes evaluadas por resultado de citología", "samples",
Composition(latest, result, strata=(
AGE, STATUS, SCREENING, results_of("initial"), results_of("subsequent")))),
Measure("CACU_VPH_GENOTIPO", "Resultados de VPH por genotipo", "hpv_reports",
Composition(lambda r: (as_day(r["report_date"]),), lambda r: r["category"],
unit="sample_id", date="sample_date"),
description="Reportes VPH con fecha de reporte y algún resultado VPH, por paciente y "
"fecha de toma; periodo por toma. Los nulos no son negativos; el contrato "
"booleano actual no representa resultados indeterminados."),
Measure("CACU_BIOPSIA_RESULTADOS", "Resultados de biopsia cervical", "biopsy_reports",
Composition(lambda r: (as_day(r["report_date"]),), lambda r: r["category"],
unit="biopsy_id", date="report_date"),
description="Reportes de biopsia por paciente y fecha de solicitud, incluidos los no "
"vinculados a una toma; periodo por fecha de reporte. El estrato no_data "
"identifica reportes sin grado; la distribución clasificable lo excluye."),
Measure("CACU_BIOPSIA_SOLICITUD_CONFIRMACION", "Resultados por solicitudes de biopsia registradas",
"biopsy_requests", BiopsyRequests(), known="order_known_at", supports_as_of=False,
description="Solicitudes de biopsia registradas por persona y fecha de solicitud, "
"según fecha de solicitud; resultados hasta el corte. La clave puede "
"agrupar órdenes y no se conocen cancelaciones ni cobertura de referencias. "
"No admite corte histórico de conocimiento as-of."),
# Her latest sample with an HPV result in the period, whatever its cytology says.
Measure("CACU_VPH", "Pacientes evaluadas por resultado de VPH", "samples",
Composition(lambda r: (as_day(r["sample_date"]), r["sample_id"]), hpv_result,
where=lambda r: r.get("hpv") is not None,
strata=(AGE, STATUS, genotype("hpv_16"), genotype("hpv_18"), SCREENING,
hpv_of("initial"), hpv_of("subsequent"))),
facts={"report_known_at": ("hpv", "hpv_16", "hpv_18")}),
Measure("CACU_CONFIRMACION_CITOLOGIA", "Confirmación histopatológica", "sample_biopsies",
Composition(latest_most_severe_biopsy, histology,
admit=lambda r: valid(r) and r["result"] in cacu.HIGH_GRADE,
strata=(RESULT,))),
# Rows become known with `known_at`; a report's values only with `report_known_at`.
*(Measure(f"CACU_VPP_{name}", f"VPP de la referencia a {title}", "referral_facts",
ReferralPPV(procedure),
facts={"report_known_at": ("result", "result_date", "adequacy",
"histology", "report_date",
"hpv", "hpv_16", "hpv_18")})
for name, title, procedure in (("COLPOSCOPIA", "colposcopía", "colposcopy"),
("BIOPSIA", "biopsia", "biopsy"))),
Measure("CACU_EU_TIEMPO_REPORTE", "Tiempo de toma a resultado de citología", "samples",
Duration("days_sample_result", "result_date", "sample_date", H["sample_to_report"],
ended="report_date"), "decrease"),
Measure("CACU_DIAS_TOMA_DIAGNOSTICO", "Tiempo de tamizaje a diagnóstico", "samples",
Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=NO_HISTORY), "decrease"),
Measure("CACU_TIEMPO_DIAGNOSTICO_CIE10", "Tiempo a diagnóstico por CIE-10 (exploratorio)",
"diagnosis_codes", DiagnosisDurations(),
description="Agrupa la fecha diagnóstica ya seleccionada por asociación temporal; no confirma vínculo clínico."),
Measure("CACU_DIAS_TOMA_TRATAMIENTO", "Tiempo de tamizaje a tratamiento", "samples",
Duration("days_sample_treatment", "treatment_date", "sample_date",
H["sample_to_treatment"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_DIAGNOSTICO_TRATAMIENTO", "Tiempo de diagnóstico a tratamiento", "samples",
Duration("days_diagnosis_treatment", "diagnosis_treatment_date", "diagnosis_date",
H["diagnosis_to_treatment"],
units=lambda r: r["history"] == 0 and r["diagnosis_date"] is not None),
"decrease"),
Measure("CACU_DIAS_TOMA_COLPOSCOPIA", "Tiempo de toma de muestra a colposcopía", "samples",
Duration("days_sample_colposcopy", "colposcopy_date", "sample_date",
H["sample_to_colposcopy"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_TOMA_BIOPSIA", "Tiempo de toma de muestra a resultado de biopsia", "samples",
Duration("days_sample_biopsy", "biopsy_date", "sample_date",
H["sample_to_biopsy"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_RESULTADO_COLPOSCOPIA", "Tiempo de resultado a colposcopía", "samples",
Duration("days_result_colposcopy", "result_colposcopy_date", "result_date",
H["result_to_colposcopy"],
units=lambda r: r["history"] == 0 and r["result_date"] is not None),
"decrease"),
Measure("CACU_DIAS_COLPOSCOPIA_BIOPSIA", "Tiempo de colposcopía a biopsia", "samples",
Duration("days_colposcopy_biopsy", "biopsy_date", "result_colposcopy_date",
H["colposcopy_to_biopsy"],
units=lambda r: r["history"] == 0
and r["result_colposcopy_date"] is not None), "decrease"),
Measure("CACU_DIAS_BIOPSIA_DIAGNOSTICO", "Tiempo de biopsia a diagnóstico", "samples",
Duration("days_biopsy_diagnosis", "biopsy_diagnosis_date", "biopsy_date",
H["biopsy_to_diagnosis"],
units=lambda r: r["history"] == 0 and r["biopsy_date"] is not None),
"decrease"),
Measure("CACU_RIESGO_BANDA", "Banda de riesgo de CIN2+ en vigilancia", "risk",
RiskBand(tuple(cacu.RISK_BANDS)),
periods=("semester",), params={"model": cacu.RISK_BAND_MODEL}),
]} # fmt: skip
+17
View File
@@ -0,0 +1,17 @@
from core.cacu.paciente.model import Paciente
from core.cacu.ordenes_estudio.model import OrdenesEstudio
from core.cacu.citologia_cervical.model import CitologiaCervical
from core.cacu.biopsia_cervical.model import BiopsiaCervical
from core.cacu.nota_medica.model import NotaMedica
from core.cacu.biometria_hematica.model import BiometriaHematica
from core.cacu.episodio_clinico.model import EpisodioClinico
__all__ = [
"Paciente",
"OrdenesEstudio",
"CitologiaCervical",
"BiopsiaCervical",
"NotaMedica",
"BiometriaHematica",
"EpisodioClinico",
]
+35
View File
@@ -0,0 +1,35 @@
## nota_medica
| Columna | Fuente | Descripción |
|---|---|---|
| `nm_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | FK lógica hacia `paciente.pac_id` — resuelto en carga, nulo si no hay match |
| `pac_id_hospital` | Hospital, DG1 | Identificador hospitalario del paciente |
| `nm_id_hospital` | Hospital, — | Identificador original de la nota en el HIS |
| `nm_nota_previa_id` | Hospital, — | FK autorreferencial para cadena de seguimiento |
| `nm_tipo_nota` | Hospital, NM1 | Tipo de visita |
| `nm_especialidad` | Hospital, NM1 | Especialidad médica que emite la nota |
| `nm_fecha` | Hospital, NM3 | Fecha de la consulta o procedimiento |
| `nm_medico_tratante` | Hospital, NM4 | Médico que emite la nota |
| `nm_motivo_consulta` | Hospital, NM10 | Motivo de consulta referido o registrado |
| `nm_interrogatorio` | Hospital, NM11 | Antecedentes relevantes e historia clínica |
| `nm_diagnostico_texto` | Hospital, NM2 | Diagnóstico clínico en texto libre |
| `nm_cie_codigo` | Hospital, NM17 | Código CIE-10 del diagnóstico principal |
| `nm_cie_descripcion` | Hospital, NM17 | Descripción del código CIE-10 |
| `nm_tratamiento_texto` | Hospital, NM12 | Descripción del tratamiento indicado |
| `nm_receta` | Hospital, NM14 | Medicamentos prescritos |
| `nm_plan_estudios` | Hospital, NM15 | Estudios planeados con orden, fecha y resultado esperado |
| `nm_pronostico` | Hospital, NM13 | Pronóstico registrado por el médico |
| `nm_observaciones` | Hospital, NM16 | Observaciones adicionales del médico |
| `nm_masa_corporal` | Hospital, NM5 | Peso corporal en la visita (kg) |
| `nm_talla` | Hospital, NM5 | Talla registrada en la visita (m) |
| `nm_imc_visita` | Derivado, pipeline | IMC calculado a partir de peso y talla |
| `nm_frecuencia_cardiaca` | Hospital, NM6 | Frecuencia cardíaca (lpm) |
| `nm_frecuencia_respiratoria` | Hospital, NM7 | Frecuencia respiratoria (rpm) |
| `nm_presion_arterial_sistolica` | Hospital, NM8 | Presión arterial sistólica (mmHg) |
| `nm_presion_arterial_diastolica` | Hospital, NM8 | Presión arterial diastólica (mmHg) |
| `nm_temperatura` | Hospital, NM9 | Temperatura corporal (°C) |
---
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
+1
View File
@@ -0,0 +1 @@
from core.cacu.nota_medica.model import NotaMedica
+40
View File
@@ -0,0 +1,40 @@
from enum import Enum
class TipoNota(str, Enum):
CONSULTA = "CONSULTA"
EGRESO = "EGRESO"
INGRESO = "INGRESO"
URG_EGRESO = "URG_EGRESO"
TIPO_NOTA_ALIAS: dict[str, str] = {
"URG. EGRESO": "URG_EGRESO",
}
class Especialidad(str, Enum):
MEDICINA_FAMILIAR = "MEDICINA_FAMILIAR"
CIRUGIA_ONCOLOGICA = "CIRUGIA_ONCOLOGICA"
CLINICA_MUJER_COLPOSCOPIA = "CLINICA_MUJER_COLPOSCOPIA"
ESPECIALIDAD_ALIAS: dict[str, str] = {
"MEDICINA FAMILIAR": "MEDICINA_FAMILIAR",
"CIRUGIA ONCOLOGICA": "CIRUGIA_ONCOLOGICA",
"CLINICA DE MUJER Y COLPOSCOPIA": "CLINICA_MUJER_COLPOSCOPIA",
}
class Parentesco(str, Enum):
AFILIADO = "Afiliado"
# Other values pending confirmation with the HIS administrator.
PARENTESCO_ALIAS: dict[str, str] = {
"AFILIADO": "Afiliado",
}
class Dependencia(str, Enum):
GOBIERNO = "GOBIERNO"
CALLES_Y_CAMINOS = "CALLES Y CAMINOS"
# Tentative values, pending confirmation with the HIS administrator.
DEPENDENCIA_ALIAS: dict[str, str] = {
"CALLES Y CAMINOS": "CALLES Y CAMINOS",
}
+124
View File
@@ -0,0 +1,124 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import HOSPITAL_ID_LENGTH
class NotaMedica(CaCuModel, table=True):
"""
Notas medicas del paciente
"""
nm_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="rellenado por el loader via lookup en paciente.pac_id_hospital; puede quedar nulo",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
description="DG1: identificador hospitalario obligatorio para vincular estudios con pacientes",
)
# Bounded and indexed: part of the natural key (with pac_id_hospital)
# the import layer upserts/merges notes on.
nm_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
)
nm_nota_previa_id: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_tipo_nota: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_especialidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
nm_medico_tratante: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_motivo_consulta: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_interrogatorio: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_diagnostico_texto: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_cie_codigo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_cie_descripcion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_tratamiento_texto: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_receta: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_plan_estudios: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_pronostico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_masa_corporal: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
nm_talla: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
nm_imc_visita: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
nm_frecuencia_cardiaca: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_frecuencia_respiratoria: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_presion_arterial_sistolica: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_presion_arterial_diastolica: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_temperatura: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
+23
View File
@@ -0,0 +1,23 @@
## ordenes_estudio
Al parecer no aparece en la plataforma el pdf de la orden del estudio emitido.
Tabla de órdenes, 1 fila por solicitud médica. Fuente: TC2 parcial, TVPH2, HPC2, NM3, NM4
| Columna | Fuente | Descripción |
| ------------------------ | ---------------------------- | ----------------------------------------------------------------------------------------------------- |
| `ord_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | FK hacia paciente.pac_id, resuelto en carga por lookup en paciente |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, desnormalizado para joins sin pasar por paciente |
| `ord_numero_hospital` | Hospital, TC1, TVPH1, HPC1 | Número de orden de 5 dígitos asignado por el HIS, índice único, join lógico hacia tablas de resultado |
| `ord_tipo_estudio` | Hospital, TC1, TVPH1, HPC1 | Tipo de estudio solicitado, texto libre, enum pendiente de confirmar con administrador |
| `ord_fecha` | Hospital, TVPH2, HPC2 | Fecha en que el médico emitió la orden |
| `ord_fecha_solicitud` | Hospital, TVPH2, HPC2 | Fecha sugerida por el médico para realizar el estudio |
| `ord_fecha_resultado` | Hospital, HPC3, TVPH4 | Fecha en que el resultado estuvo disponible, nulo hasta que llegue |
| `ord_estatus` | Hospital, TVPH4, HPC3 | Estatus de la orden, texto libre, enum pendiente de confirmar con administrador |
| `ord_diagnostico` | Hospital, ord | Diagnóstico presuntivo del médico (pantalla Asignar diagnóstico) |
| `ord_observaciones` | Hospital, — | Observaciones generales de la orden |
| `ord_especialidad` | Hospital, NM1 | Especialidad del médico solicitante |
| `ord_medico_solicitante` | Hospital, NM4 | Nombre o clave del médico tratante que emite la orden |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
@@ -0,0 +1 @@
from core.cacu.ordenes_estudio.model import OrdenesEstudio
+11
View File
@@ -0,0 +1,11 @@
from enum import Enum
class TipoEstudio(str, Enum):
BIOPSIA_CHICA = "BIOPSIA_CHICA"
SOLICITUD_PAPANICOLAO_BASE_LIQUIDA = "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA"
TIPO_ESTUDIO_ALIAS: dict[str, str] = {
"BIOPSIA CHICA": "BIOPSIA_CHICA",
"SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
"Solicitud de Papanicolao en Base Liquida": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
}
+77
View File
@@ -0,0 +1,77 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import HOSPITAL_ID_LENGTH
class OrdenesEstudio(CaCuModel, table=True):
"""
Modelo ORM para órdenes de estudio.
Condensa cabecera y detalle en una sola tabla.
Una orden corresponde a un único tipo de estudio.
El resultado (citología, biopsia) referencia esta tabla via ord_numero_hospital (join logico).
"""
ord_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("paciente.pac_id"), index=True),
)
# Denormalized so studies join without going through paciente
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
ord_numero_hospital: int = Field(
sa_column=sa.Column(sa.Integer, unique=True, index=True, nullable=False),
description="TC1/TVPH1/HPC1: numero de orden de 5 digitos asignado por el HIS",
)
ord_tipo_estudio: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Citología Base líquida, Biopsia Cervical"
)
ord_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha de emisión de la orden por el médico",
)
ord_fecha_solicitud: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha sugerida por el médico para realizar el estudio",
)
ord_fecha_resultado: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha en que el resultado estuvo disponible, nulo hasta que llegue",
)
ord_estatus: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="REALIZADO E INTERPRETADO",
)
ord_diagnostico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Diagnóstico, pantalla: Asignar diagnostico",
)
ord_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
ord_especialidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="",
)
ord_medico_solicitante: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Nombre o clave del médico NM4",
)
+15
View File
@@ -0,0 +1,15 @@
## pacientes
| Columna | Fuente | Descripción |
| ---------------------- | ----------------------- | ---------------------------------------------------------------------------------------------- |
| `pac_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, índice único, permite lookup desde tablas de resultado |
| `pac_fecha_nacimiento` | Hospital, DG2 | Fecha de nacimiento |
| `pac_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 |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cacu/`.
+1
View File
@@ -0,0 +1 @@
from core.cacu.paciente.model import Paciente
+18
View File
@@ -0,0 +1,18 @@
from enum import Enum
class SexoBiologico(str, Enum):
"""
Sexo biológico del paciente.
Hasta ahora asumieremos que se guarda como texto en el mercado de datos:
("Femenino", "Masculino").
Solamente se usará en la capa de validación.
"""
F = "Femenino"
M = "Masculino"
SEXO_BIOLOGICO_ALIAS: dict[str, str] = {
"F": "Femenino",
"M": "Masculino",
"FEMENINO": "Femenino",
"MASCULINO": "Masculino",
}
+54
View File
@@ -0,0 +1,54 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cacu.base import CaCuModel
from core.columns import HOSPITAL_ID_LENGTH
class Paciente(CaCuModel, table=True):
"""
Modelo ORM, solamente almacena.
Se reservan las validaciones de dominio para otra capa.
"""
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# The patient's original HIS id (DG1), uniquely indexed for lookups
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), unique=True, index=True, nullable=False),
)
pac_sexo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
# IND-01: required; age at each event of interest (clinical episode) is
# computed from it.
pac_fecha_nacimiento: date = Field(
sa_column=sa.Column(sa.Date, nullable=False),
)
# 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),
)
pac_codigo_postal: Optional[str] = Field(
default=None,
sa_column=sa.Column(
sa.CHAR(5),
),
description="Código postal de 5 dígitos",
)
pac_dependencia: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Dependencia",
)
pac_parentesco: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Parentesco",
)
-27
View File
@@ -1,27 +0,0 @@
"""Stage facts for a sample, using gold's dates and explicit biopsy links."""
def stage_facts(sample, biopsies, events, cutoff):
def day(value):
return str(value)[:10] if value is not None else None
start, end = day(sample['sample_date']), str(cutoff)[:10]
out = {}
for kind, column in [('colposcopy', 'colposcopy_date'), ('diagnosis', 'diagnosis_date')]:
selected = day(sample.get(column))
if selected and start < selected <= end:
matches = {(e['source_table'], e['source_id']) for e in events
if e['type'] == kind and day(e['date']) == selected}
out[kind] = ('inferred', selected) if len(matches) == 1 else ('ambiguous', None)
linked = [b for b in biopsies if day(b.get('cytology_sample_date')) == start
and day(b.get('request_date')) and start <= day(b['request_date']) <= end]
if len(linked) > 1 or any((b.get('rows_merged') or 0) > 1 for b in linked):
out['biopsy'] = ('ambiguous', None)
elif linked:
b = linked[0]
reported = day(b.get('report_date'))
if reported and reported < day(b['request_date']):
out['biopsy'] = ('ambiguous', None)
elif reported and reported <= end:
out['biopsy'] = ('structured', reported)
else:
out['biopsy'] = ('pending', None)
return out
-48
View File
@@ -1,48 +0,0 @@
"""CaMa clinical parameters: the one place they are set. dbt reads them as vars, the measures
and models import them. Codes are the platform's (core.catalog)."""
# BI-RADS, least to most severe: an incomplete study (0) asks for more and weighs more than a
# benign one; a 4 without subcategory weighs less than 4A.
BIRADS_SEVERITY = ["1", "2", "3", "0", "4", "4A", "4B", "4C", "5", "6"]
BIRADS_4_TO_6 = ["4", "4A", "4B", "4C", "5", "6"]
SUSPICIOUS = ["4", "4A", "4B", "4C", "5"] # should be confirmed by biopsy (not 6: already is)
# Biopsy grades, least to most severe.
BIOPSY_SEVERITY = ["benign", "in_situ", "invasive"]
CANCER = ["in_situ", "invasive"] # detected (detection rate)
INVASIVE = ["invasive"]
# Survival: indexed at the first biopsy reported with one of these, within the recruitment
# window (start inclusive, end exclusive).
SURVIVAL_GRADES = ["invasive"]
RECRUITMENT = ("2018-01-01", "2027-01-01")
# Inferred from clinical notes (ICD-10 without the dot; specialties are the platform's codes):
# - diagnosis: a note that resolves a mammogram, with a diagnosis ICD-10 by a diagnosing
# specialty;
# - history: a breast cancer note, whoever wrote it.
DIAGNOSIS_SPECIALTIES = ["oncology_surgery"]
HISTORY_ICD10 = [
"D05", "D050", "D051", "D057", "D059",
"C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509",
] # fmt: skip
DIAGNOSIS_ICD10 = [
"Z123", "N60", "N600", "N601", "N602", "N603", "N604", "N608", "N609", "N61", "N62", "N63",
"N64", "N640", "N641", "N642", "N643", "N644", "N645", "N648", "N649", "D24", "R92",
*HISTORY_ICD10,
] # fmt: skip
# Measures (core.measures): the horizons, in days; an interval that hasn't ended after its
# horizon counts as not ended. A diagnosis this soon after the mammogram resolves it.
HORIZONS = {"sample_to_report": 60, "to_diagnosis": 180}
AGE_GROUPS = [(40, 49), (50, 59), (60, 69)] # plus "<40" and "70+"
# The follow-up list: patients whose latest mammogram, taken within the window before the
# cut-off, is BI-RADS 4 to 6.
FOLLOW_UP_WINDOWS = [1, 3, 6, 12] # months
FOLLOW_UP_WINDOW = 3
def dbt_vars() -> dict:
"""What dbt reads (`var('cama')`)."""
return {k.lower(): v for k, v in globals().items() if k.isupper()}
+12
View File
@@ -0,0 +1,12 @@
import sqlalchemy.orm as orm
from sqlmodel import SQLModel
registry = orm.registry()
class CaMaModel(SQLModel, registry=registry):
"""Base class for every CaMa table.
Uses its own SQLAlchemy registry so table names such as `notamedica`
don't collide with CaCu's tables of the same name.
"""
@@ -0,0 +1,34 @@
## biometria_hematica
Tabla de resultados de laboratorio, 1 fila por reporte de biometría hemática.
Fuente: extracción OCR y NLP sobre PDF vinculado en Estudios Laboratorio (BH1).
Join hacia ordenes_estudio por ord_numero_hospital (lógico, sin FK constraint). Join hacia paciente por pac_id_hospital (resuelto en carga).
| Columna | Fuente | Descripción |
| ------------------------------ | -------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `bh_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | Join lógico hacia paciente.pac_id, resuelto en carga, nulo si no hay match al momento de ingesta |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, obligatorio para el join lógico hacia paciente |
| `ord_numero_hospital` | Hospital, BH4 | Número de orden HIS, join lógico hacia ordenes_estudio.ord_numero_hospital |
| `bh_fecha` | Hospital, BH2 | Fecha de solicitud del estudio; pendiente de distinción con BH3 (fecha resultado) según ETL |
| `eritrocitos_mill_ul` | Derivado, OCR sobre PDF BH1 | Conteo de eritrocitos (millones/µL) |
| `hemoglobina_g_dl` | Derivado, OCR sobre PDF BH1 | Concentración de hemoglobina (g/dL) |
| `hematocrito_pct` | Derivado, OCR sobre PDF BH1 | Hematocrito como porcentaje del volumen sanguíneo |
| `vcm_fl` | Derivado, OCR sobre PDF BH1 | Volumen corpuscular medio (fL) |
| `hcm_pg` | Derivado, OCR sobre PDF BH1 | Hemoglobina corpuscular media (pg) |
| `chcm_g_dl` | Derivado, OCR sobre PDF BH1 | Concentración de hemoglobina corpuscular media (g/dL) |
| `rdw_pct` | Derivado, OCR sobre PDF BH1 | Amplitud de distribución eritrocitaria (%) |
| `leucocitos_mil_ul` | Derivado, OCR sobre PDF BH1 | Conteo total de leucocitos (miles/µL) |
| `neutrofilos_pct` | Derivado, OCR sobre PDF BH1 | Neutrófilos totales como porcentaje del diferencial leucocitario |
| `linfocitos_pct` | Derivado, OCR sobre PDF BH1 | Linfocitos como porcentaje del diferencial leucocitario |
| `monocitos_pct` | Derivado, OCR sobre PDF BH1 | Monocitos como porcentaje del diferencial leucocitario |
| `eosinofilos_pct` | Derivado, OCR sobre PDF BH1 | Eosinófilos como porcentaje del diferencial leucocitario |
| `basofilos_pct` | Derivado, OCR sobre PDF BH1 | Basófilos como porcentaje del diferencial leucocitario |
| `neutrofilos_segmentados_pct` | Derivado, OCR sobre PDF BH1 | Neutrófilos segmentados, desglose del diferencial neutrofílico (%) |
| `neutrofilos_banda_pct` | Derivado, OCR sobre PDF BH1 | Neutrófilos en banda, desglose del diferencial neutrofílico (%) |
| `metamielocitos_pct` | Derivado, OCR sobre PDF BH1 | Metamielocitos, desglose del diferencial neutrofílico (%) |
| `mielocitos_pct` | Derivado, OCR sobre PDF BH1 | Mielocitos, desglose del diferencial neutrofílico (%) |
| `plaquetas_mil_ul` | Derivado, OCR sobre PDF BH1 | Conteo de plaquetas (miles/µL) |
| `vpm_fl` | Derivado, OCR sobre PDF BH1 | Volumen plaquetario medio (fL) |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
@@ -0,0 +1 @@
from core.cama.biometria_hematica.model import BiometriaHematica
@@ -0,0 +1,60 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import HOSPITAL_ID_LENGTH
class BiometriaHematica(CaMaModel, table=True):
"""
Modelo ORM para biometría hemática.
No hay validación en esta capa, se almacena laxamente.
"""
bh_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# Logical join, resolved on import by looking up paciente.pac_id_hospital
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
)
# Hospital patient id: links studies to patients
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
# Logical join to ordenes_estudio.ord_numero_hospital, no FK constraint
ord_numero_hospital: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
bh_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
eritrocitos_mill_ul: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
hemoglobina_g_dl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
hematocrito_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
vcm_fl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
hcm_pg: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
chcm_g_dl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
rdw_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
leucocitos_mil_ul: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
linfocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
monocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
basofilos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
eosinofilos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
neutrofilos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
mielocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
metamielocitos_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
neutrofilos_banda_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
neutrofilos_segmentados_pct: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
plaquetas_mil_ul: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
vpm_fl: Optional[float] = Field(default=None, sa_column=sa.Column(sa.Float))
+18
View File
@@ -0,0 +1,18 @@
## biopsia_mama
Una fila por reporte de biopsia mamaria · fuente: sistema estructurado + OCR/NLP sobre PDF histopatológico
| Columna | Fuente | Descripción |
| --------------------- | ------------------------------- | --------------------------------------------------------------------- |
| `bx_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital| FK hacia paciente, resuelto en el loader, nulo si no hay match |
| `pac_id_hospital` | Hospital, DG1 | Identificador hospitalario del paciente, desnormalizado |
| `ord_id` | Derivado, lookup en ordenes_estudio | FK formal a `ordenesestudio.ord_id`; el loader lo resuelve comparando `ord_numero_hospital` de este registro con `ordenes_estudio.ord_numero_hospital` |
| `ord_numero_hospital` | Hospital, BX1 | Número de orden asignado por el HIS; clave de join para resolver `ord_id` |
| `mast_id` | Derivado, lookup mast_id | FK hacia mastografia, nulo si la biopsia no tiene mastografía previa |
| `bx_fecha_solicitud` | Hospital, BX2 | Fecha de solicitud de la biopsia |
| `bx_fecha_reporte` | Hospital, BX3 | Fecha de emisión del reporte histopatológico |
| `bx_grado_histologico`| Derivado, OCR sobre PDF BX5 | Grado histológico del resultado |
| `bx_pdf_blob` | Hospital, BX5 | Contenido binario del PDF del reporte histopatológico |
| `bx_ocr_confianza` | Derivado, pipeline OCR | Score de confianza del OCR sobre este documento |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
+1
View File
@@ -0,0 +1 @@
from core.cama.biopsia_mama.model import BiopsiaMama
+19
View File
@@ -0,0 +1,19 @@
from enum import Enum
class GradoHistologicoMama(str, Enum):
BENIGNO = "BENIGNO"
CARCINOMA_IN_SITU = "CARCINOMA_IN_SITU"
CARCINOMA_INVASOR = "CARCINOMA_INVASOR"
DESCONOCIDO = "DESCONOCIDO"
class TipoEstudio(str, Enum):
BIOPSIA_CHICA = "BIOPSIA_CHICA"
SOLICITUD_PAPANICOLAO_BASE_LIQUIDA = "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA"
TIPO_ESTUDIO_ALIAS: dict[str, str] = {
"BIOPSIA CHICA": "BIOPSIA_CHICA",
"SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
"Solicitud de Papanicolao en Base Liquida": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
}
+153
View File
@@ -0,0 +1,153 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
class BiopsiaMama(CaMaModel, table=True):
"""
Modelo ORM para biopsia de mama. Fechas en sa.Date (sistema estructurado).
"""
bx_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
description="identificador hospitalario, obligatorio para vincular estudios con pacientes",
)
ord_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("ordenesestudio.ord_id"), index=True),
description="FK resuelto por el loader via lookup en ordenes_estudio.ord_numero_hospital",
)
ord_numero_hospital: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
mast_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("mastografia.mast_id"), index=True),
)
bx_fecha_solicitud: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
bx_fecha_reporte: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
bx_grado_histologico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_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(FileBlob),
)
bx_ocr_confianza: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
# VARM-04a
bx_ocr_estatus: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="valor de core.ocr.OcrEstatus guardado como texto",
)
bx_ocr_requiere_revision: Optional[bool] = Field(
default=None,
sa_column=sa.Column(sa.Boolean),
)
bx_ocr_metodo_principal: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_ocr_metodo_alternativo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
+6
View File
@@ -0,0 +1,6 @@
from core.cama.paciente.enums import SexoBiologico, SEXO_BIOLOGICO_ALIAS
from core.cama.nota_medica.enums import TipoNota, TIPO_NOTA_ALIAS, Especialidad, ESPECIALIDAD_ALIAS, Parentesco, PARENTESCO_ALIAS, Dependencia, DEPENDENCIA_ALIAS
from core.cama.ordenes_estudio.enums import TipoEstudio, TIPO_ESTUDIO_ALIAS
from core.cama.biopsia_mama.enums import GradoHistologicoMama
from core.cama.mastografia.enums import BIRADS, BIRADS_ALIAS
from core.cama.episodio_clinico.enums import TipoEpisodio, TIPO_EPISODIO_ALIAS
+17
View File
@@ -0,0 +1,17 @@
from enum import Enum
class TipoEpisodio(str, Enum):
"""IND-02: la unidad de análisis para evaluación de desempeño del
modelo es un episodio de tamizaje, diagnóstico o tratamiento."""
TAMIZAJE = "TAMIZAJE"
DIAGNOSTICO = "DIAGNOSTICO"
TRATAMIENTO = "TRATAMIENTO"
TIPO_EPISODIO_ALIAS: dict[str, str] = {
"SCREENING": "TAMIZAJE",
"DIAGNOSTIC": "DIAGNOSTICO",
"TREATMENT": "TRATAMIENTO",
}
+62
View File
@@ -0,0 +1,62 @@
from datetime import date, datetime, timezone
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import HOSPITAL_ID_LENGTH
class EpisodioClinico(CaMaModel, table=True):
"""IND-02/IND-03: clinical episode for CaMa. Same structure as
`core.cacu.episodio_clinico.model.EpisodioClinico`."""
episodio_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
)
tipo_episodio: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
description="valor de core.cama.episodio_clinico.enums.TipoEpisodio guardado como texto",
)
nm_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("notamedica.nm_id"), index=True),
description="nota médica cuyo contenido escrito origina/documenta el episodio",
)
cie10_codigo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
especialidad_medica: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
evento_fecha: date = Field(
sa_column=sa.Column(sa.Date, nullable=False),
description="fecha del evento de interés que define el episodio",
)
ventana_inicio: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
ventana_fin: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
episodio_anterior_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("episodioclinico.episodio_id"), index=True),
)
created_at: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc),
sa_column=sa.Column(sa.DateTime, nullable=False),
)
-77
View File
@@ -1,77 +0,0 @@
"""CaMa's follow-up list (pure): the patients whose latest mammogram reported by the cut-off
is BI-RADS 4 to 6 and was taken within the window, with where her biopsy stands and how soon
she should be seen.
Status, from the biopsies that mammogram led to, reported by the cut-off:
- cancer: one found cancer (in situ or invasive);
- pending_biopsy: none reported;
- biopsy_no_result: the latest has no grade;
- benign_biopsy: otherwise.
Priority: high for a cancer, or a pending biopsy after a BI-RADS 5 or 6; medium for any other
pending biopsy or one without result; low otherwise."""
from datetime import date
from core import cama
from core.measures import as_day
WINDOWS = cama.FOLLOW_UP_WINDOWS
SORTS = ("-recent",)
DEFAULT_HORIZON = None
STATUS_SYSTEM = "cama-follow-up-status"
PROCEDURES: tuple[str, ...] = ()
REPORT_FACTS: dict[str, str] = {}
URGENT = ["5", "6"] # BI-RADS whose pending biopsy is high priority
def _ranked(row: dict) -> tuple:
return as_day(row["exam_date"]), as_day(row["report_date"]), row["birads_rank"] or 0
def listed(rows: list[dict], start: date, cutoff: date) -> list[dict]:
"""From each reported mammogram and the biopsies it led to (`gold.cama_mammogram_biopsies`),
who is on the list, most recent mammogram first."""
latest: dict[str, dict] = {}
biopsies: dict[str, list[dict]] = {}
for row in rows:
exam, report = as_day(row["exam_date"]), as_day(row["report_date"])
if row["birads"] is None or report is None or not exam <= report <= cutoff:
continue
person = row["person_id"]
if person not in latest or _ranked(row) > _ranked(latest[person]):
latest[person] = row
found = as_day(row["biopsy_report_date"])
if found is not None and exam <= found <= cutoff:
biopsies.setdefault(row["mammogram_id"], []).append(row)
out = []
for person, row in latest.items():
if row["birads"] not in cama.BIRADS_4_TO_6 or not start <= as_day(row["exam_date"]):
continue
mine = biopsies.get(row["mammogram_id"], [])
shown = max(mine, key=lambda b: (as_day(b["biopsy_report_date"]), b["biopsy_id"]),
default=None) # fmt: skip
cancers = [as_day(b["biopsy_report_date"]) for b in mine if b["histology"] in cama.CANCER]
if cancers:
status, priority = "cancer", "high"
elif shown is None:
status = "pending_biopsy"
priority = "high" if row["birads"] in URGENT else "medium"
elif shown["histology"] is None:
status, priority = "biopsy_no_result", "medium"
else:
status, priority = "benign_biopsy", "low"
out.append({
"person_id": person, "birth_date": row["birth_date"], "status": status,
"priority": priority, "recent": as_day(row["exam_date"]),
"first_cancer": min(cancers, default=None),
}) # fmt: skip
return sorted(out, key=lambda r: (-r["recent"].toordinal(), r["person_id"]))
def status(row: dict, cutoff: date) -> None:
"""A patient's status exists only on the list."""
return None
def ordered(rows: list[dict], sort: str, risks: dict, horizon) -> list[dict]:
return rows
+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(),)
+18
View File
@@ -0,0 +1,18 @@
## mastografia
Una fila por estudio de mastografía · fuente: DICOM + OCR/NLP sobre PDF de interpretación
| Columna | Fuente | Descripción |
| --------------------- | ------------------------------- | ------------------------------------------------------------------ |
| `mast_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital| FK hacia paciente, resuelto en el loader, nulo si no hay match |
| `pac_id_hospital` | Hospital, DG1 | Identificador hospitalario del paciente, desnormalizado |
| `ord_id` | Derivado, lookup en ordenes_estudio | FK formal a `ordenesestudio.ord_id`; el loader lo resuelve comparando `ord_numero_hospital` de este registro con `ordenes_estudio.ord_numero_hospital` |
| `ord_numero_hospital` | Hospital, IM1 | Número de orden asignado por el HIS; clave de join para resolver `ord_id` |
| `mast_fecha_toma` | Hospital, IM2 | Fecha de toma del estudio entregada por el sistema DICOM |
| `mast_fecha_reporte` | Hospital, IM5 | Fecha del reporte de interpretación |
| `mast_calidad_imagen` | Derivado, OCR sobre PDF IM5 | Calidad técnica del estudio para interpretación |
| `mast_birads` | Derivado, OCR sobre PDF IM5 | Clasificación BI-RADS del reporte de interpretación |
| `mast_dicom_blob` | Hospital, IM6 | Contenido binario del archivo DICOM |
| `mast_interpretacion` | Hospital, IM5 | Enlace o referencia a la interpretación del radiólogo |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
+1
View File
@@ -0,0 +1 @@
from core.cama.mastografia.model import Mastografia
+35
View File
@@ -0,0 +1,35 @@
from enum import Enum
class BIRADS(str, Enum):
B0 = "B0" # incomplete
B1 = "B1" # negative
B2 = "B2" # benign
B3 = "B3" # probably benign
B4 = "B4" # suspicious
B5 = "B5" # highly suggestive of malignancy
B6 = "B6" # known biopsy-proven malignancy
BIRADS_ALIAS: dict[str, str] = {
"BIRADS 0": "B0", "BIRADS 1": "B1", "BIRADS 2": "B2",
"BIRADS 3": "B3", "BIRADS 4": "B4", "BIRADS 5": "B5", "BIRADS 6": "B6",
"BI-RADS 0": "B0", "BI-RADS 1": "B1", "BI-RADS 2": "B2",
"BI-RADS 3": "B3", "BI-RADS 4": "B4", "BI-RADS 5": "B5", "BI-RADS 6": "B6",
"0": "B0", "1": "B1", "2": "B2", "3": "B3", "4": "B4", "5": "B5", "6": "B6",
# The 4A/4B/4C subcategories (ACR BI-RADS lexicon) are common in real
# reports; this schema doesn't track them separately, so they fold into
# the base B4 rather than being rejected as out-of-catalog.
"BIRADS 4A": "B4", "BIRADS 4B": "B4", "BIRADS 4C": "B4",
"BI-RADS 4A": "B4", "BI-RADS 4B": "B4", "BI-RADS 4C": "B4",
"4A": "B4", "4B": "B4", "4C": "B4",
# Raw hospital source values (mastografia.mast_birads) spell the
# subcategory directly onto the code, e.g. "B4A" rather than "4A".
"B4A": "B4", "B4B": "B4", "B4C": "B4",
}
class GradoHistologicoMama(str, Enum):
BENIGNO = "BENIGNO"
CARCINOMA_IN_SITU = "CARCINOMA_IN_SITU"
CARCINOMA_INVASOR = "CARCINOMA_INVASOR"
DESCONOCIDO = "DESCONOCIDO"
+74
View File
@@ -0,0 +1,74 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import FileBlob, HOSPITAL_ID_LENGTH
class Mastografia(CaMaModel, table=True):
"""
Modelo ORM para mastografía.
"""
mast_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="join logico, resuelto por el loader via lookup en paciente.pac_id_hospital",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False, index=True),
description="identificador hospitalario, obligatorio para vincular estudios con pacientes",
)
ord_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("ordenesestudio.ord_id"), index=True),
description="FK resuelto por el loader via lookup en ordenes_estudio.ord_numero_hospital",
)
ord_numero_hospital: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="numero de orden HIS, join logico hacia ordenes_estudio.ord_numero_hospital",
)
mast_fecha_toma: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
mast_fecha_reporte: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
mast_calidad_imagen: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
mast_birads: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
mast_dicom_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(FileBlob),
)
mast_interpretacion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="enlace o referencia a la interpretación del radiólogo; formato pendiente",
)
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),
)
-114
View File
@@ -1,114 +0,0 @@
"""CaMa's measures (`core.measures` evaluates them), over the gold rows of
`persistance.measures`: mammograms, biopsies, and each mammogram with the biopsies it led to.
A mammogram's report, a biopsy's report and a diagnosis note can become known after the
mammogram itself; asked before then, a row has them empty (`facts`), so the mammogram counts
with no data instead of being left out."""
from core import cama
from core.measures import (
NO_BIOPSY,
NO_DATA,
Composition,
Duration,
Measure,
Proportion,
as_day,
desc,
)
H = cama.HORIZONS
REPORT = {"report_known_at": ("report_date", "birads", "birads_rank", "days_sample_report",
"report_diagnosis_date", "days_report_diagnosis")} # fmt: skip
DIAGNOSIS = {"diagnosis_known_at": ("diagnosis_date", "days_sample_diagnosis")}
BIOPSY = {"biopsy_known_at": ("biopsy_report_date", "histology", "histology_rank")}
def reported(row: dict) -> bool:
"""A mammogram with a reported BI-RADS."""
return row["birads"] is not None and row["report_date"] is not None
def most_severe(row: dict) -> tuple:
"""Her most severe reported mammogram ranks highest; on a tie, the latest."""
return reported(row), row["birads_rank"] or 0, as_day(row["exam_date"])
def then_its_most_severe_biopsy(row: dict) -> tuple:
"""Her most severe mammogram, then its most severe reported biopsy, the latest first."""
counted = row["biopsy_report_date"] is not None
return (*most_severe(row), counted, desc(row["histology_rank"]),
desc(as_day(row["biopsy_report_date"])), desc(row["biopsy_id"])) # fmt: skip
def birads(row: dict) -> str:
return row["birads"] if reported(row) else NO_DATA
def biopsy_histology(row: dict) -> str:
"""The chosen biopsy's grade (NO_BIOPSY when her mammogram led to none reported)."""
if row["biopsy_report_date"] is None:
return NO_BIOPSY
return row["histology"] or NO_DATA
def four_to_six(row: dict) -> bool:
return reported(row) and row["birads"] in cama.BIRADS_4_TO_6
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no breast cancer note before
BIRADS = ("birads", lambda row, p: row["birads"])
MEASURES = {m.id: m for m in [
Measure("CAMA_BIRADS", "Distribución de BI-RADS", "mammograms",
Composition(most_severe, birads, date="exam_date"), facts=REPORT),
Measure("CAMA_BIRADS456_PACIENTE",
"Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6", "mammograms",
Composition(most_severe, birads, admit=four_to_six, date="exam_date"), facts=REPORT),
Measure("CAMA_BIRADS456_MASTOGRAFIA",
"Porcentaje individual de mastografías con resultado BI-RADS 4, 5 y 6", "mammograms",
Composition(most_severe, birads, where=four_to_six, unit="mammogram_id",
date="exam_date"), facts=REPORT),
Measure("CAMA_BIRADS_CANCER_INVASOR", "BI-RADS de la mastografía previa a un cáncer invasor",
"biopsies",
Composition(lambda r: (r["birads"] is not None, as_day(r["report_date"]),
r["biopsy_id"]),
lambda r: r["birads"] or NO_DATA,
where=lambda r: r["histology"] in cama.INVASIVE, date="report_date"),
known="report_known_at"),
Measure("CAMA_BIOPSIAS", "Distribución de resultados de biopsia", "biopsies",
Composition(lambda r: (r["histology"] is not None, as_day(r["report_date"])),
lambda r: r["histology"] or NO_DATA, unit="biopsy_id",
date="report_date"),
known="report_known_at"),
Measure("CAMA_HISTOPATOLOGIA_BIRADS", "Resultado histopatológico por categoría BI-RADS",
"mammogram_biopsies",
Composition(then_its_most_severe_biopsy, biopsy_histology, admit=four_to_six,
strata=(BIRADS,), date="exam_date"),
facts=REPORT | BIOPSY),
Measure("CAMA_CONFIRMACION_BIRADS45", "Tasa de confirmación histopatológica",
"mammogram_biopsies",
Proportion(lambda r: r["biopsy_report_date"] is not None,
denominator=lambda r: r["report_date"] is not None
and r["birads"] in cama.SUSPICIOUS,
unit="mammogram_id", date="exam_date"),
"increase", group="principal", facts=REPORT | BIOPSY),
Measure("CAMA_TASA_DETECCION_HISTOPATOLOGICA", "Tasa de detección histopatológica",
"biopsies",
Proportion(lambda r: r["histology"] in cama.CANCER,
denominator=lambda r: r["histology"] in cama.BIOPSY_SEVERITY,
unit="biopsy_id", date="report_date"),
group="principal", known="report_known_at"),
Measure("CAMA_EU38A", "Días de la toma de la mastografía a su resultado", "mammograms",
Duration("days_sample_report", "report_date", "exam_date", H["sample_to_report"],
unit="mammogram_id", date="exam_date"), "decrease", facts=REPORT),
Measure("CAMA_DIAS_TOMA_DIAGNOSTICO", "Tiempo de tamizaje a diagnóstico", "mammograms",
Duration("days_sample_diagnosis", "diagnosis_date", "exam_date", H["to_diagnosis"],
units=NO_HISTORY, unit="mammogram_id", date="exam_date"),
"decrease", facts=DIAGNOSIS),
Measure("CAMA_DIAS_RESULTADO_DIAGNOSTICO", "Tiempo de resultado a diagnóstico", "mammograms",
Duration("days_report_diagnosis", "report_diagnosis_date", "report_date",
H["to_diagnosis"], units=NO_HISTORY, unit="mammogram_id",
date="report_date"),
"decrease", known="report_known_at"),
]} # fmt: skip
+21
View File
@@ -0,0 +1,21 @@
from core.cama.paciente.model import Paciente
from core.cama.ordenes_estudio.model import OrdenesEstudio
from core.cama.mastografia.model import Mastografia
from core.cama.biopsia_mama.model import BiopsiaMama
from core.cama.nota_medica.model import NotaMedica
from core.cama.biometria_hematica.model import BiometriaHematica
from core.cama.episodio_clinico.model import EpisodioClinico
from core.cama.tratamiento_mama.model import TratamientoMama
from core.cama.seguimiento_mama.model import SeguimientoMama
__all__ = [
"Paciente",
"OrdenesEstudio",
"Mastografia",
"BiopsiaMama",
"NotaMedica",
"BiometriaHematica",
"EpisodioClinico",
"TratamientoMama",
"SeguimientoMama",
]
+35
View File
@@ -0,0 +1,35 @@
## nota_medica
| Columna | Fuente | Descripción |
|---|---|---|
| `nm_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | FK lógica hacia `paciente.pac_id` — resuelto en carga, nulo si no hay match |
| `pac_id_hospital` | Hospital, DG1 | Identificador hospitalario del paciente |
| `nm_id_hospital` | Hospital, — | Identificador original de la nota en el HIS |
| `nm_nota_previa_id` | Hospital, — | FK autorreferencial para cadena de seguimiento |
| `nm_tipo_nota` | Hospital, NM1 | Tipo de visita |
| `nm_especialidad` | Hospital, NM1 | Especialidad médica que emite la nota |
| `nm_fecha` | Hospital, NM3 | Fecha de la consulta o procedimiento |
| `nm_medico_tratante` | Hospital, NM4 | Médico que emite la nota |
| `nm_motivo_consulta` | Hospital, NM10 | Motivo de consulta referido o registrado |
| `nm_interrogatorio` | Hospital, NM11 | Antecedentes relevantes e historia clínica |
| `nm_diagnostico_texto` | Hospital, NM2 | Diagnóstico clínico en texto libre |
| `nm_cie_codigo` | Hospital, NM17 | Código CIE-10 del diagnóstico principal |
| `nm_cie_descripcion` | Hospital, NM17 | Descripción del código CIE-10 |
| `nm_tratamiento_texto` | Hospital, NM12 | Descripción del tratamiento indicado |
| `nm_receta` | Hospital, NM14 | Medicamentos prescritos |
| `nm_plan_estudios` | Hospital, NM15 | Estudios planeados con orden, fecha y resultado esperado |
| `nm_pronostico` | Hospital, NM13 | Pronóstico registrado por el médico |
| `nm_observaciones` | Hospital, NM16 | Observaciones adicionales del médico |
| `nm_masa_corporal` | Hospital, NM5 | Peso corporal en la visita (kg) |
| `nm_talla` | Hospital, NM5 | Talla registrada en la visita (m) |
| `nm_imc_visita` | Derivado, pipeline | IMC calculado a partir de peso y talla |
| `nm_frecuencia_cardiaca` | Hospital, NM6 | Frecuencia cardíaca (lpm) |
| `nm_frecuencia_respiratoria` | Hospital, NM7 | Frecuencia respiratoria (rpm) |
| `nm_presion_arterial_sistolica` | Hospital, NM8 | Presión arterial sistólica (mmHg) |
| `nm_presion_arterial_diastolica` | Hospital, NM8 | Presión arterial diastólica (mmHg) |
| `nm_temperatura` | Hospital, NM9 | Temperatura corporal (°C) |
---
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
+1
View File
@@ -0,0 +1 @@
from core.cama.nota_medica.model import NotaMedica
+40
View File
@@ -0,0 +1,40 @@
from enum import Enum
class TipoNota(str, Enum):
CONSULTA = "CONSULTA"
EGRESO = "EGRESO"
INGRESO = "INGRESO"
URG_EGRESO = "URG_EGRESO"
TIPO_NOTA_ALIAS: dict[str, str] = {
"URG. EGRESO": "URG_EGRESO",
}
class Especialidad(str, Enum):
MEDICINA_FAMILIAR = "MEDICINA_FAMILIAR"
CIRUGIA_ONCOLOGICA = "CIRUGIA_ONCOLOGICA"
CLINICA_MUJER_COLPOSCOPIA = "CLINICA_MUJER_COLPOSCOPIA"
ESPECIALIDAD_ALIAS: dict[str, str] = {
"MEDICINA FAMILIAR": "MEDICINA_FAMILIAR",
"CIRUGIA ONCOLOGICA": "CIRUGIA_ONCOLOGICA",
"CLINICA DE MUJER Y COLPOSCOPIA": "CLINICA_MUJER_COLPOSCOPIA",
}
class Parentesco(str, Enum):
AFILIADO = "Afiliado"
# Other values pending confirmation with the HIS administrator.
PARENTESCO_ALIAS: dict[str, str] = {
"AFILIADO": "Afiliado",
}
class Dependencia(str, Enum):
GOBIERNO = "GOBIERNO"
CALLES_Y_CAMINOS = "CALLES Y CAMINOS"
# Tentative values, pending confirmation with the HIS administrator.
DEPENDENCIA_ALIAS: dict[str, str] = {
"CALLES Y CAMINOS": "CALLES Y CAMINOS",
}
+132
View File
@@ -0,0 +1,132 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import HOSPITAL_ID_LENGTH
class NotaMedica(CaMaModel, table=True):
"""
Notas medicas del paciente
"""
nm_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="rellenado por el loader via lookup en paciente.pac_id_hospital; puede quedar nulo",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
description="DG1: identificador hospitalario obligatorio para vincular estudios con pacientes",
)
# Bounded and indexed: part of the natural key (with pac_id_hospital)
# the import layer upserts/merges notes on.
nm_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
)
nm_nota_previa_id: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_tipo_nota: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_especialidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
nm_medico_tratante: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_motivo_consulta: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_interrogatorio: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_diagnostico_texto: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_cie_codigo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_cie_descripcion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_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),
)
nm_receta: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_plan_estudios: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_pronostico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_masa_corporal: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
nm_talla: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
nm_imc_visita: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
nm_frecuencia_cardiaca: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_frecuencia_respiratoria: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_presion_arterial_sistolica: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_presion_arterial_diastolica: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer),
)
nm_temperatura: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
+23
View File
@@ -0,0 +1,23 @@
## ordenes_estudio
Al parecer no aparece en la plataforma el pdf de la orden del estudio emitido.
Tabla de órdenes, 1 fila por solicitud médica. Fuente: TC2 parcial, TVPH2, HPC2, NM3, NM4
| Columna | Fuente | Descripción |
| ------------------------ | ---------------------------- | ----------------------------------------------------------------------------------------------------- |
| `ord_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id` | Derivado, lookup pac_id_hospital | FK hacia paciente.pac_id, resuelto en carga por lookup en paciente |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, desnormalizado para joins sin pasar por paciente |
| `ord_numero_hospital` | Hospital, TC1, TVPH1, HPC1 | Número de orden de 5 dígitos asignado por el HIS, índice único, join lógico hacia tablas de resultado |
| `ord_tipo_estudio` | Hospital, TC1, TVPH1, HPC1 | Tipo de estudio solicitado, texto libre, enum pendiente de confirmar con administrador |
| `ord_fecha` | Hospital, TVPH2, HPC2 | Fecha en que el médico emitió la orden |
| `ord_fecha_solicitud` | Hospital, TVPH2, HPC2 | Fecha sugerida por el médico para realizar el estudio |
| `ord_fecha_resultado` | Hospital, HPC3, TVPH4 | Fecha en que el resultado estuvo disponible, nulo hasta que llegue |
| `ord_estatus` | Hospital, TVPH4, HPC3 | Estatus de la orden, texto libre, enum pendiente de confirmar con administrador |
| `ord_diagnostico` | Hospital, ord | Diagnóstico presuntivo del médico (pantalla Asignar diagnóstico) |
| `ord_observaciones` | Hospital, — | Observaciones generales de la orden |
| `ord_especialidad` | Hospital, NM1 | Especialidad del médico solicitante |
| `ord_medico_solicitante` | Hospital, NM4 | Nombre o clave del médico tratante que emite la orden |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
@@ -0,0 +1 @@
from core.cama.ordenes_estudio.model import OrdenesEstudio
+12
View File
@@ -0,0 +1,12 @@
from enum import Enum
class TipoEstudio(str, Enum):
MASTOGRAFIA = "MASTOGRAFIA" # the study this domain orders
BIOPSIA_CHICA = "BIOPSIA_CHICA"
SOLICITUD_PAPANICOLAO_BASE_LIQUIDA = "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA"
TIPO_ESTUDIO_ALIAS: dict[str, str] = {
"BIOPSIA CHICA": "BIOPSIA_CHICA",
"SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
"Solicitud de Papanicolao en Base Liquida": "SOLICITUD_PAPANICOLAO_BASE_LIQUIDA",
}
+77
View File
@@ -0,0 +1,77 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import HOSPITAL_ID_LENGTH
class OrdenesEstudio(CaMaModel, table=True):
"""
Modelo ORM para órdenes de estudio.
Condensa cabecera y detalle en una sola tabla.
Una orden corresponde a un único tipo de estudio.
El resultado (citología, biopsia) referencia esta tabla via ord_numero_hospital (join logico).
"""
ord_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, sa.ForeignKey("paciente.pac_id"), index=True),
)
# Denormalized so studies join without going through paciente
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), nullable=False),
)
ord_numero_hospital: int = Field(
sa_column=sa.Column(sa.Integer, unique=True, index=True, nullable=False),
description="TC1/TVPH1/HPC1: numero de orden de 5 digitos asignado por el HIS",
)
ord_tipo_estudio: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Citología Base líquida, Biopsia Cervical"
)
ord_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha de emisión de la orden por el médico",
)
ord_fecha_solicitud: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha sugerida por el médico para realizar el estudio",
)
ord_fecha_resultado: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
description="Fecha en que el resultado estuvo disponible, nulo hasta que llegue",
)
ord_estatus: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="REALIZADO E INTERPRETADO",
)
ord_diagnostico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Diagnóstico, pantalla: Asignar diagnostico",
)
ord_observaciones: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
ord_especialidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="",
)
ord_medico_solicitante: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Nombre o clave del médico NM4",
)
+15
View File
@@ -0,0 +1,15 @@
## pacientes
| Columna | Fuente | Descripción |
| ---------------------- | ----------------------- | ---------------------------------------------------------------------------------------------- |
| `pac_id` | Derivado, autoincrement | Llave primaria sustituta |
| `pac_id_hospital` | Hospital, DG1 | Identificador del paciente en el HIS, índice único, permite lookup desde tablas de resultado |
| `pac_fecha_nacimiento` | Hospital, DG2 | Fecha de nacimiento |
| `pac_sexo` | Hospital, DG3 | Sexo biológico |
| `pac_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 |
La validación y normalización al importar están en `WebApi/webapi/imports/schemas/cama/`.
+1
View File
@@ -0,0 +1 @@
from core.cama.paciente.model import Paciente
+18
View File
@@ -0,0 +1,18 @@
from enum import Enum
class SexoBiologico(str, Enum):
"""
Sexo biológico del paciente.
Hasta ahora asumieremos que se guarda como texto en el mercado de datos:
("Femenino", "Masculino").
Solamente se usará en la capa de validación.
"""
F = "Femenino"
M = "Masculino"
SEXO_BIOLOGICO_ALIAS: dict[str, str] = {
"F": "Femenino",
"M": "Masculino",
"FEMENINO": "Femenino",
"MASCULINO": "Masculino",
}
+102
View File
@@ -0,0 +1,102 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import HOSPITAL_ID_LENGTH
class Paciente(CaMaModel, table=True):
"""
Modelo ORM, solamente almacena.
Se reservan las validaciones de dominio para otra capa.
"""
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
# The patient's original HIS id (DG1), uniquely indexed for lookups
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), unique=True, index=True, nullable=False),
)
pac_sexo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
# IND-01: required; age at each event of interest (clinical episode) is
# computed from it.
pac_fecha_nacimiento: date = Field(
sa_column=sa.Column(sa.Date, nullable=False),
)
# 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),
),
description="Código postal de 5 dígitos",
)
pac_dependencia: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Dependencia",
)
pac_parentesco: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
description="Parentesco",
)
+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),
)
-187
View File
@@ -1,187 +0,0 @@
"""The platform's clinical catalog: every study, the events it is made of, its fields, and the
code systems their values come from. It is data (the YAML files beside this module) and
changes only by a reviewed commit; nothing ships that it doesn't name.
Everything that validates, stores or serves a clinical value reads it: the pydantic model of
each study (what a pipeline's target checks rows against), the long silver tables and their
wide views (dbt), and the FHIR conformance resources the API serves.
"""
from datetime import date
from functools import cache
from pathlib import Path
from typing import Annotated, Any, ClassVar, Literal
import yaml
from pydantic import BaseModel, ConfigDict, Field, create_model, model_validator
HERE = Path(__file__).parent
EventClass = Literal["order", "encounter", "sample", "report", "part"]
# `file`: a document or signal kept whole (an EEG); silver holds its content hash, the
# platform keeps the content once (persistance.files).
ValueType = Literal["code", "boolean", "number", "date", "text", "file"]
class System(BaseModel):
model_config = ConfigDict(extra="forbid")
url: str
title: str
external: bool = False # a standard system we name but don't publish
class Event(BaseModel):
model_config = ConfigDict(extra="forbid")
date: str # the field that dates it
parent: EventClass | None = None
class FieldDef(BaseModel):
model_config = ConfigDict(extra="forbid")
type: ValueType
event: EventClass
title: str
system: str | None = None
codes: dict[str, str] = {} # allowed code -> display; empty: any code of `system`
pattern: str | None = None
unit: str | None = None
required: bool = False
@model_validator(mode="after")
def _codes_have_a_system(self):
if self.type == "code" and self.system is None:
raise ValueError("a code field names its system")
if self.type != "code" and (self.codes or self.system):
raise ValueError("only code fields take a system and codes")
return self
class Study(BaseModel):
model_config = ConfigDict(extra="forbid")
title: str
key: list[str] # fields that, with the person, identify one study instance
events: dict[EventClass, Event]
fields: dict[str, FieldDef]
@model_validator(mode="after")
def _consistent(self):
for name in self.key:
if name not in self.fields:
raise ValueError(f"key field {name} is not a field")
for cls, event in self.events.items():
if self.fields.get(event.date, None) is None or self.fields[event.date].type != "date":
raise ValueError(f"{cls}: its date {event.date} is not a date field")
if event.parent and event.parent not in self.events:
raise ValueError(f"{cls}: parent {event.parent} is not an event")
for name, f in self.fields.items():
if f.event not in self.events:
raise ValueError(f"{name}: event {f.event} is not one of the study's")
return self
def _load(name: str) -> dict:
return yaml.safe_load((HERE / f"{name}.yaml").read_text(encoding="utf-8"))
@cache
def systems() -> dict[str, System]:
return {k: System.model_validate(v) for k, v in _load("systems").items()}
@cache
def files() -> dict[str, list[str]]:
"""Each catalog file (a domain, or `common` to all) and the studies it defines."""
return {
path.stem: list(_load(path.stem))
for path in sorted(HERE.glob("*.yaml"))
if path.stem != "systems"
}
def of_domain(domain: str) -> list[str]:
"""The studies a domain serves: its own and the common ones."""
return [*files().get(domain, []), *files().get("common", [])]
@cache
def studies() -> dict[str, Study]:
"""Every study of every catalog file, by name (names are unique across files)."""
found: dict[str, Study] = {}
for path in sorted(HERE.glob("*.yaml")):
if path.stem == "systems":
continue
for name, spec in _load(path.stem).items():
if name in found:
raise ValueError(f"study {name} is defined twice")
study = Study.model_validate(spec)
unknown = {f.system for f in study.fields.values() if f.system} - set(systems())
if unknown:
raise ValueError(f"{name}: unknown systems {sorted(unknown)}")
found[name] = study
return found
class Record(BaseModel):
"""One row of a study, as a pipeline's target receives it."""
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
key: ClassVar[tuple[str, ...]] = ()
study: ClassVar[str] = ""
_TYPES: dict[str, Any] = {
"boolean": bool,
"number": float,
"date": date,
"text": str,
"file": str,
} # fmt: skip (a file field holds its content hash)
def _annotation(f: FieldDef) -> Any:
if f.type == "code" and f.codes:
kind: Any = Literal[tuple(f.codes)] # type: ignore[valid-type]
elif f.type == "code":
kind = Annotated[str, Field(pattern=f.pattern)] if f.pattern else str
else:
kind = _TYPES[f.type]
return kind if f.required else kind | None
@cache
def model(study: str) -> type[Record]:
"""The pydantic model a row of this study is checked against."""
spec = studies()[study]
fields = {
name: (_annotation(f), ... if f.required else None) for name, f in spec.fields.items()
}
found = create_model(study, __base__=Record, **fields) # type: ignore[call-overload]
found.key = tuple(spec.key)
found.study = study
return found
def value_column(f: FieldDef) -> str:
"""The typed column of the long observation table a field's value is stored in."""
return {"boolean": "value_bool", "number": "value_num", "date": "value_date"}.get(
f.type, "value_text"
)
def dbt_vars() -> dict:
"""What dbt reads (`var('catalog')`): each study's key, events and typed fields."""
return {
name: {
"key": s.key,
"events": {c: e.model_dump() for c, e in s.events.items()},
"fields": {
f: {
"type": d.type,
"event": d.event,
"column": value_column(d),
"codes": list(d.codes),
}
for f, d in s.fields.items()
},
}
for name, s in studies().items()
}
-117
View File
@@ -1,117 +0,0 @@
# Cervical cancer screening.
cervical_cytology:
title: Citología cervical
key: [sample_date]
events:
sample: {date: sample_date}
report: {date: report_date, parent: sample}
fields:
sample_date: {type: date, event: sample, title: Fecha de toma, required: true}
screening_history:
type: code
event: sample
title: Detección de cáncer de cérvix
system: cervical-screening-history
codes:
first_time: Primera vez en la vida
1_year_or_less: Un año o menos
2_years: 2 años
3_years_or_more: 3 o más años
# Condiciones ginecoobstétricas a la detección, as recorded at the sample: true when the
# form says it; otherwise unknown, never false (the source records only one of them).
gyn_puerperium: {type: boolean, event: sample, title: "Puerperio postparto o postaborto"}
gyn_pregnancy: {type: boolean, event: sample, title: "Embarazo actual"}
gyn_iud: {type: boolean, event: sample, title: "DIU in situ"}
gyn_hormonal_treatment: {type: boolean, event: sample, title: "Tratamiento hormonal"}
gyn_other_treatment: {type: boolean, event: sample, title: "Otro tratamiento ginecológico"}
gyn_postmenopause: {type: boolean, event: sample, title: "Posmenopausia"}
gyn_hysterectomy: {type: boolean, event: sample, title: "Histerectomía"}
gyn_not_applicable: {type: boolean, event: sample, title: "Condiciones ginecoobstétricas: no aplica"}
# Actualmente presenta, recorded like the conditions above: true or unknown, never false.
presents_discharge: {type: boolean, event: sample, title: "Actualmente presenta: flujo"}
presents_vulvar_pruritus: {type: boolean, event: sample, title: "Actualmente presenta: prurito o ardor vulvar"}
presents_abnormal_bleeding: {type: boolean, event: sample, title: "Actualmente presenta: sangrado anormal"}
presents_none: {type: boolean, event: sample, title: "Actualmente presenta: ninguno"}
cervix_exam:
type: code
event: sample
title: A la exploración se observa
system: cervix-exam
codes:
healthy: Cuello sano
abnormal_with_lesion: Cuello anormal con lesión
not_visible: No se observa cuello
report_date: {type: date, event: report, title: Fecha de reporte}
adequacy:
type: code
event: report
title: Calidad de la muestra
system: adequacy
codes: {satisfactory: Satisfactoria, unsatisfactory: Insatisfactoria}
result:
type: code
event: report
title: Resultado (Bethesda)
system: bethesda
codes:
NILM: Negativo para lesión intraepitelial o malignidad
ASC-US: Células escamosas atípicas de significado indeterminado
ASC-H: Células escamosas atípicas, no se descarta LIEAG
LSIL: Lesión intraepitelial escamosa de bajo grado
HSIL: Lesión intraepitelial escamosa de alto grado
CIS: Carcinoma in situ
hpv: {type: boolean, event: report, title: VPH de alto riesgo}
hpv_16: {type: boolean, event: report, title: VPH 16}
hpv_18: {type: boolean, event: report, title: VPH 18}
# The cytologist's additional findings, free text on the form (known with the report).
# A finding is true when the text states it; otherwise unknown, never false.
cyto_findings_text: {type: text, event: report, title: Hallazgos adicionales}
cyto_inflammation: {type: boolean, event: report, title: "Inflamación"}
cyto_reactive_changes: {type: boolean, event: report, title: "Cambios reactivos"}
cyto_bacterial_vaginosis_flora: {type: boolean, event: report, title: "Flora sugestiva de vaginosis bacteriana"}
cyto_candida: {type: boolean, event: report, title: "Microorganismos compatibles con Candida sp"}
cyto_bacillary_flora_cytolysis: {type: boolean, event: report, title: "Aumento de la flora bacilar con citólisis"}
cyto_intermediate_cytolysis: {type: boolean, event: report, title: "Citólisis de las células intermedias"}
cyto_trichomonas: {type: boolean, event: report, title: "Trichomonas vaginalis"}
cyto_leptothrix: {type: boolean, event: report, title: "Microorganismos compatibles con Leptothrix"}
cyto_actinomyces_organisms: {type: boolean, event: report, title: "Microorganismos compatibles con Actinomyces sp"}
cyto_actinomyces_changes: {type: boolean, event: report, title: "Cambios celulares compatibles con Actinomyces sp"}
cyto_herpes_simplex_changes: {type: boolean, event: report, title: "Cambios celulares compatibles con virus herpes simple"}
cyto_squamous_tubular_metaplasia: {type: boolean, event: report, title: "Metaplasia escamosa tubular"}
cyto_keratotic_changes: {type: boolean, event: report, title: "Cambios queratósicos"}
cyto_pregnancy_changes: {type: boolean, event: report, title: "Cambios asociados al embarazo"}
cyto_atrophy: {type: boolean, event: report, title: "Atrofia"}
cyto_hypoestrogenism: {type: boolean, event: report, title: "Hipoestrogenismo"}
cyto_radiotherapy_effect: {type: boolean, event: report, title: "Efecto de radioterapia"}
cyto_iud_changes: {type: boolean, event: report, title: "Cambios compatibles con dispositivo intrauterino"}
cyto_post_hysterectomy_glandular_cells: {type: boolean, event: report, title: "Células glandulares post-histerectomía"}
cyto_bacteria: {type: boolean, event: report, title: "Bacterias"}
cyto_herpes_image: {type: boolean, event: report, title: "Imagen del virus del herpes"}
cyto_fungi: {type: boolean, event: report, title: "Hongos"}
cyto_radiation: {type: boolean, event: report, title: "Cambios reactivos: radiación"}
cyto_repair: {type: boolean, event: report, title: "Cambios reactivos: reparación"}
cyto_iud_effect: {type: boolean, event: report, title: "Efecto del DIU"}
cyto_endometrial_cells_40_plus: {type: boolean, event: report, title: "Células endometriales, 40 años o más"}
cyto_findings_none: {type: boolean, event: report, title: "Hallazgos adicionales: ninguno"}
cervical_biopsy:
title: Biopsia cervical
key: [request_date]
events:
order: {date: request_date}
report: {date: report_date, parent: order}
fields:
request_date: {type: date, event: order, title: Fecha de solicitud, required: true}
cytology_sample_date: {type: date, event: order, title: Toma de la citología que la originó}
report_date: {type: date, event: report, title: Fecha de reporte}
histology:
type: code
event: report
title: Histología
system: who-cervical-histology
codes:
normal: Sin lesión
LSIL: Lesión intraepitelial escamosa de bajo grado (CIN 1)
HSIL: Lesión intraepitelial escamosa de alto grado (CIN 2-3)
CIS: Carcinoma in situ
carcinoma: Carcinoma invasor
-119
View File
@@ -1,119 +0,0 @@
# Breast cancer screening.
mammography:
title: Mastografía
key: [exam_date]
events:
sample: {date: exam_date}
report: {date: report_date, parent: sample}
fields:
exam_date: {type: date, event: sample, title: Fecha del estudio, required: true}
report_date: {type: date, event: report, title: Fecha de reporte}
adequacy:
type: code
event: report
title: Calidad de la imagen
system: adequacy
codes: {satisfactory: Satisfactoria, unsatisfactory: Insatisfactoria}
birads:
type: code
event: report
title: BI-RADS
system: bi-rads
codes:
'0': Incompleta, requiere estudios adicionales
'1': Negativa
'2': Hallazgos benignos
'3': Probablemente benigna
'4': Sospechosa
4A: Sospecha baja de malignidad
4B: Sospecha moderada de malignidad
4C: Sospecha alta de malignidad
'5': Altamente sugestiva de malignidad
'6': Malignidad confirmada por biopsia
breast_biopsy:
title: Biopsia de mama
key: [request_date, mammogram_exam_date]
events:
order: {date: request_date}
report: {date: report_date, parent: order}
fields:
request_date: {type: date, event: order, title: Fecha de solicitud, required: true}
mammogram_exam_date: {type: date, event: order, title: Mastografía que la originó}
report_date: {type: date, event: report, title: Fecha de reporte}
histology:
type: code
event: report
title: Histología
system: breast-histology
codes: {benign: Benigno, in_situ: In situ, invasive: Invasor}
histologic_type:
type: code
event: report
title: Tipo histológico (CIE-O-3)
system: icd-o-3
grade:
type: code
event: report
title: Grado histológico (Nottingham)
system: nottingham-grade
codes: {'1': Grado 1, '2': Grado 2, '3': Grado 3}
er:
type: code
event: report
title: Receptor de estrógeno
system: receptor-status
codes: &receptor {positive: Positivo, negative: Negativo}
pr:
type: code
event: report
title: Receptor de progesterona
system: receptor-status
codes: *receptor
her2:
type: code
event: report
title: HER2
system: receptor-status
codes: *receptor
ki67_pct: {type: number, event: report, title: Ki-67, unit: '%'}
size_mm: {type: number, event: report, title: Tamaño del tumor, unit: mm}
stage:
type: code
event: report
title: Estadio clínico (AJCC)
system: ajcc-stage
codes:
'0': Estadio 0
I: Estadio I (sin subgrupo)
II: Estadio II (sin subgrupo)
III: Estadio III (sin subgrupo)
IA: Estadio IA
IB: Estadio IB
IIA: Estadio IIA
IIB: Estadio IIB
IIIA: Estadio IIIA
IIIB: Estadio IIIB
IIIC: Estadio IIIC
IV: Estadio IV
breast_treatment:
title: Tratamiento de cáncer de mama
key: [start_date, kind]
events:
encounter: {date: start_date}
fields:
start_date: {type: date, event: encounter, title: Fecha de inicio, required: true}
kind:
type: code
event: encounter
title: Tratamiento
system: breast-treatment
required: true
codes:
breast_conserving_surgery: Cirugía conservadora
mastectomy: Mastectomía
chemotherapy: Quimioterapia
radiotherapy: Radioterapia
hormone_therapy: Hormonoterapia
anti_her2: Terapia anti-HER2
-36
View File
@@ -1,36 +0,0 @@
# Studies every domain shares.
clinical_note:
title: Nota médica
key: [note_date, specialty]
events:
encounter: {date: note_date}
fields:
note_date: {type: date, event: encounter, title: Fecha de la nota}
specialty:
type: code
event: encounter
title: Especialidad
system: specialty
codes:
colposcopy: Clínica de la mujer y colposcopia
oncology_surgery: Cirugía oncológica
medical_oncology: Oncología médica
radiation_oncology: Radio-oncología
family_medicine: Medicina familiar
pediatric_neurology: Neurología pediátrica
icd10:
type: code
event: encounter
title: Diagnóstico (CIE-10)
system: icd-10
pattern: '^[A-Z]\d{2}(\.\d{1,2})?$'
reason: {type: text, event: encounter, title: Motivo de consulta}
diagnosis_text: {type: text, event: encounter, title: Diagnóstico como se escribió}
death:
title: Defunción
key: []
events:
encounter: {date: death_date}
fields:
death_date: {type: date, event: encounter, title: Fecha de defunción, required: true}
-49
View File
@@ -1,49 +0,0 @@
# The code systems the platform's fields take their codes from. External systems are named by
# their canonical URI; only the codes a field allows are listed with the field.
bethesda:
url: https://isssteleon.org/fhir/CodeSystem/bethesda
title: Sistema Bethesda (citología cervical)
who-cervical-histology:
url: https://isssteleon.org/fhir/CodeSystem/who-cervical-histology
title: Clasificación OMS de lesiones cervicales (histología)
cervical-screening-history:
url: https://isssteleon.org/fhir/CodeSystem/cervical-screening-history
title: Antecedente de detección de cáncer de cérvix
cervix-exam:
url: https://isssteleon.org/fhir/CodeSystem/cervix-exam
title: Exploración del cuello uterino
bi-rads:
url: https://isssteleon.org/fhir/CodeSystem/bi-rads
title: BI-RADS
icd-10:
url: http://hl7.org/fhir/sid/icd-10
title: CIE-10
external: true
adequacy:
url: https://isssteleon.org/fhir/CodeSystem/adequacy
title: Calidad de la muestra
specialty:
url: https://isssteleon.org/fhir/CodeSystem/specialty
title: Especialidades
breast-histology:
url: https://isssteleon.org/fhir/CodeSystem/breast-histology
title: Histología de mama
ados2-module:
url: https://isssteleon.org/fhir/CodeSystem/ados2-module
title: Módulos del ADOS-2
icd-o-3:
url: http://terminology.hl7.org/CodeSystem/icd-o-3
title: CIE-O-3 (morfología)
external: true
nottingham-grade:
url: https://isssteleon.org/fhir/CodeSystem/nottingham-grade
title: Grado histológico de Nottingham
receptor-status:
url: https://isssteleon.org/fhir/CodeSystem/receptor-status
title: Estado de receptores hormonales y HER2
ajcc-stage:
url: https://isssteleon.org/fhir/CodeSystem/ajcc-stage
title: Estadio clínico AJCC (grupo)
breast-treatment:
url: https://isssteleon.org/fhir/CodeSystem/breast-treatment
title: Tratamientos de cáncer de mama
-60
View File
@@ -1,60 +0,0 @@
# Autism (TEA) screening: M-CHAT, ADOS-2, EEG; the neurology note that confirms the diagnosis
# is the common clinical note (specialty pediatric_neurology).
mchat:
title: M-CHAT-R/F
key: [screening_date]
events:
encounter: {date: screening_date}
fields:
screening_date: {type: date, event: encounter, title: Fecha del M-CHAT, required: true}
score: {type: number, event: encounter, title: Puntaje total (0 a 20)}
ados2:
title: ADOS-2
key: [evaluation_date]
events:
encounter: {date: evaluation_date}
fields:
evaluation_date: {type: date, event: encounter, title: Fecha de evaluación, required: true}
module:
type: code
event: encounter
title: Módulo
system: ados2-module
codes: {toddler: Módulo para niños pequeños, module_1: Módulo 1, module_2: Módulo 2, module_3: Módulo 3}
# The 22 items by what they observe (the same meaning in every module), each 0 to 3.
vocalization_directed: {type: number, event: encounter, title: Frecuencia de la vocalización espontánea dirigida a otros}
pointing: {type: number, event: encounter, title: Señalar}
gestures: {type: number, event: encounter, title: Gestos}
unusual_eye_contact: {type: number, event: encounter, title: Contacto visual inusual}
facial_expressions: {type: number, event: encounter, title: Expresiones faciales dirigidas a otros}
gaze_integration: {type: number, event: encounter, title: Integración de la mirada y otras conductas}
shared_enjoyment: {type: number, event: encounter, title: Disfrute compartido durante la interacción}
response_to_name: {type: number, event: encounter, title: Respuesta al nombre}
ignoring: {type: number, event: encounter, title: Ignorar}
requesting: {type: number, event: encounter, title: Pedir}
showing: {type: number, event: encounter, title: Mostrar}
joint_attention_initiation: {type: number, event: encounter, title: Iniciación espontánea de la atención conjunta}
joint_attention_response: {type: number, event: encounter, title: Respuesta a la atención conjunta}
social_overtures_quality: {type: number, event: encounter, title: Características de las iniciaciones sociales}
social_overtures_caregiver: {type: number, event: encounter, title: Cantidad de acercamientos sociales al cuidador}
reciprocal_communication: {type: number, event: encounter, title: Cantidad de comunicación social recíproca}
rapport_quality: {type: number, event: encounter, title: Calidad general de la relación}
intonation: {type: number, event: encounter, title: Entonación de las vocalizaciones o verbalizaciones}
stereotyped_language: {type: number, event: encounter, title: Uso estereotipado o idiosincrásico de palabras o frases}
unusual_sensory_interest: {type: number, event: encounter, title: Interés sensorial inusual}
hand_finger_mannerisms: {type: number, event: encounter, title: Manierismos de manos y dedos}
repetitive_interests: {type: number, event: encounter, title: Intereses inusualmente repetitivos}
social_affect_total: {type: number, event: encounter, title: Total de afectación social (impreso)}
restricted_repetitive_total: {type: number, event: encounter, title: Total de comportamiento restringido y repetitivo (impreso)}
overall_total: {type: number, event: encounter, title: Puntuación total global (impresa)}
eeg:
title: Electroencefalograma
key: [study_date]
events:
sample: {date: study_date}
fields:
study_date: {type: date, event: sample, title: Fecha del estudio, required: true}
lab_record_id: {type: text, event: sample, title: Registro del laboratorio}
edf: {type: file, event: sample, title: Registro EDF}
+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")
-88
View File
@@ -1,88 +0,0 @@
"""A site's codes in platform terms: FHIR ConceptMaps (R4B), as data a site's configuration
holds, never code. A new laboratory that writes "Negativo para lesión" for NILM, or "F" for
female, is one more element in its ConceptMap.
Each group maps the site's codes (`source`, any URI the site uses) onto one system the
platform's fields take their codes from (`target`): a catalog system (core.catalog), FHIR's
administrative gender (identity `sex`), or the platform's yes/no system (boolean fields).
"""
from collections.abc import Iterable
from fhir.resources.R4B.conceptmap import ConceptMap
from core import catalog
GENDER = "http://hl7.org/fhir/administrative-gender"
BOOLEAN = "https://isssteleon.org/fhir/CodeSystem/boolean"
_GENDER_CODES = {"female", "male"}
_BOOLEAN_CODES = {"true", "false"}
def systems(field: str) -> dict[str, set[str] | None]:
"""The systems a field of this name takes codes from, each with its allowed codes
(None: any code of the system)."""
found: dict[str, set[str] | None] = {}
if field == "sex":
found[GENDER] = _GENDER_CODES
for study in catalog.studies().values():
f = study.fields.get(field)
if f is None:
continue
if f.type == "boolean":
found[BOOLEAN] = _BOOLEAN_CODES
elif f.type == "code":
url = catalog.systems()[f.system].url
codes = set(f.codes) or None
known = found.get(url, set())
found[url] = None if codes is None or known is None else known | codes
return found
def problems(cm: ConceptMap) -> list[str]:
"""Why this map can't be used: a group onto a system no field takes, or a target code
its field doesn't allow."""
allowed: dict[str, set[str] | None] = {GENDER: _GENDER_CODES, BOOLEAN: _BOOLEAN_CODES}
for study in catalog.studies().values():
for name in study.fields:
allowed |= systems(name)
found = []
for group in cm.group or []:
if group.target not in allowed:
found.append(f"{group.target}: no platform field takes codes from it")
continue
codes = allowed[group.target]
for element in group.element:
for target in element.target or []:
if codes is not None and target.code not in codes:
found.append(f"{group.target}: {target.code} is not an allowed code")
return found
def table(maps: Iterable[ConceptMap], field: str) -> dict[str, str]:
"""A field's translations, site code (case ignored) -> platform code, from the groups
of these maps that target a system the field takes."""
targets = systems(field)
found = {}
for cm in maps:
for group in cm.group or []:
if group.target not in targets:
continue
for element in group.element:
for target in element.target or []:
if target.equivalence in ("equivalent", "equal", "wider", "subsumes"):
found[element.code.casefold()] = target.code
return found
def translate(maps: Iterable[ConceptMap], source: str, code: str) -> tuple[str, str] | None:
"""A sender's coding (system, code) as (platform system, code), when a map knows it."""
for cm in maps:
for group in cm.group or []:
if group.source != source:
continue
for element in group.element:
if element.code.casefold() == code.casefold():
for target in element.target or []:
return group.target, target.code
return None
-30
View File
@@ -1,30 +0,0 @@
"""The platform's domains. A domain is a package `core.<domain>` holding its parameters
(`__init__`: what dbt reads through `dbt_vars()`), and when it has them, its measures
(`measures.MEASURES`) and its follow-up list (`follow_up`)."""
import importlib
from enum import StrEnum
from types import ModuleType
class Domain(StrEnum):
CACU = "cacu"
CAMA = "cama"
TEA = "tea"
def part(domain: Domain, name: str = "") -> ModuleType | None:
"""The domain's module `name` (its package without one), or None while it has none."""
path = f"core.{domain.value}" + (f".{name}" if name else "")
try:
return importlib.import_module(path)
except ModuleNotFoundError as e:
if e.name is not None and path.startswith(e.name):
return None
raise
def measures(domain: Domain) -> dict:
"""The domain's measures by id (none for a domain without them yet)."""
found = part(domain, "measures")
return found.MEASURES if found else {}
-470
View File
@@ -1,470 +0,0 @@
"""Platform rows as FHIR R4B resources (pure, no IO), and the conformance resources that
declare what ours are: the local code systems, our extensions and our search parameters.
Every mapper builds a `fhir.resources.R4B` model, so a resource that breaks FHIR's structure
fails here, before it is served. Clinical resources other than Patient are found by search
only; their ids are stable (a UUID of their natural key), not addresses.
"""
import uuid
from collections.abc import Iterable
from datetime import UTC, date, datetime
from fhir.resources.R4B.codesystem import CodeSystem
from fhir.resources.R4B.condition import Condition
from fhir.resources.R4B.diagnosticreport import DiagnosticReport
from fhir.resources.R4B.encounter import Encounter
from fhir.resources.R4B.measure import Measure
from fhir.resources.R4B.observation import Observation
from fhir.resources.R4B.patient import Patient
from fhir.resources.R4B.procedure import Procedure
from fhir.resources.R4B.resource import Resource
from fhir.resources.R4B.riskassessment import RiskAssessment
from fhir.resources.R4B.searchparameter import SearchParameter
from fhir.resources.R4B.structuredefinition import StructureDefinition
from core import catalog
FHIR_VERSION = "4.3.0"
BASE = "https://isssteleon.org/fhir"
EXTENSION = f"{BASE}/StructureDefinition/"
CODES = f"{BASE}/CodeSystem/"
ICD10 = "http://hl7.org/fhir/sid/icd-10"
UCUM = "http://unitsofmeasure.org"
_IDS = uuid.uuid5(uuid.NAMESPACE_URL, BASE)
# Local code systems: code -> display (Spanish, as the screens show them).
CODE_SYSTEMS: dict[str, tuple[str, dict[str, str]]] = {
"cacu-procedure": ("Procedimientos de CaCu", {
"colposcopy": "Colposcopia", "treatment": "Tratamiento",
}),
"cacu-follow-up-status": ("Estatus de seguimiento", {
"case": "Caso (cáncer)", "pre_colposcopy": "Pre colposcopia",
"post_colposcopy": "Post colposcopia", "post_treatment": "Post tratamiento",
}),
"cama-follow-up-status": ("Estatus de seguimiento", {
"cancer": "Diagnóstico confirmado", "pending_biopsy": "Pendiente de biopsia",
"biopsy_no_result": "Biopsia sin resultado", "benign_biopsy": "Biopsia benigna",
}),
"follow-up-priority": ("Prioridad de seguimiento", {
"high": "Alta", "medium": "Media", "low": "Baja",
}),
"measure-stratifier": ("Estratos de indicadores", {
"category": "Categoría", "age_group": "Grupo de edad",
"follow_up_status": "Estatus de seguimiento", "result": "Citología de alto grado",
"diagnosis_code": "Diagnóstico CIE-10",
"birads": "BI-RADS de la mastografía",
"referral_cytology": "Citología previa", "histology_level": "Histología",
"screening_round": "Tamizaje inicial o subsecuente",
"result_initial": "Resultado en tamizaje inicial",
"result_subsequent": "Resultado en tamizaje subsecuente",
"referral_hpv": "VPH de la citología previa", "hpv_16": "VPH 16", "hpv_18": "VPH 18",
"hpv_initial": "VPH en tamizaje inicial",
"hpv_subsequent": "VPH en tamizaje subsecuente",
}),
"risk-model": ("Modelos de riesgo", {}), # open: a model's name is its code
} # fmt: skip
def _catalog_systems() -> dict[str, tuple[str, dict[str, str]]]:
"""The catalog's own code systems, with every code some field allows."""
found: dict[str, tuple[str, dict[str, str]]] = {}
for name, system in catalog.systems().items():
if not system.external:
codes = {c: d for s in catalog.studies().values() for f in s.fields.values()
if f.system == name for c, d in f.codes.items()} # fmt: skip
found[name] = (system.title, codes)
return found
CODE_SYSTEMS |= _catalog_systems()
# What the catalog names: its studies, and every field as `<study>.<field>`.
CODE_SYSTEMS["study"] = ("Estudios", {n: s.title for n, s in catalog.studies().items()})
CODE_SYSTEMS["catalog-field"] = ("Campos de los estudios", {
f"{n}.{f}": d.title for n, s in catalog.studies().items() for f, d in s.fields.items()
}) # fmt: skip
# Our extensions: name -> (value type, the elements they extend).
EXTENSIONS: dict[str, tuple[str, list[str]]] = {
"ic-bajo": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
"ic-alto": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
"q1": ("decimal", ["MeasureReport.group.measureScore"]),
"q3": ("decimal", ["MeasureReport.group.measureScore"]),
"corte-conocimiento": ("dateTime", ["MeasureReport"]),
"period-type": ("code", ["Measure"]),
"follow-up-status": ("Coding", ["Patient"]),
"follow-up-priority": ("Coding", ["Patient"]),
"report-date": ("date", ["DiagnosticReport"]),
"days-to-diagnosis": ("integer", ["DiagnosticReport"]),
"stage-colposcopy-state": ("code", ["DiagnosticReport"]),
"stage-colposcopy-date": ("date", ["DiagnosticReport"]),
"stage-biopsy-state": ("code", ["DiagnosticReport"]),
"stage-biopsy-date": ("date", ["DiagnosticReport"]),
"stage-diagnosis-state": ("code", ["DiagnosticReport"]),
"stage-diagnosis-date": ("date", ["DiagnosticReport"]),
} # fmt: skip
def _name(code: str) -> str:
"""A conformance resource's computable name (CamelCase)."""
return "".join(part.capitalize() for part in code.replace("_", "-").split("-"))
def _id(*key) -> str:
return str(uuid.uuid5(_IDS, "|".join(str(k) for k in key)))
def _day(value) -> str | None:
if value is None:
return None
return value.isoformat()[:10] if isinstance(value, date) else str(value)[:10]
def _instant(value) -> str | None:
"""A stored moment as an instant; one stored without an offset is UTC."""
if value is None:
return None
found = value if isinstance(value, datetime) else datetime.fromisoformat(str(value))
return (found if found.tzinfo else found.replace(tzinfo=UTC)).isoformat()
def coding(system: str, code: str) -> dict:
display = CODE_SYSTEMS[system][1].get(code) if system in CODE_SYSTEMS else None
return {"system": CODES + system, "code": code, **({"display": display} if display else {})}
def concept(system: str, code: str) -> dict:
found = coding(system, code)
return {"coding": [found], "text": found.get("display", code)}
def ext(name: str, value_type: str, value) -> dict:
return {"url": EXTENSION + name, f"value{value_type[0].upper()}{value_type[1:]}": value}
def subject(person_id: str) -> dict:
return {"reference": f"Patient/{person_id}"}
# --- clinical resources ----------------------------------------------------------------
def patient(row: dict, status_system: str | None = None) -> Patient:
"""A person: what her records agree on, her names and identifiers, the ids she
replaced; on a follow-up list, her status there (`status_system`) and priority."""
found: dict = {"resourceType": "Patient", "id": row["person_id"]}
if row.get("sex"):
found["gender"] = row["sex"]
if row.get("birth_date"):
found["birthDate"] = _day(row["birth_date"])
if row.get("death_date"):
found["deceasedDateTime"] = _day(row["death_date"])
if row.get("status") and status_system:
found["extension"] = [ext("follow-up-status", "Coding",
coding(status_system, row["status"]))] # fmt: skip
if row.get("priority"):
priority = coding("follow-up-priority", row["priority"])
found["extension"].append(ext("follow-up-priority", "Coding", priority))
if row.get("names"):
found["name"] = [{"text": n} for n in row["names"]]
if row.get("identifiers"):
found["identifier"] = [{"system": s, "value": v} for s, v in row["identifiers"]]
if row.get("replaces"):
found["link"] = [{"other": {"reference": f"Patient/{old}"}, "type": "replaces"}
for old in row["replaces"]] # fmt: skip
return Patient.model_validate(found)
def replaced_patient(person_id: str, replaced_by: str) -> Patient:
"""A person a review merged into another: no longer active, pointing at who replaced
her, so her id keeps resolving."""
return Patient.model_validate({
"resourceType": "Patient", "id": person_id, "active": False,
"link": [{"other": {"reference": f"Patient/{replaced_by}"}, "type": "replaced-by"}],
}) # fmt: skip
def _value(f: catalog.FieldDef, value) -> dict:
"""A field's value as the Observation value of its type."""
if f.type == "code":
system = catalog.systems()[f.system]
if system.external:
return {"valueCodeableConcept": {"coding": [{"system": system.url, "code": value}],
"text": value}} # fmt: skip
return {"valueCodeableConcept": concept(f.system, value)}
if f.type == "boolean":
return {"valueBoolean": bool(value)}
if f.type == "number":
return {"valueQuantity": {"value": value, **({"unit": f.unit} if f.unit else {})}}
if f.type == "date":
return {"valueDateTime": _day(value)}
return {"valueString": str(value)}
def known(study: str, row: dict, cutoff) -> dict:
"""A study instance as the platform knew it by the end of `cutoff`: the fields of an
event that has no date yet, or a later one, are not known."""
spec = catalog.studies()[study]
out = dict(row)
for cls, event in spec.events.items():
day = _day(row.get(event.date))
if event.parent is not None and (day is None or day > _day(cutoff)):
for name, f in spec.fields.items():
if f.event == cls:
out[name] = None
return out
def instance(study: str, row: dict, report_extensions: Iterable[dict] = ()) -> list[Resource]:
"""One study instance (a row of `silver.<study>`) as FHIR, from the catalog: an
Observation per field that is not an event's date, and, when the study has a report,
the DiagnosticReport that gathers them."""
spec = catalog.studies()[study]
person = row["person_id"]
key = [_day(row[k]) if spec.fields[k].type == "date" else row[k] for k in spec.key]
dates = {e.date for e in spec.events.values()}
root = next(e for e in spec.events.values() if e.parent is None)
effective = _day(row.get(root.date))
container = _id(study, person, *key) # its report, or the encounter its notes are of
visit = "report" not in spec.events
observations = []
for name, f in spec.fields.items():
if name in dates or row.get(name) is None or f.type == "file":
continue
observations.append(Observation.model_validate({
"resourceType": "Observation",
"id": _id(study, name, person, *key),
"status": "final",
"code": concept("catalog-field", f"{study}.{name}"),
"subject": subject(person),
**({"encounter": {"reference": f"Encounter/{container}"}} if visit else {}),
**({"effectiveDateTime": effective} if effective else {}),
**_value(f, row[name]),
})) # fmt: skip
if visit: # a study without a report (a consultation): the encounter its values are of
if not observations:
return []
encounter = Encounter.model_validate({
"resourceType": "Encounter", "id": container, "status": "finished",
"class": {"system": "http://terminology.hl7.org/CodeSystem/v3-ActCode",
"code": "AMB"},
"type": [concept("study", study)],
"subject": subject(person),
**({"period": {"start": effective}} if effective else {}),
}) # fmt: skip
return [encounter, *observations]
reported = _day(row.get(spec.events["report"].date))
extensions = ([ext("report-date", "date", reported)] if reported else []) + list(
report_extensions
)
report = DiagnosticReport.model_validate({
"resourceType": "DiagnosticReport",
"id": container,
"status": "final" if reported else "registered",
"code": concept("study", study),
"subject": subject(person),
**({"effectiveDateTime": effective} if effective else {}),
**({"extension": extensions} if extensions else {}),
"result": [{"reference": f"Observation/{o.id}"} for o in observations] or None,
}) # fmt: skip
return [report, *observations]
def condition(row: dict) -> Condition:
"""What a clinical note diagnosed (`silver.clinical_note`), by ICD-10 or as written."""
person, day = row["person_id"], _day(row["note_date"])
code: dict = {"text": row.get("diagnosis_text") or row.get("icd10")}
if row.get("icd10"):
code["coding"] = [{"system": ICD10, "code": row["icd10"]}]
found: dict = {
"resourceType": "Condition",
"id": _id("condition", person, day, row.get("specialty")),
"category": [{"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/condition-category",
"code": "encounter-diagnosis"}]}],
"code": code,
"subject": subject(person),
"recordedDate": day,
} # fmt: skip
if row.get("reason"):
found["note"] = [{"text": row["reason"]}]
return Condition.model_validate(found)
def procedure(row: dict) -> Procedure:
"""A procedure the timeline inferred (`gold.cacu_events`: colposcopy, treatment)."""
person, day = row["person_id"], _day(row["date"])
return Procedure.model_validate({
"resourceType": "Procedure",
"id": _id("procedure", row["type"], person, day),
"status": "completed",
"code": concept("cacu-procedure", row["type"]),
"subject": subject(person),
"performedDateTime": day,
}) # fmt: skip
def risk_assessment(row: dict, horizons: Iterable[dict]) -> RiskAssessment:
"""A model's risk for one person at her index date (`gold.cacu_risk`): one prediction
per horizon, in years, with its 95% interval."""
predictions = []
for h in sorted(horizons, key=lambda h: h["horizon_years"]):
bounds = (("ic-bajo", "ci_low"), ("ic-alto", "ci_high"))
interval = [ext(name, "decimal", h[key]) for name, key in bounds
if h.get(key) is not None] # fmt: skip
predictions.append({
"probabilityDecimal": h["probability"],
"whenRange": {"high": {"value": h["horizon_years"], "unit": "a", "system": UCUM,
"code": "a"}},
**({"extension": interval} if interval else {}),
}) # fmt: skip
model = row["model"]
return RiskAssessment.model_validate({
"resourceType": "RiskAssessment",
"id": _id("risk", model, row["version"], row["person_id"], _day(row["index_date"])),
"meta": {"lastUpdated": _instant(row["scored_at"])},
"status": "final",
"method": {"coding": [{"system": CODES + "risk-model", "code": model}],
"text": f"{model} v{row['version']}"},
"subject": subject(row["person_id"]),
"occurrenceDateTime": _day(row["index_date"]),
"prediction": predictions,
}) # fmt: skip
SCORING = {"proportion": "proportion", "continuous-variable": "continuous-variable",
"composition": "cohort"} # fmt: skip
def measure_id(code: str) -> str:
"""A measure's FHIR id (ids allow no underscore)."""
return code.lower().replace("_", "-")
def measure_url(code: str) -> str:
return f"{BASE}/Measure/{code}"
# The populations each kind of measure counts (core.measures emits exactly these).
POPULATIONS = {"proportion": ["initial-population", "denominator", "numerator"],
"continuous-variable": ["initial-population", "measure-observation"],
"composition": ["initial-population", "measure-observation"]} # fmt: skip
POPULATION = "http://terminology.hl7.org/CodeSystem/measure-population"
def stratifiers(m) -> list[str]:
"""A measure's strata: a composition's categories first, then its declared strata."""
first = ["category"] if m.rule.kind == "composition" else []
return first + [name for name, _ in getattr(m.rule, "strata", ())]
def stratifier_code(name: str) -> dict:
return concept("measure-stratifier", name)
def measure(m, domain: str) -> Measure:
"""A measure definition (`core.measures.Measure`): how it is computed is Core's code,
which `criteria` points to."""
criteria = {"language": "text/x-python",
"expression": f"core.{domain}.measures.MEASURES['{m.id}']"} # fmt: skip
group: dict = {
"id": m.group,
"population": [{"code": {"coding": [{"system": POPULATION, "code": c}]},
"criteria": criteria} for c in POPULATIONS[m.rule.kind]],
} # fmt: skip
if strata := stratifiers(m):
group["stratifier"] = [{"id": s, "code": stratifier_code(s), "criteria": criteria}
for s in strata] # fmt: skip
found: dict = {
"resourceType": "Measure",
"id": measure_id(m.id),
"url": measure_url(m.id),
"version": m.version,
"name": m.id,
"title": m.title,
"status": "active",
"scoring": {"coding": [{"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": SCORING[m.rule.kind]}]},
"extension": [ext("period-type", "code", p) for p in m.periods],
"group": [group],
} # fmt: skip
if m.improvement:
found["improvementNotation"] = {"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": m.improvement}]} # fmt: skip
if m.description:
found["description"] = m.description
return Measure.model_validate(found)
# --- conformance: what our resources declare ---------------------------------------------
def code_systems() -> list[CodeSystem]:
return [CodeSystem.model_validate({
"resourceType": "CodeSystem", "id": name, "url": CODES + name,
"name": _name(name),
"title": title, "status": "active", "caseSensitive": True,
"content": "complete" if concepts else "not-present",
"concept": [{"code": c, "display": d} for c, d in concepts.items()],
}) for name, (title, concepts) in CODE_SYSTEMS.items()] # fmt: skip
def extensions() -> list[StructureDefinition]:
found = []
for name, (value_type, contexts) in EXTENSIONS.items():
url = EXTENSION + name
found.append(StructureDefinition.model_validate({
"resourceType": "StructureDefinition", "id": name, "url": url,
"name": _name(name), "status": "active", "fhirVersion": FHIR_VERSION,
"kind": "complex-type", "abstract": False, "type": "Extension",
"context": [{"type": "element", "expression": c} for c in contexts],
"baseDefinition": "http://hl7.org/fhir/StructureDefinition/Extension",
"derivation": "constraint",
"differential": {"element": [
{"id": "Extension", "path": "Extension", "max": "*" if name == "period-type"
else "1"},
{"id": "Extension.extension", "path": "Extension.extension", "max": "0"},
{"id": "Extension.url", "path": "Extension.url", "fixedUri": url},
{"id": "Extension.value[x]", "path": "Extension.value[x]", "min": 1,
"type": [{"code": value_type}]},
]},
})) # fmt: skip
return found
# Our search parameters: code -> (resource, type, description).
SEARCH_PARAMETERS: dict[str, tuple[str, str, str]] = {
"stage-cutoff": ("DiagnosticReport", "date", "Cutoff for sample-linked stages"),
"follow-up-age-min": ("Patient", "number", "Minimum completed age at the cutoff"),
"follow-up-age-max": ("Patient", "number", "Maximum completed age at the cutoff"),
"follow-up-search": ("Patient", "string", "Partial name or identifier"),
"follow-up-status": ("Patient", "token", "Follow-up status at the cut-off"),
"follow-up-cutoff": ("Patient", "date", "The day the follow-up list is taken at"),
"follow-up-window": ("Patient", "number",
"Months before the cut-off a cytology puts a patient on the list"),
"recent": ("Patient", "date", "Her latest cytology in the window (sort only)"),
"risk-cin2": ("Patient", "number", "Her current CIN2+ risk (sort only)"),
"risk-cancer": ("Patient", "number", "Her current cancer risk (sort only)"),
"risk-horizon": ("Patient", "number", "The horizon, in years, risks are sorted at"),
"reporting-period": ("MeasureReport", "token",
"A semester (2025-S1) or a month (2025-03) the report covers"),
"as-of": ("MeasureReport", "date", "Count only what the platform knew by then"),
"event-cutoff": ("MeasureReport", "date", "Durations count to this day"),
} # fmt: skip
def search_parameters() -> list[SearchParameter]:
return [SearchParameter.model_validate({
"resourceType": "SearchParameter", "id": code,
"url": f"{BASE}/SearchParameter/{code}", "name": _name(code),
"status": "active", "description": description, "code": code, "base": [base],
"type": kind,
}) for code, (base, kind, description) in SEARCH_PARAMETERS.items()] # fmt: skip
def conformance() -> list[Resource]:
"""Everything our resources declare: what the validator loads, and what the
CapabilityStatement points to."""
return [*code_systems(), *extensions(), *search_parameters()]
-157
View File
@@ -1,157 +0,0 @@
"""FHIR in: what a standard hospital sends (R4 Bundles), as the rows a pipeline's link and
target nodes take, the same rows a site's map and extract nodes give. One silver,
two doors.
A record is one resource the hospital sent: a Patient, and each DiagnosticReport or
Encounter (one study instance). Every report also gives an identity row, its subject's, so
the link node joins it to its person the way it joins any document: by identifiers, name and
birth date. Codes in the platform's own systems pass as they are; any other code goes through
the sender's ConceptMaps (core.concept_map), and one no map knows is kept as sent, so the
target holds the row saying why.
"""
import hashlib
from collections.abc import Iterable
from typing import Any
from fhir.resources.R4B.conceptmap import ConceptMap
from core import catalog, concept_map
from core.fhir import CODES
from core.pipeline import RECORD
from core.schema import IDENTIFIER_SYSTEMS
STUDY = CODES + "study"
FIELD = CODES + "catalog-field"
def record(sender: str, reference: str) -> str:
"""A sent resource's record id: stable across resends of the same resource."""
return hashlib.sha256(f"{sender}|{reference}".encode()).hexdigest()
def resources(bundle: dict) -> dict[str, dict]:
"""The Bundle's resources by `Type/id`: what its references name, whether they use that
form or the entry's `fullUrl` (`urn:uuid:...`, as transaction Bundles do)."""
return {f"{r['resourceType']}/{r['id']}": r for r in _entries(bundle).values()}
def _entries(bundle: dict) -> dict[str, dict]:
"""Every resource under each name a reference may use: `Type/id` and its fullUrl."""
found = {}
for entry in bundle.get("entry", []):
r = entry.get("resource") or {}
if r.get("resourceType") and r.get("id"):
found[f"{r['resourceType']}/{r['id']}"] = r
if entry.get("fullUrl"):
found[entry["fullUrl"]] = r
return found
def _translated(maps: Iterable[ConceptMap], coding: dict, system: str) -> str | None:
"""A coding as a code of `system`: as it is when already there, else through the maps."""
if coding.get("system") == system:
return coding.get("code")
found = concept_map.translate(maps, coding.get("system", ""), coding.get("code", ""))
return found[1] if found and found[0] == system else None
def _codings(concept: dict | None) -> list[dict]:
return (concept or {}).get("coding", [])
def identity(patient: dict) -> dict[str, Any]:
"""What a Patient says about whom she is: identifiers by system, name, birth date, sex."""
found: dict[str, Any] = {}
by_system = {v: k for k, v in IDENTIFIER_SYSTEMS.items()}
for i in patient.get("identifier", []):
field = by_system.get(i.get("system"), "record_number")
found.setdefault(field, i.get("value"))
if names := patient.get("name"):
name = names[0]
found["full_name"] = name.get("text") or " ".join(
[*name.get("given", []), *([name["family"]] if name.get("family") else [])]
)
if patient.get("birthDate"):
found["birth_date"] = patient["birthDate"]
if patient.get("gender") in ("female", "male"):
found["sex"] = patient["gender"]
return found
def _value(observation: dict, f: catalog.FieldDef, maps) -> Any:
if "valueCodeableConcept" in observation:
codings = _codings(observation["valueCodeableConcept"])
url = catalog.systems()[f.system].url if f.system else None
for coding in codings:
if url and (code := _translated(maps, coding, url)) is not None:
return code
return codings[0].get("code") if codings else None # kept as sent: held, saying why
for key in ("valueBoolean", "valueString", "valueInteger"):
if key in observation:
return observation[key]
if "valueQuantity" in observation:
return observation["valueQuantity"].get("value")
if "valueDateTime" in observation:
return observation["valueDateTime"][:10]
return None
def rows(bundle: dict, entity: str, sender: str, maps: Iterable[ConceptMap] = ()) -> list[dict]:
"""The Bundle's rows of one entity: `identity` (each Patient, and each report's
subject), `death` (Patients who died), or a study of the catalog (each report or
encounter of it, with its results as fields)."""
maps = list(maps)
sent = resources(bundle)
named = _entries(bundle) # what a reference may name
def subject(r: dict) -> dict | None:
return named.get((r.get("subject") or {}).get("reference", ""))
if entity == "identity":
out = [{**identity(r), RECORD: record(sender, ref)}
for ref, r in sent.items() if r["resourceType"] == "Patient"] # fmt: skip
for ref, r in sent.items():
if r["resourceType"] in ("DiagnosticReport", "Encounter") and (p := subject(r)):
out.append({**identity(p), RECORD: record(sender, ref)})
return out
if entity == "death":
return [{"death_date": r["deceasedDateTime"][:10], RECORD: record(sender, ref)}
for ref, r in sent.items()
if r["resourceType"] == "Patient" and r.get("deceasedDateTime")] # fmt: skip
spec = catalog.studies()[entity]
kind = "DiagnosticReport" if "report" in spec.events else "Encounter"
root = next(e for e in spec.events.values() if e.parent is None)
out = []
for ref, r in sent.items():
if r["resourceType"] != kind:
continue
code = r.get("code") if kind == "DiagnosticReport" else (r.get("type") or [None])[0]
if not any(_translated(maps, c, STUDY) == entity for c in _codings(code)):
continue
row: dict[str, Any] = {RECORD: record(sender, ref)}
start = r.get("effectiveDateTime") if kind == "DiagnosticReport" else (
(r.get("period") or {}).get("start")) # fmt: skip
if start:
row[root.date] = start[:10]
if kind == "DiagnosticReport":
reported = next((x.get("valueDate") for x in r.get("extension", [])
if x.get("url", "").endswith("/report-date")), None) # fmt: skip
reported = reported or (r.get("issued") or "")[:10] or None
if reported:
row[spec.events["report"].date] = reported
results = [named.get(x.get("reference", "")) for x in r.get("result", [])]
else:
mine = {ref, *(k for k, v in named.items() if v is r)}
results = [o for o in sent.values() if o["resourceType"] == "Observation"
and (o.get("encounter") or {}).get("reference") in mine] # fmt: skip
for o in filter(None, results):
for coding in _codings(o.get("code")):
name = _translated(maps, coding, FIELD) or ""
study, _, field = name.partition(".")
if study == entity and field in spec.fields:
row[field] = _value(o, spec.fields[field], maps)
break
out.append(row)
return out
-26
View File
@@ -1,26 +0,0 @@
"""What every domain's follow-up list shares (pure). A domain with a list has a module
`core.<domain>.follow_up` with:
- `WINDOWS`: the windows (months) the list can be asked for; `SORTS` and `DEFAULT_HORIZON`
(years, for orders by risk; None without one);
- `STATUS_SYSTEM`: the code system of a patient's status on the list;
- `listed(rows, start, cutoff)`: who is on the list in reading order (most recent first),
each with her `status` (and `priority`, when the domain ranks them), from the rows of its
`follow_up` read (persistance.fhir);
- `status(row, cutoff)`: a person's status at the cut-off from her person row, or None;
- `ordered(rows, sort, risks, horizon)`: the list in another sort;
- `PROCEDURES`: the timeline's inferred procedures served as FHIR Procedures;
- `REPORT_FACTS`: facts gold adds to a study's report, by study.
"""
import calendar
from datetime import date
def window_start(cutoff: date, months: int) -> date:
"""The first day of the window: `months` before the cut-off (the month's last day when
shorter), plus one day."""
total = cutoff.year * 12 + cutoff.month - 1 - months
year, month = divmod(total, 12)
day = min(cutoff.day, calendar.monthrange(year, month + 1)[1])
return date.fromordinal(date(year, month + 1, day).toordinal() + 1)
View File
+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"

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