Compare commits

..

57 Commits

Author SHA1 Message Date
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
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
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
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
120 changed files with 3341 additions and 563 deletions
@@ -13,6 +13,11 @@ class CelulasEscamosas(str, Enum):
LIEAG = "LIEAG"
CIS = "CIS"
class CelulasGlandulares(str, Enum):
"""Resultado de células glandulares (Bethesda): atípicas o adenocarcinoma."""
AGC = "AGC"
ADENOCARCINOMA = "ADENOCARCINOMA"
CELULAS_ESCAMOSAS_ALIAS: dict[str,str] = {
# Long forms, as the hospital platform is expected to write them
"LESIÓN INTRAEPITELIAL ESCAMOSA DE BAJO GRADO (DISPLASIA LEVE Y/O VPH)": "LIEBG",
+1 -1
View File
@@ -1,5 +1,5 @@
from core.cacu.paciente.enums import SexoBiologico, SEXO_BIOLOGICO_ALIAS
from core.cacu.citologia_cervical.enums import CelulasEscamosas, CELULAS_ESCAMOSAS_ALIAS, CITO_CALIDAD_ESPECIMEN_ALIAS, ResultadoVPH
from core.cacu.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
+4
View File
@@ -6,6 +6,8 @@ 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,
@@ -71,6 +73,8 @@ from core.indicadores.reportes import (
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"
+1
View File
@@ -6,6 +6,7 @@
| `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 |
+5
View File
@@ -28,6 +28,11 @@ class Paciente(CaCuModel, table=True):
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(
+4
View File
@@ -6,6 +6,8 @@ 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,
@@ -71,6 +73,8 @@ from core.indicadores.reportes import (
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"
+1
View File
@@ -7,6 +7,7 @@
| `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 |
+5
View File
@@ -28,6 +28,11 @@ class Paciente(CaMaModel, table=True):
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_codigo_postal: Optional[str] = Field(
default=None,
sa_column=sa.Column(
+5 -1
View File
@@ -13,7 +13,7 @@ codigos_hospital = ["..."] # cómo lo nombra el hospital (tipo de estud
etiqueta = "..."
tipo_valor = "codigo" # codigo, booleano, numero, fecha, texto, externo
unidad = "min" # opcional (numero)
sistema = "CIE-10" # solo externo
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" },
]
@@ -35,5 +35,9 @@ valores = [
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.
+5 -1
View File
@@ -26,7 +26,11 @@ valores = [
[citologia.resultados.celulas_glandulares]
etiqueta = "Células glandulares"
tipo_valor = "texto"
tipo_valor = "codigo"
valores = [
{ valor = "AGC", etiqueta = "Células glandulares atípicas (AGC)" },
{ valor = "ADENOCARCINOMA", etiqueta = "Adenocarcinoma" },
]
[citologia.resultados.carcinoma_invasor]
etiqueta = "Carcinoma invasor"
+655 -9
View File
@@ -2,10 +2,13 @@
# BI-RADS: el hospital reporta 4A, 4B y 4C, normalizados (usuario, 2026-10-16); un 4 sin subcategoría
# también puede llegar (`cama.birads_gravedad` en parametros.toml).
# Mammography. Procedures: the `toma` (the study, both breasts), its `reporte` (the interpretation), one `parte` of the
# report per breast and, inside each breast, one `parte` per finding. Each result says which one it goes in.
[mastografia]
etiqueta = "Mastografía"
codigos_hospital = ["MASTOGRAFIA"]
# In the toma.
[mastografia.resultados.calidad_imagen]
etiqueta = "Calidad de la imagen"
tipo_valor = "codigo"
@@ -14,6 +17,21 @@ valores = [
{ valor = "INSATISFACTORIO", etiqueta = "Insatisfactoria" },
]
# In the toma. Screening or diagnostic (NOM-041-SSA2-2011, 7.3.3 and 9.2): the registry's method of primary detection
# (Apéndice Normativo G). SEGUIMIENTO is the six-monthly control of a BI-RADS 3 (14.4.5.4).
[mastografia.resultados.tipo_estudio]
etiqueta = "Tipo de estudio"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Tipo de estudio", "Estudio", "Indicación"]
valores = [
{ valor = "TAMIZAJE", etiqueta = "Tamizaje", alias = ["Tamizaje", "Detección", "Escrutinio", "Screening"] },
{ valor = "DIAGNOSTICA", etiqueta = "Diagnóstica", alias = ["Diagnóstica", "Diagnóstico"] },
{ valor = "SEGUIMIENTO", etiqueta = "Seguimiento", alias = ["Seguimiento", "Control"] },
]
# In the report (the final category) and in each breast's part (that breast's); the last BI-RADS edition, 7.3.4.1
# and 9.2.
[mastografia.resultados.birads]
etiqueta = "BI-RADS"
tipo_valor = "codigo"
@@ -30,7 +48,7 @@ valores = [
{ valor = "B6", etiqueta = "BI-RADS 6" },
]
# Read from the radiologist's interpretation (`mast_interpretacion`). Provisional: captions and spellings are
# In the report. Read from the radiologist's interpretation (`mast_interpretacion`). Provisional: captions and spellings are
# assumptions until the hospital's reports are seen; adding one is a line in `etiquetas_fuente` or `alias`.
[mastografia.resultados.densidad]
etiqueta = "Densidad mamaria (ACR)"
@@ -44,6 +62,51 @@ valores = [
{ valor = "D", etiqueta = "Extremadamente densa", alias = ["Tipo D", "ACR D", "Categoría D", "(D)", "Extremadamente densas"] },
]
# In each breast's part.
[mastografia.resultados.lateralidad]
etiqueta = "Mama"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Mama", "Lado", "Lateralidad"]
valores = [
{ valor = "DERECHA", etiqueta = "Derecha", alias = ["Mama derecha", "MD", "Der"] },
{ valor = "IZQUIERDA", etiqueta = "Izquierda", alias = ["Mama izquierda", "MI", "Izq"] },
]
# In each finding's part: the BI-RADS lexicon's kinds of finding.
[mastografia.resultados.tipo_hallazgo]
etiqueta = "Tipo de hallazgo"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Hallazgo", "Hallazgos", "Tipo de hallazgo"]
buscar_en_texto = true
valores = [
{ valor = "MASA", etiqueta = "Masa", alias = ["Masa", "Nódulo", "Tumoración"] },
{ valor = "CALCIFICACIONES", etiqueta = "Calcificaciones", alias = ["Calcificaciones", "Microcalcificaciones"] },
{ valor = "ASIMETRIA", etiqueta = "Asimetría", alias = ["Asimetría", "Asimetría focal", "Asimetría global", "Asimetría en desarrollo", "Densidad asimétrica"] },
{ valor = "DISTORSION_ARQUITECTURAL", etiqueta = "Distorsión de la arquitectura", alias = ["Distorsión de la arquitectura", "Distorsión arquitectural"] },
{ valor = "GANGLIO_INTRAMAMARIO", etiqueta = "Ganglio intramamario", alias = ["Ganglio intramamario"] },
{ valor = "LESION_CUTANEA", etiqueta = "Lesión cutánea", alias = ["Lesión cutánea", "Lesión de piel"] },
{ valor = "CONDUCTO_DILATADO", etiqueta = "Conducto dilatado solitario", alias = ["Conducto dilatado", "Ectasia ductal"] },
]
# In each finding's part that is a mass: its margin in the BI-RADS lexicon (5th edition). A spiculated margin is the
# strongest single sign of malignancy.
[mastografia.resultados.margen_masa]
etiqueta = "Margen de la masa"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Margen", "Márgenes", "Bordes", "Contorno"]
buscar_en_texto = true
valores = [
{ valor = "CIRCUNSCRITO", etiqueta = "Circunscrito", alias = ["Circunscrito", "Bien definido", "Bordes definidos", "Bordes regulares"] },
{ valor = "OSCURECIDO", etiqueta = "Oscurecido", alias = ["Oscurecido", "Obscurecido", "Parcialmente oscurecido"] },
{ valor = "MICROLOBULADO", etiqueta = "Microlobulado", alias = ["Microlobulado", "Microlobulados"] },
{ valor = "INDISTINTO", etiqueta = "Indistinto", alias = ["Indistinto", "Mal definido", "Bordes mal definidos", "Bordes irregulares"] },
{ valor = "ESPICULADO", etiqueta = "Espiculado", alias = ["Espiculado", "Espiculada", "Bordes espiculados", "Espículas"] },
]
# In each finding's part.
[mastografia.resultados.tamano_lesion_mm]
etiqueta = "Tamaño de la lesión"
tipo_valor = "numero"
@@ -51,10 +114,32 @@ unidad = "mm"
provisional = true
etiquetas_fuente = ["Tamaño de la lesión", "Tamaño del nódulo", "Diámetro mayor", "Mide"]
# In each finding's part: the subsite by its ICD-10 code, as `biopsia.localizacion`.
[mastografia.resultados.localizacion]
etiqueta = "Localización en la mama"
tipo_valor = "codigo"
sistema = "CIE-10"
provisional = true
etiquetas_fuente = ["Localización", "Cuadrante", "Sitio"]
valores = [
{ valor = "C500", etiqueta = "Pezón y areola", alias = ["C50.0", "Pezón", "Areola", "Retroareolar"] },
{ valor = "C501", etiqueta = "Porción central", alias = ["C50.1", "Central"] },
{ valor = "C502", etiqueta = "Cuadrante superior interno", alias = ["C50.2", "CSI", "Superior interno"] },
{ valor = "C503", etiqueta = "Cuadrante inferior interno", alias = ["C50.3", "CII", "Inferior interno"] },
{ valor = "C504", etiqueta = "Cuadrante superior externo", alias = ["C50.4", "CSE", "Superior externo"] },
{ valor = "C505", etiqueta = "Cuadrante inferior externo", alias = ["C50.5", "CIE", "Inferior externo"] },
{ valor = "C506", etiqueta = "Prolongación axilar", alias = ["C50.6", "Cola axilar", "Prolongación axilar"] },
{ valor = "C508", etiqueta = "Lesión de sitios contiguos", alias = ["C50.8", "Unión de cuadrantes", "Sitios contiguos"] },
{ valor = "C509", etiqueta = "Mama, parte no especificada", alias = ["C50.9", "No especificada"] },
]
# Biopsy and surgical specimen. Procedures: the `orden` (the request), one `toma` per breast (a surgical specimen's
# hangs from its `cirugia`) and its `reporte` (the pathology report, NOM-041-SSA2-2011 8.3.5).
[biopsia]
etiqueta = "Biopsia de mama"
codigos_hospital = ["BIOPSIA_CHICA"]
# In the report.
[biopsia.resultados.grado]
etiqueta = "Grado histológico"
tipo_valor = "codigo"
@@ -69,18 +154,146 @@ valores = [
etiqueta = "Fecha de solicitud"
tipo_valor = "fecha"
# Read from the pathology report's text layer (`bx_pdf_blob`). Provisional, as the mammography's.
[biopsia.resultados.tipo_histologico]
etiqueta = "Tipo histológico"
# In the toma (8.3.5.1).
[biopsia.resultados.lateralidad]
etiqueta = "Mama"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Tipo histológico", "Diagnóstico histopatológico", "Diagnóstico"]
etiquetas_fuente = ["Mama", "Lado", "Lateralidad"]
valores = [
{ valor = "DERECHA", etiqueta = "Derecha", alias = ["Mama derecha", "MD", "Der"] },
{ valor = "IZQUIERDA", etiqueta = "Izquierda", alias = ["Mama izquierda", "MI", "Izq"] },
]
# In the toma. The subsite of the breast by its ICD-10 code, as the hospital writes diagnoses (`nota_medica.diagnostico`);
# ICD-O-3's topography uses the same codes, so this is also the registry's anatomical site (Apéndice Normativo G).
[biopsia.resultados.localizacion]
etiqueta = "Localización en la mama"
tipo_valor = "codigo"
sistema = "CIE-10"
provisional = true
etiquetas_fuente = ["Localización", "Cuadrante", "Sitio", "Topografía"]
valores = [
{ valor = "C500", etiqueta = "Pezón y areola", alias = ["C50.0", "Pezón", "Areola", "Retroareolar"] },
{ valor = "C501", etiqueta = "Porción central", alias = ["C50.1", "Central"] },
{ valor = "C502", etiqueta = "Cuadrante superior interno", alias = ["C50.2", "CSI", "Superior interno"] },
{ valor = "C503", etiqueta = "Cuadrante inferior interno", alias = ["C50.3", "CII", "Inferior interno"] },
{ valor = "C504", etiqueta = "Cuadrante superior externo", alias = ["C50.4", "CSE", "Superior externo"] },
{ valor = "C505", etiqueta = "Cuadrante inferior externo", alias = ["C50.5", "CIE", "Inferior externo"] },
{ valor = "C506", etiqueta = "Prolongación axilar", alias = ["C50.6", "Cola axilar", "Prolongación axilar"] },
{ valor = "C508", etiqueta = "Lesión de sitios contiguos", alias = ["C50.8", "Unión de cuadrantes", "Sitios contiguos"] },
{ valor = "C509", etiqueta = "Mama, parte no especificada", alias = ["C50.9", "No especificada"] },
]
# In the toma: how the tissue was obtained (3.5, 8.3.4); a surgical specimen's surgery is its `cirugia`.
[biopsia.resultados.tipo_biopsia]
etiqueta = "Tipo de biopsia"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Tipo de biopsia", "Tipo de espécimen", "Tipo de muestra", "Procedimiento", "Espécimen"]
buscar_en_texto = true
valores = [
{ valor = "DUCTAL_INFILTRANTE", etiqueta = "Carcinoma ductal infiltrante", alias = ["Ductal infiltrante", "Carcinoma ductal invasor", "Carcinoma infiltrante de tipo no especial", "CDI"] },
{ valor = "LOBULILLAR_INFILTRANTE", etiqueta = "Carcinoma lobulillar infiltrante", alias = ["Lobulillar infiltrante", "Carcinoma lobulillar invasor", "CLI"] },
{ valor = "DUCTAL_IN_SITU", etiqueta = "Carcinoma ductal in situ", alias = ["Ductal in situ", "CDIS"] },
{ valor = "OTRO", etiqueta = "Otro tipo histológico" },
{ valor = "BAAF", etiqueta = "Aspiración con aguja fina", alias = ["BAAF", "Biopsia por aspiración con aguja fina", "Aspiración con aguja fina"] },
{ valor = "AGUJA_CORTE", etiqueta = "Aguja de corte grueso (14 a 18 G)", alias = ["Aguja de corte", "Aguja de corte grueso", "Biopsia con aguja de corte", "Tru-cut", "Trucut", "Core"] },
{ valor = "ASPIRACION_VACIO", etiqueta = "Aguja de corte con aspiración por vacío (8 a 14 G)", alias = ["Aspiración por vacío", "Biopsia asistida por vacío", "Mammotome", "BAV"] },
{ valor = "ESCISIONAL", etiqueta = "Biopsia escisional", alias = ["Escisional", "Biopsia escisional", "Biopsia excisional"] },
{ valor = "PIEZA_QUIRURGICA", etiqueta = "Pieza quirúrgica", alias = ["Pieza quirúrgica", "Segmentectomía", "Cuadrantectomía", "Mastectomía", "Tumorectomía", "Lumpectomía"] },
]
# Provisional, as the mammography's. The values are the
# WHO classification of breast tumours (NOM-041-SSA2-2011, 8.3.6 and Apéndice Informativo C) by their ICD-O-3
# morphology code, which the case registry asks for (Apéndice Normativo G). The NOM prints 8211/3 for medullary
# carcinoma and 8290/2 for oncocytic carcinoma; ICD-O-3 gives 8510/3 and 8290/3. A lesion the WHO list names
# without a code (atypical ductal hyperplasia, radial scar) isn't a value here.
[biopsia.resultados.tipo_histologico]
etiqueta = "Tipo histológico (OMS)"
tipo_valor = "codigo"
sistema = "CIE-O-3"
provisional = true
etiquetas_fuente = ["Tipo histológico", "Diagnóstico histopatológico", "Diagnóstico", "Variedad histológica"]
buscar_en_texto = true
valores = [
{ valor = "8500/3", etiqueta = "Carcinoma ductal invasivo (sin tipo especial)", alias = ["8500/3", "Carcinoma ductal infiltrante", "Ductal infiltrante", "Carcinoma ductal invasor", "Carcinoma infiltrante de tipo no especial", "Carcinoma ductal invasivo", "CDI"] },
{ valor = "8520/3", etiqueta = "Carcinoma lobulillar invasivo", alias = ["8520/3", "Carcinoma lobulillar infiltrante", "Lobulillar infiltrante", "Carcinoma lobulillar invasor", "Carcinoma lobular invasivo", "CLI"] },
{ valor = "8211/3", etiqueta = "Carcinoma tubular", alias = ["8211/3"] },
{ valor = "8201/3", etiqueta = "Carcinoma cribiforme invasivo", alias = ["8201/3", "Carcinoma cribiforme"] },
{ valor = "8510/3", etiqueta = "Carcinoma medular", alias = ["8510/3"] },
{ valor = "8480/3", etiqueta = "Carcinoma mucinoso", alias = ["8480/3", "Carcinoma coloide"] },
{ valor = "8490/3", etiqueta = "Carcinoma de células en anillo de sello", alias = ["8490/3"] },
{ valor = "8503/3", etiqueta = "Carcinoma papilar invasivo", alias = ["8503/3"] },
{ valor = "8507/3", etiqueta = "Carcinoma micropapilar invasivo", alias = ["8507/3"] },
{ valor = "8401/3", etiqueta = "Carcinoma apocrino", alias = ["8401/3", "Carcinoma apócrino"] },
{ valor = "8575/3", etiqueta = "Carcinoma metaplásico", alias = ["8575/3", "Carcinoma metaplásicos"] },
{ valor = "8070/3", etiqueta = "Carcinoma de células escamosas", alias = ["8070/3", "Carcinoma epidermoide"] },
{ valor = "8572/3", etiqueta = "Adenocarcinoma con metaplasia de células fusiformes", alias = ["8572/3"] },
{ valor = "8560/3", etiqueta = "Carcinoma adenoescamoso", alias = ["8560/3"] },
{ valor = "8430/3", etiqueta = "Carcinoma mucoepidermoide", alias = ["8430/3"] },
{ valor = "8022/3", etiqueta = "Carcinoma pleomórfico", alias = ["8022/3"] },
{ valor = "8035/3", etiqueta = "Carcinoma con células gigantes osteoclásticas", alias = ["8035/3", "Carcinoma con células osteoclásticas gigantes"] },
{ valor = "8249/3", etiqueta = "Carcinoma neuroendocrino sólido", alias = ["8249/3"] },
{ valor = "8041/3", etiqueta = "Carcinoma de células pequeñas", alias = ["8041/3", "Carcinoma de células avenoides pequeñas"] },
{ valor = "8013/3", etiqueta = "Carcinoma neuroendocrino de células grandes", alias = ["8013/3"] },
{ valor = "8314/3", etiqueta = "Carcinoma rico en lípidos", alias = ["8314/3"] },
{ valor = "8502/3", etiqueta = "Carcinoma secretor", alias = ["8502/3"] },
{ valor = "8290/3", etiqueta = "Carcinoma oncocítico", alias = ["8290/3"] },
{ valor = "8200/3", etiqueta = "Carcinoma adenoide quístico", alias = ["8200/3"] },
{ valor = "8550/3", etiqueta = "Carcinoma de células acinares", alias = ["8550/3", "Carcinoma de células acínicas"] },
{ valor = "8315/3", etiqueta = "Carcinoma de células claras rico en glucógeno", alias = ["8315/3"] },
{ valor = "8410/3", etiqueta = "Carcinoma sebáceo", alias = ["8410/3"] },
{ valor = "8530/3", etiqueta = "Carcinoma inflamatorio", alias = ["8530/3"] },
{ valor = "8540/3", etiqueta = "Enfermedad de Paget del pezón", alias = ["8540/3", "Enfermedad de Paget de la mama", "Enfermedad de Paget"] },
{ valor = "8982/3", etiqueta = "Mioepitelioma maligno", alias = ["8982/3"] },
{ valor = "9020/3", etiqueta = "Tumor filodes maligno", alias = ["9020/3"] },
{ valor = "9120/3", etiqueta = "Angiosarcoma", alias = ["9120/3"] },
{ valor = "8850/3", etiqueta = "Liposarcoma", alias = ["8850/3"] },
{ valor = "8900/3", etiqueta = "Rabdomiosarcoma", alias = ["8900/3"] },
{ valor = "9180/3", etiqueta = "Osteosarcoma", alias = ["9180/3"] },
{ valor = "8890/3", etiqueta = "Leiomiosarcoma", alias = ["8890/3"] },
{ valor = "9680/3", etiqueta = "Linfoma difuso de células B grandes", alias = ["9680/3", "Linfoma difuso de células B"] },
{ valor = "9687/3", etiqueta = "Linfoma de Burkitt", alias = ["9687/3"] },
{ valor = "9699/3", etiqueta = "Linfoma extranodal de células B tipo MALT", alias = ["9699/3"] },
{ valor = "9690/3", etiqueta = "Linfoma folicular", alias = ["9690/3"] },
# Not in the WHO list, but coded by cancer registries (SEER) for breast primaries.
{ valor = "8522/3", etiqueta = "Carcinoma ductal y lobulillar infiltrante", alias = ["8522/3", "Carcinoma ductal y lobulillar", "Carcinoma mixto ductal y lobulillar", "Carcinoma ductolobulillar"] },
{ valor = "8523/3", etiqueta = "Carcinoma ductal infiltrante mixto con otros tipos", alias = ["8523/3"] },
{ valor = "8521/3", etiqueta = "Carcinoma ductular infiltrante", alias = ["8521/3"] },
{ valor = "8541/3", etiqueta = "Enfermedad de Paget con carcinoma ductal infiltrante", alias = ["8541/3"] },
{ valor = "8543/3", etiqueta = "Enfermedad de Paget con carcinoma intraductal", alias = ["8543/3"] },
{ valor = "8509/3", etiqueta = "Carcinoma papilar sólido invasivo", alias = ["8509/3"] },
{ valor = "8504/3", etiqueta = "Carcinoma papilar encapsulado invasivo", alias = ["8504/3"] },
{ valor = "8050/3", etiqueta = "Carcinoma papilar, SAI", alias = ["8050/3"] },
{ valor = "8032/3", etiqueta = "Carcinoma de células fusiformes", alias = ["8032/3"] },
{ valor = "8246/3", etiqueta = "Carcinoma neuroendocrino, SAI", alias = ["8246/3"] },
{ valor = "8255/3", etiqueta = "Adenocarcinoma con subtipos mixtos", alias = ["8255/3"] },
{ valor = "8140/3", etiqueta = "Adenocarcinoma, SAI", alias = ["8140/3", "Adenocarcinoma"] },
{ valor = "8010/3", etiqueta = "Carcinoma, SAI", alias = ["8010/3", "Carcinoma"] },
{ valor = "8000/3", etiqueta = "Neoplasia maligna", alias = ["8000/3", "Neoplasia maligna", "Tumor maligno"] },
{ valor = "8500/2", etiqueta = "Carcinoma ductal in situ", alias = ["8500/2", "Ductal in situ", "Carcinoma intraductal", "CDIS"] },
{ valor = "8520/2", etiqueta = "Carcinoma lobulillar in situ", alias = ["8520/2", "Carcinoma lobular in situ", "CLIS"] },
{ valor = "8503/2", etiqueta = "Carcinoma papilar intraductal", alias = ["8503/2"] },
{ valor = "8504/2", etiqueta = "Carcinoma papilar intraquístico", alias = ["8504/2"] },
{ valor = "9020/1", etiqueta = "Tumor filodes limítrofe", alias = ["9020/1", "Tumor filodes borderline"] },
{ valor = "8821/1", etiqueta = "Fibromatosis (agresiva)", alias = ["8821/1"] },
{ valor = "8825/1", etiqueta = "Tumor miofibroblástico inflamatorio", alias = ["8825/1"] },
{ valor = "9150/1", etiqueta = "Hemangiopericitoma", alias = ["9150/1"] },
{ valor = "9010/0", etiqueta = "Fibroadenoma", alias = ["9010/0"] },
{ valor = "9020/0", etiqueta = "Tumor filodes benigno", alias = ["9020/0"] },
{ valor = "8503/0", etiqueta = "Papiloma intraductal", alias = ["8503/0", "Papiloma central", "Papiloma periférico", "Adenoma ductal"] },
{ valor = "8211/0", etiqueta = "Adenoma tubular", alias = ["8211/0"] },
{ valor = "8204/0", etiqueta = "Adenoma de la lactancia", alias = ["8204/0"] },
{ valor = "8401/0", etiqueta = "Adenoma apocrino", alias = ["8401/0", "Adenoma apócrino"] },
{ valor = "8940/0", etiqueta = "Adenoma pleomórfico", alias = ["8940/0"] },
{ valor = "8983/0", etiqueta = "Adenomioepitelioma", alias = ["8983/0"] },
{ valor = "8506/0", etiqueta = "Adenoma del pezón", alias = ["8506/0", "Adenoma de pezón"] },
{ valor = "8407/0", etiqueta = "Adenoma siringomatoso", alias = ["8407/0"] },
{ valor = "8825/0", etiqueta = "Miofibroblastoma", alias = ["8825/0"] },
{ valor = "9120/0", etiqueta = "Hemangioma", alias = ["9120/0"] },
{ valor = "8850/0", etiqueta = "Lipoma", alias = ["8850/0"] },
{ valor = "8861/0", etiqueta = "Angiolipoma", alias = ["8861/0"] },
{ valor = "9580/0", etiqueta = "Tumor de células granulares", alias = ["9580/0", "Tumor de células granulosas"] },
{ valor = "9540/0", etiqueta = "Neurofibroma", alias = ["9540/0"] },
{ valor = "9560/0", etiqueta = "Schwannoma", alias = ["9560/0"] },
{ valor = "8890/0", etiqueta = "Leiomioma", alias = ["8890/0"] },
]
[biopsia.resultados.grado_nottingham]
@@ -148,6 +361,127 @@ unidad = "%"
provisional = true
etiquetas_fuente = ["Ki-67", "Ki67", "Índice de proliferación"]
# The confirmation by in situ hybridization of an equivocal HER2 (Apéndice Informativo B: negative under 4 copies
# per nucleus or a HER2/CEP17 ratio under 1.8, positive over 6 or over 2.2).
[biopsia.resultados.her2_fish]
etiqueta = "HER2 (hibridación in situ)"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["FISH", "HER2 FISH", "Hibridación in situ", "SISH", "CISH"]
valores = [
{ valor = "NEGATIVO", etiqueta = "No amplificado", alias = ["Negativo", "No amplificado"] },
{ valor = "EQUIVOCO", etiqueta = "Equívoco", alias = ["Equívoco", "Indeterminado"] },
{ valor = "POSITIVO", etiqueta = "Amplificado", alias = ["Positivo", "Amplificado"] },
]
# The tumour's largest dimension; for an in situ carcinoma, its size or extent. T in `pt` is read from it
# (Apéndice Normativo E: T1 up to 20 mm, T2 up to 50 mm, T3 beyond).
[biopsia.resultados.tamano_tumor_mm]
etiqueta = "Tamaño del tumor"
tipo_valor = "numero"
unidad = "mm"
provisional = true
etiquetas_fuente = ["Tamaño del tumor", "Tamaño tumoral", "Tamaño de la lesión", "Extensión de la lesión", "Diámetro mayor", "Tumor mide"]
[biopsia.resultados.invasion_linfovascular]
etiqueta = "Invasión vascular o linfática"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Invasión linfovascular", "Invasión vascular", "Invasión linfática", "Permeación linfovascular", "Permeación vascular"]
valores = [
{ valor = "PRESENTE", etiqueta = "Presente", alias = ["Presente", "Positiva", "Sí", "Identificada"] },
{ valor = "AUSENTE", etiqueta = "Ausente", alias = ["Ausente", "Negativa", "No", "No identificada"] },
]
# The nodes: counts, which the St. Gallen risk categories read (Apéndice Normativo F: 1 to 3, 4 or more), and pN.
[biopsia.resultados.ganglios_examinados]
etiqueta = "Ganglios linfáticos examinados"
tipo_valor = "numero"
unidad = "ganglios"
provisional = true
etiquetas_fuente = ["Ganglios examinados", "Ganglios disecados", "Ganglios disecados totales", "Ganglios linfáticos examinados"]
[biopsia.resultados.ganglios_positivos]
etiqueta = "Ganglios linfáticos con metástasis"
tipo_valor = "numero"
unidad = "ganglios"
provisional = true
etiquetas_fuente = ["Ganglios positivos", "Ganglios con metástasis", "Ganglios metastásicos", "Ganglios comprometidos"]
# Pathological T and N (Apéndice Normativo E). The values are the AJCC categories the NOM lists, written as AJCC
# writes them; a subcategory the NOM doesn't list for N (N2a, N3b, a 7th or 8th edition's pN1a) is an alias of its
# category, and the node counts keep what it adds.
[biopsia.resultados.pt]
etiqueta = "T patológica (pT)"
tipo_valor = "codigo"
sistema = "TNM-AJCC"
provisional = true
etiquetas_fuente = ["pT", "T patológica", "Tumor primario (pT)"]
valores = [
{ valor = "TX", etiqueta = "TX", alias = ["pTX"] },
{ valor = "T0", etiqueta = "T0", alias = ["pT0"] },
{ valor = "Tis", etiqueta = "Tis", alias = ["pTis"] },
{ valor = "T1mi", etiqueta = "T1mi", alias = ["pT1mi", "T1mic", "pT1mic"] },
{ valor = "T1a", etiqueta = "T1a", alias = ["pT1a"] },
{ valor = "T1b", etiqueta = "T1b", alias = ["pT1b"] },
{ valor = "T1c", etiqueta = "T1c", alias = ["pT1c"] },
{ valor = "T1", etiqueta = "T1", alias = ["pT1"] },
{ valor = "T2", etiqueta = "T2", alias = ["pT2"] },
{ valor = "T3", etiqueta = "T3", alias = ["pT3"] },
{ valor = "T4a", etiqueta = "T4a", alias = ["pT4a"] },
{ valor = "T4b", etiqueta = "T4b", alias = ["pT4b"] },
{ valor = "T4c", etiqueta = "T4c", alias = ["pT4c"] },
{ valor = "T4d", etiqueta = "T4d", alias = ["pT4d"] },
{ valor = "T4", etiqueta = "T4", alias = ["pT4"] },
]
[biopsia.resultados.pn]
etiqueta = "N patológica (pN)"
tipo_valor = "codigo"
sistema = "TNM-AJCC"
provisional = true
etiquetas_fuente = ["pN", "N patológica", "Ganglios linfáticos regionales (pN)"]
valores = [
{ valor = "NX", etiqueta = "NX", alias = ["pNX"] },
{ valor = "N0", etiqueta = "N0", alias = ["pN0", "pN0(i-)", "pN0(i+)", "pN0(mol-)", "pN0(mol+)"] },
{ valor = "N1", etiqueta = "N1", alias = ["pN1", "pN1mi", "pN1a", "pN1b", "pN1c", "pN1bI", "pN1bII", "pN1bIII", "pN1bIV"] },
{ valor = "N2", etiqueta = "N2", alias = ["pN2", "pN2a", "pN2b"] },
{ valor = "N3", etiqueta = "N3", alias = ["pN3", "pN3a", "pN3b", "pN3c"] },
]
# In the report of an excisional or surgical specimen (8.3.5.8): a needle biopsy has none of these.
[biopsia.resultados.margenes]
etiqueta = "Márgenes quirúrgicos"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Márgenes quirúrgicos", "Márgenes", "Bordes quirúrgicos", "Bordes de sección", "Lechos quirúrgicos"]
valores = [
{ valor = "LIBRES", etiqueta = "Libres", alias = ["Libres", "Negativos", "Libres de neoplasia", "Sin neoplasia"] },
{ valor = "CERCANOS", etiqueta = "Cercanos", alias = ["Cercanos", "Próximos"] },
{ valor = "AFECTADOS", etiqueta = "Afectados", alias = ["Afectados", "Positivos", "Comprometidos", "Con neoplasia"] },
]
[biopsia.resultados.multicentricidad]
etiqueta = "Multicentricidad"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Multicentricidad", "Multicéntrico"]
valores = [
{ valor = "PRESENTE", etiqueta = "Presente", alias = ["Presente", "Sí", "Multicéntrico"] },
{ valor = "AUSENTE", etiqueta = "Ausente", alias = ["Ausente", "No", "Unicéntrico"] },
]
[biopsia.resultados.multifocalidad]
etiqueta = "Multifocalidad"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Multifocalidad", "Multifocal"]
valores = [
{ valor = "PRESENTE", etiqueta = "Presente", alias = ["Presente", "Sí", "Multifocal"] },
{ valor = "AUSENTE", etiqueta = "Ausente", alias = ["Ausente", "No", "Unifocal"] },
]
# Medical note: an `encuentro`.
[nota_medica]
etiqueta = "Nota médica"
@@ -181,9 +515,308 @@ tipo_valor = "codigo"
valores = [
{ valor = "MEDICINA_FAMILIAR", etiqueta = "Medicina familiar" },
{ valor = "CIRUGIA_ONCOLOGICA", etiqueta = "Cirugía oncológica" },
{ valor = "ONCOLOGIA_MEDICA", etiqueta = "Oncología médica" },
{ valor = "CLINICA_MUJER_COLPOSCOPIA", etiqueta = "Clínica de la mujer (colposcopia)" },
]
# The kind of visit, as Core's `TipoNota`. A discharge note (EGRESO, URG_EGRESO) is where a discharge reason, death
# among them, would be written: survival's outcome.
[nota_medica.resultados.tipo_nota]
etiqueta = "Tipo de nota"
tipo_valor = "codigo"
valores = [
{ valor = "CONSULTA", etiqueta = "Consulta" },
{ valor = "INGRESO", etiqueta = "Ingreso hospitalario" },
{ valor = "EGRESO", etiqueta = "Egreso hospitalario" },
{ valor = "URG_EGRESO", etiqueta = "Egreso de urgencias" },
]
# Clinical T, N and M (Apéndice Normativo E).
[nota_medica.resultados.ct]
etiqueta = "T clínica (cT)"
tipo_valor = "codigo"
sistema = "TNM-AJCC"
provisional = true
etiquetas_fuente = ["cT", "T clínica", "Tumor primario"]
valores = [
{ valor = "TX", etiqueta = "TX", alias = ["cTX"] },
{ valor = "T0", etiqueta = "T0", alias = ["cT0"] },
{ valor = "Tis", etiqueta = "Tis", alias = ["cTis"] },
{ valor = "T1mi", etiqueta = "T1mi", alias = ["cT1mi", "T1mic"] },
{ valor = "T1a", etiqueta = "T1a", alias = ["cT1a"] },
{ valor = "T1b", etiqueta = "T1b", alias = ["cT1b"] },
{ valor = "T1c", etiqueta = "T1c", alias = ["cT1c"] },
{ valor = "T1", etiqueta = "T1", alias = ["cT1"] },
{ valor = "T2", etiqueta = "T2", alias = ["cT2"] },
{ valor = "T3", etiqueta = "T3", alias = ["cT3"] },
{ valor = "T4a", etiqueta = "T4a", alias = ["cT4a"] },
{ valor = "T4b", etiqueta = "T4b", alias = ["cT4b"] },
{ valor = "T4c", etiqueta = "T4c", alias = ["cT4c"] },
{ valor = "T4d", etiqueta = "T4d", alias = ["cT4d", "Carcinoma inflamatorio"] },
{ valor = "T4", etiqueta = "T4", alias = ["cT4"] },
]
[nota_medica.resultados.cn]
etiqueta = "N clínica (cN)"
tipo_valor = "codigo"
sistema = "TNM-AJCC"
provisional = true
etiquetas_fuente = ["cN", "N clínica", "Ganglios linfáticos regionales"]
valores = [
{ valor = "NX", etiqueta = "NX", alias = ["cNX"] },
{ valor = "N0", etiqueta = "N0", alias = ["cN0"] },
{ valor = "N1", etiqueta = "N1", alias = ["cN1", "N1mi"] },
{ valor = "N2", etiqueta = "N2", alias = ["cN2", "N2a", "N2b", "cN2a", "cN2b"] },
{ valor = "N3", etiqueta = "N3", alias = ["cN3", "N3a", "N3b", "N3c", "cN3a", "cN3b", "cN3c"] },
]
[nota_medica.resultados.m]
etiqueta = "Metástasis a distancia (M)"
tipo_valor = "codigo"
sistema = "TNM-AJCC"
provisional = true
etiquetas_fuente = ["Metástasis a distancia", "Metástasis distante", "cM"]
valores = [
{ valor = "MX", etiqueta = "MX", alias = ["cMX"] },
{ valor = "M0", etiqueta = "M0", alias = ["cM0", "Mo", "M0(i+)"] },
{ valor = "M1", etiqueta = "M1", alias = ["cM1", "pM1"] },
]
# The visit's body measurements.
[nota_medica.resultados.peso]
etiqueta = "Peso"
tipo_valor = "numero"
unidad = "kg"
[nota_medica.resultados.talla]
etiqueta = "Talla"
tipo_valor = "numero"
unidad = "m"
[nota_medica.resultados.imc]
etiqueta = "Índice de masa corporal"
tipo_valor = "numero"
unidad = "kg/m2"
# The risk factors the clinical history investigates (NOM-041-SSA2-2011, 7.1.1 and 8.2.1.1): a `parte` hanging from
# the document they were recorded in (a note, a mammogram's intake interview), dated by it, so what changes
# (menopause) is read as of a date. Age comes from the birth date, density from the mammogram, BRCA from its own
# test (`prueba_genetica`).
[factores_riesgo]
etiqueta = "Factores de riesgo"
[factores_riesgo.resultados.menarca_edad]
etiqueta = "Edad a la menarca"
tipo_valor = "numero"
unidad = "años"
provisional = true
etiquetas_fuente = ["Menarca", "Menarquia", "Edad de menarca", "Edad a la menarca"]
[factores_riesgo.resultados.menopausia]
etiqueta = "Estado menopáusico"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Menopausia", "Estado menopáusico", "Estado hormonal", "Climaterio"]
valores = [
{ valor = "PREMENOPAUSICA", etiqueta = "Premenopáusica", alias = ["Premenopausia", "Premenopáusica", "No"] },
{ valor = "PERIMENOPAUSICA", etiqueta = "Perimenopáusica", alias = ["Perimenopausia", "Perimenopáusica", "Climaterio"] },
{ valor = "POSTMENOPAUSICA", etiqueta = "Postmenopáusica", alias = ["Postmenopausia", "Postmenopáusica", "Posmenopausia", "Posmenopáusica", "Sí"] },
]
[factores_riesgo.resultados.menopausia_edad]
etiqueta = "Edad a la menopausia"
tipo_valor = "numero"
unidad = "años"
provisional = true
etiquetas_fuente = ["Edad de menopausia", "Edad a la menopausia", "Menopausia a los"]
[factores_riesgo.resultados.gestas]
etiqueta = "Embarazos (gestas)"
tipo_valor = "numero"
unidad = "embarazos"
provisional = true
etiquetas_fuente = ["Gestas", "Gesta", "Embarazos", "Número de embarazos"]
[factores_riesgo.resultados.primer_embarazo_edad]
etiqueta = "Edad al primer embarazo a término"
tipo_valor = "numero"
unidad = "años"
provisional = true
etiquetas_fuente = ["Edad al primer embarazo", "Primer embarazo a término", "Edad al primer hijo", "Primer embarazo", "Primer parto"]
[factores_riesgo.resultados.familiares_primer_grado]
etiqueta = "Familiares de primer grado con cáncer de mama"
tipo_valor = "numero"
unidad = "familiares"
provisional = true
etiquetas_fuente = ["Familiares de primer grado con cáncer de mama", "Antecedentes familiares de cáncer de mama", "AHF cáncer de mama"]
[factores_riesgo.resultados.biopsia_previa]
etiqueta = "Biopsia o procedimiento mamario previo"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Biopsia previa", "Biopsias previas", "Procedimientos mamarios previos", "Cirugías mamarias previas"]
valores = [
{ valor = "SI", etiqueta = "Sí", alias = ["Sí", "Si", "Positiva"] },
{ valor = "NO", etiqueta = "No", alias = ["No", "Negativa", "Negada", "Ninguna"] },
]
[factores_riesgo.resultados.lesion_previa_alto_riesgo]
etiqueta = "Lesión de alto riesgo en biopsia previa"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Resultado de biopsia previa", "Antecedente de biopsia", "Hallazgo previo"]
valores = [
{ valor = "HIPERPLASIA_DUCTAL_ATIPICA", etiqueta = "Hiperplasia ductal atípica", alias = ["Hiperplasia ductal atípica", "HDA"] },
{ valor = "CARCINOMA_LOBULILLAR_IN_SITU", etiqueta = "Carcinoma lobulillar in situ", alias = ["Carcinoma lobulillar in situ", "Carcinoma lobular in situ", "CLIS"] },
{ valor = "CICATRIZ_RADIAL", etiqueta = "Imagen radial o estrellada", alias = ["Cicatriz radial", "Imagen radial", "Imagen estrellada", "Lesión esclerosante compleja"] },
]
[factores_riesgo.resultados.terapia_hormonal_anos]
etiqueta = "Terapia hormonal en la peri o postmenopausia"
tipo_valor = "numero"
unidad = "años"
provisional = true
etiquetas_fuente = ["Terapia hormonal de reemplazo", "Terapia de reemplazo hormonal", "TRH"]
[factores_riesgo.resultados.radioterapia_torax]
etiqueta = "Radioterapia previa en tórax"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Radioterapia en tórax", "Radioterapia previa", "Radiación torácica"]
valores = [
{ valor = "SI", etiqueta = "Sí", alias = ["Sí", "Si", "Positiva"] },
{ valor = "NO", etiqueta = "No", alias = ["No", "Negativa", "Negada"] },
]
# What the record says about the patient that changes over time: a `parte` hanging from the document that records it
# (the admission sheet, a note), dated by it, so it's read as of a date.
[sociodemografico]
etiqueta = "Datos sociodemográficos"
[sociodemografico.resultados.estado_civil]
etiqueta = "Estado civil"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Estado civil", "Edo. civil", "Edo civil"]
valores = [
{ valor = "SOLTERA", etiqueta = "Soltera", alias = ["Soltera", "Soltero", "S"] },
{ valor = "CASADA", etiqueta = "Casada", alias = ["Casada", "Casado", "C"] },
{ valor = "UNION_LIBRE", etiqueta = "Unión libre", alias = ["Unión libre", "Union libre", "Concubinato", "UL"] },
{ valor = "SEPARADA", etiqueta = "Separada", alias = ["Separada", "Separado"] },
{ valor = "DIVORCIADA", etiqueta = "Divorciada", alias = ["Divorciada", "Divorciado", "D"] },
{ valor = "VIUDA", etiqueta = "Viuda", alias = ["Viuda", "Viudo", "V"] },
]
# The BRCA1 and BRCA2 test (7.1.1.1.7, 7.5.3): `orden`, `toma` and its `reporte`. Each gene gets the class of the
# variant found, in the ACMG/AMP five tiers, or NEGATIVO when the report finds none.
[prueba_genetica]
etiqueta = "Prueba genética (BRCA1 y BRCA2)"
[prueba_genetica.resultados.brca1]
etiqueta = "BRCA1"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["BRCA1"]
valores = [
{ valor = "PATOGENICA", etiqueta = "Variante patogénica", alias = ["Patogénica", "Mutación patogénica", "Positivo"] },
{ valor = "PROBABLEMENTE_PATOGENICA", etiqueta = "Variante probablemente patogénica", alias = ["Probablemente patogénica"] },
{ valor = "SIGNIFICADO_INCIERTO", etiqueta = "Variante de significado incierto", alias = ["Significado incierto", "VUS", "VSI"] },
{ valor = "PROBABLEMENTE_BENIGNA", etiqueta = "Variante probablemente benigna", alias = ["Probablemente benigna"] },
{ valor = "BENIGNA", etiqueta = "Variante benigna", alias = ["Benigna"] },
{ valor = "NEGATIVO", etiqueta = "Sin variantes", alias = ["Negativo", "No se detectaron variantes", "Sin mutación"] },
]
[prueba_genetica.resultados.brca2]
etiqueta = "BRCA2"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["BRCA2"]
valores = [
{ valor = "PATOGENICA", etiqueta = "Variante patogénica", alias = ["Patogénica", "Mutación patogénica", "Positivo"] },
{ valor = "PROBABLEMENTE_PATOGENICA", etiqueta = "Variante probablemente patogénica", alias = ["Probablemente patogénica"] },
{ valor = "SIGNIFICADO_INCIERTO", etiqueta = "Variante de significado incierto", alias = ["Significado incierto", "VUS", "VSI"] },
{ valor = "PROBABLEMENTE_BENIGNA", etiqueta = "Variante probablemente benigna", alias = ["Probablemente benigna"] },
{ valor = "BENIGNA", etiqueta = "Variante benigna", alias = ["Benigna"] },
{ valor = "NEGATIVO", etiqueta = "Sin variantes", alias = ["Negativo", "No se detectaron variantes", "Sin mutación"] },
]
# Treatment (10.2.5): a procedure per method, an `orden` when a note indicates it and an `encuentro` when it was done;
# one per course, surgery and radiotherapy one per breast. The procedure's date is the start.
[cirugia]
etiqueta = "Cirugía de mama"
[cirugia.resultados.lateralidad]
etiqueta = "Mama"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Mama", "Lado", "Lateralidad"]
valores = [
{ valor = "DERECHA", etiqueta = "Derecha", alias = ["Mama derecha", "MD", "Der"] },
{ valor = "IZQUIERDA", etiqueta = "Izquierda", alias = ["Mama izquierda", "MI", "Izq"] },
]
[cirugia.resultados.tipo_cirugia]
etiqueta = "Tipo de cirugía"
tipo_valor = "codigo"
valores = [
{ valor = "ESCISIONAL", etiqueta = "Biopsia escisional o tumorectomía" },
{ valor = "SEGMENTECTOMIA", etiqueta = "Segmentectomía o cuadrantectomía" },
{ valor = "MASTECTOMIA_TOTAL", etiqueta = "Mastectomía total" },
{ valor = "MASTECTOMIA_RADICAL_MODIFICADA", etiqueta = "Mastectomía radical modificada" },
]
[cirugia.resultados.cirugia_axilar]
etiqueta = "Cirugía axilar"
tipo_valor = "codigo"
valores = [
{ valor = "NINGUNA", etiqueta = "Ninguna" },
{ valor = "GANGLIO_CENTINELA", etiqueta = "Ganglio centinela" },
{ valor = "DISECCION_AXILAR", etiqueta = "Disección axilar" },
]
[radioterapia]
etiqueta = "Radioterapia"
[radioterapia.resultados.intencion]
etiqueta = "Intención"
tipo_valor = "codigo"
valores = [
{ valor = "NEOADYUVANTE", etiqueta = "Neoadyuvante" },
{ valor = "ADYUVANTE", etiqueta = "Adyuvante" },
{ valor = "PALIATIVA", etiqueta = "Paliativa" },
]
[radioterapia.resultados.lateralidad]
etiqueta = "Mama"
tipo_valor = "codigo"
provisional = true
etiquetas_fuente = ["Mama", "Lado", "Lateralidad"]
valores = [
{ valor = "DERECHA", etiqueta = "Derecha", alias = ["Mama derecha", "MD", "Der"] },
{ valor = "IZQUIERDA", etiqueta = "Izquierda", alias = ["Mama izquierda", "MI", "Izq"] },
]
[radioterapia.resultados.fecha_fin]
etiqueta = "Fecha de término"
tipo_valor = "fecha"
[quimioterapia]
etiqueta = "Quimioterapia"
[quimioterapia.resultados.intencion]
etiqueta = "Intención"
tipo_valor = "codigo"
valores = [
{ valor = "NEOADYUVANTE", etiqueta = "Neoadyuvante" },
{ valor = "ADYUVANTE", etiqueta = "Adyuvante" },
{ valor = "PALIATIVA", etiqueta = "Paliativa" },
]
[quimioterapia.resultados.fecha_fin]
etiqueta = "Fecha de término"
tipo_valor = "fecha"
# Los datos de una orden (procedimiento con clase `orden`; su `estudio_id` es el estudio pedido, de
# `codigos_hospital`). ADR-MD-007.
[orden]
@@ -215,5 +848,18 @@ tipo_valor = "codigo"
valores = [
{ valor = "MEDICINA_FAMILIAR", etiqueta = "Medicina familiar" },
{ valor = "CIRUGIA_ONCOLOGICA", etiqueta = "Cirugía oncológica" },
{ valor = "ONCOLOGIA_MEDICA", etiqueta = "Oncología médica" },
{ valor = "CLINICA_MUJER_COLPOSCOPIA", etiqueta = "Clínica de la mujer (colposcopia)" },
]
# Left out of the minimum, to add later (NOM-041-SSA2-2011):
# mastografia axillary nodes (per breast), clock position (per finding)
# biopsia date taken (8.3.5 b); nuclear grade, mitotic index and tubule formation (8.3.5.5; the Nottingham
# total suffices); architectural pattern, necrosis, microcalcifications, specimen size, closest
# margin, coexisting intraductal carcinoma and its extent (Apéndice Informativo B); extracapsular
# invasion, size and site of the metastasis (8.3.5.8.5, 8.3.5.8.6); receptors' H-score
# nota_medica the St. Gallen category as the note writes it (10.3.3; dbt derives it from the report)
# factores_riesgo breastfeeding (7.1.1.6), implants (Apéndice Informativo D)
# treatment reconstruction (10.2.3); radiotherapy's dose, fractions and site; chemotherapy's cycles and
# regimen; hormone and biological therapy (10.2.5.4, 10.2.5.5)
+309 -25
View File
@@ -196,13 +196,39 @@ etiqueta = "Diagnóstico"
tipo_valor = "externo"
sistema = "CIE-10"
# The EEG: what its analysis writes. On the recording (`toma`), the sleep, channels, duration, the five quality
# criteria and each metric's measured value; on each electrode (`parte`, `codigo_fuente` the electrode), the metric's
# z-score there, under the same result.
# 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`) and the curve's p5, median and p95 there. 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"
@@ -217,55 +243,313 @@ etiqueta = "Duración del registro"
tipo_valor = "numero"
unidad = "min"
[eeg.resultados.calidad_amplitud]
etiqueta = "Canales con amplitud extrema"
tipo_valor = "numero"
unidad = "canales"
[eeg.resultados.calidad_alta_frecuencia]
etiqueta = "Ruido de alta frecuencia"
tipo_valor = "numero"
unidad = "canales"
[eeg.resultados.calidad_correlacion]
etiqueta = "Baja correlación entre canales"
tipo_valor = "numero"
unidad = "canales"
[eeg.resultados.calidad_sin_senal]
etiqueta = "Canales planos o sin señal"
tipo_valor = "numero"
unidad = "canales"
[eeg.resultados.calidad_linea]
[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.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_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.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.gradiente_anteroposterior]
etiqueta = "Gradiente anteroposterior"
tipo_valor = "numero"
unidad = "razón posterior/anterior"
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"
# An order (procedure of class `orden`): its `estudio_id` is the study it asks for, from `codigos_hospital`.
[orden]
+3 -1
View File
@@ -99,7 +99,9 @@ class EvaluacionRiesgoBase(SQLModel):
evaluacion_id: int | None = Field(default=None, primary_key=True)
lote_id: int = Field(foreign_key="evaluacion_riesgo_lote.lote_id", index=True)
pac_id: int = Field(foreign_key="persona.pac_id") # subject
horizonte_anios: float # prediction.when: años desde la fecha índice; 0 = prevalente
# El punto de decisión desde el que el modelo predice para esta paciente (lo define el modelo, no la cohorte).
fecha_indice: date
horizonte_anios: float # prediction.when: años desde `fecha_indice`; 0 = prevalente
probabilidad: float # prediction.probabilityDecimal, de 0 a 1
# Incertidumbre, si el modelo la da (solo con un Hessiano definido positivo). Nula si no.
ic_bajo: float | None = None
+22
View File
@@ -54,6 +54,28 @@ class MetricaEeg(str, Enum):
GRADIENTE_ANTEROPOSTERIOR = "GRADIENTE_ANTEROPOSTERIOR"
class CriterioEeg(str, Enum):
"""cri_codigo in table eeg_criterio: the EEG analysis's check codes, channel reasons without their numbers."""
ARCHIVO = "file"
VENTANAS_LIMPIAS = "clean-windows"
COBERTURA_INTERNA = "internal-coverage"
CUERO_CABELLUDO_MALO = "bad-scalp-triage"
CUERO_CABELLUDO_UTIL = "usable-scalp"
NIVEL_TRIAJE = "triage-level"
RUIDO_LINEA = "line-noise"
CANAL_MUERTO = "dead-channel"
CONGELADO = "frozen"
SATURADO = "saturated"
VALORES_INF = "inf-values"
HUECOS_PROPIOS = "own-gaps"
PUENTE = "bridge"
AMPLITUD = "amplitude"
AMPLITUD_AUXILIAR = "aux-amplitude"
SIN_CORRELACION = "does-not-correlate"
CONTACTO_INTERMITENTE = "intermittent-contact"
CONTACTO_POR_RAFAGAS = "intermittent-bursts"
# The electrodes of the 10-20 system an electrode value can name (mel_electrodo).
ELECTRODOS_10_20 = (
"Fp1", "Fp2", "F7", "F3", "Fz", "F4", "F8", "T3", "C3", "Cz", "C4", "T4",
+44 -8
View File
@@ -1,14 +1,14 @@
"""TEA staging tables (data dictionary: spec/tablas_TEA.md).
One table per kind of study: the M-CHAT, the ADOS-2, the neuropediatrics note and the EEG, with the patients and
the orders. The EEG's quality criteria, channels, duration, sleep, metrics and electrode values are written by the
EEG analysis from the stored EDF.
the orders. The EEG's verdict, quality checks, channels, duration, sleep, metrics and electrode values are written
by the EEG analysis (the `tea` library) from the stored EDF.
Permissive storage: every domain field is optional so a load never rejects a row; booleans are INTEGER and enums
TEXT. Coercion and validation happen in the import schemas (WebApi/webapi/imports/schemas/tea).
"""
import uuid
from datetime import date
from datetime import date, datetime
from typing import Optional
import sqlalchemy as sa
@@ -49,6 +49,10 @@ def _date() -> Field:
return Field(default=None, sa_column=sa.Column(sa.Date))
def _datetime() -> Field:
return Field(default=None, sa_column=sa.Column(sa.DateTime))
class Pacientes(TeaModel, table=True):
__tablename__ = "pacientes"
@@ -152,13 +156,37 @@ class Eeg(TeaModel, table=True):
eeg_con_sueno: Optional[int] = _int()
eeg_canales: Optional[int] = _int()
eeg_duracion_min: Optional[float] = _float()
# Quality criteria: channels flagged by each one, and the line noise. An EEG is bad when any criterion is.
eeg_canales_amplitud: Optional[int] = _int()
eeg_canales_alta_frecuencia: Optional[int] = _int()
eeg_canales_correlacion: Optional[int] = _int()
eeg_canales_sin_senal: Optional[int] = _int()
eeg_ruido_linea_db: Optional[float] = _float()
eeg_estudio: Optional[bytes] = Field(default=None, sa_column=sa.Column(FileBlob)) # the EDF
# The analysis's verdict: 1 valid, 0 not valid, null not analysed yet. Its checks are rows of eeg_criterio.
eeg_valido: Optional[int] = _int()
eeg_nivel: Optional[str] = _text() # triage level: completo, sin_referencia_auricular, parcial, no_analizable
eeg_fraccion_limpia: Optional[float] = _float()
eeg_canales_malos: Optional[int] = _int()
eeg_edad_meses: Optional[float] = _float() # the age the analysis compared the metrics at
# What produced the analysis, so a new plan or module version analyses the EEG again.
eeg_plan_hash: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(16)))
eeg_versiones: Optional[str] = _text()
eeg_analizado_en: Optional[datetime] = _datetime()
eeg_error: Optional[str] = _text()
class EegCriterio(TeaModel, table=True):
"""One quality check the EEG analysis evaluated on an EEG: a study rule, or a bad channel with its electrode."""
__tablename__ = "eeg_criterio"
cri_id: Optional[str] = _id()
cri_eeg_id: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(36), index=True))
cri_codigo: Optional[str] = _text() # CriterioEeg
cri_electrodo: Optional[str] = _text()
cri_valor: Optional[float] = _float()
cri_valor_texto: Optional[str] = _text()
cri_unidad: Optional[str] = _text()
cri_bajo: Optional[float] = _float() # out of range below this
cri_alto: Optional[float] = _float() # out of range above this
cri_decisivo: Optional[int] = _int() # this check alone can make the EEG not valid
cri_anormal: Optional[int] = _int()
class EegMetrica(TeaModel, table=True):
@@ -170,6 +198,13 @@ class EegMetrica(TeaModel, table=True):
met_eeg_id: Optional[str] = _text()
met_codigo: Optional[str] = _text() # MetricaEeg
met_valor: Optional[float] = _float()
# Against the age baseline at eeg_edad_meses: z, -1/0/+1 below p5 / within / above p95, and the curve there.
met_z: Optional[float] = _float()
met_fuera: Optional[int] = _int()
met_p5: Optional[float] = _float()
met_mediana: Optional[float] = _float()
met_p95: Optional[float] = _float()
met_modelo: Optional[str] = _text() # the baseline's registered model version
class EegMetricaElectrodo(TeaModel, table=True):
@@ -181,3 +216,4 @@ class EegMetricaElectrodo(TeaModel, table=True):
mel_met_id: Optional[str] = _text()
mel_electrodo: Optional[str] = _text()
mel_valor: Optional[float] = _float()
mel_z: Optional[float] = _float()
+46 -14
View File
@@ -5,8 +5,8 @@ neuropediatría y EEG), más los pacientes y las órdenes. Para cada tabla se li
la unidad (cuando aplica) y la validación que cumple cada una al importarse. El almacenamiento es permisivo: todo
campo es opcional y la validación ocurre en los esquemas de importación (`WebApi/webapi/imports/schemas/tea`).
Las columnas marcadas **(análisis del EEG)** las escribe el análisis del EEG a partir del EDF guardado: calidad,
canales, duración, sueño, métricas y valores por electrodo.
Las columnas marcadas **(análisis del EEG)** las escribe el análisis del EEG (la biblioteca `tea`) a partir del EDF
guardado: veredicto, criterios de calidad, canales, duración, sueño, métricas y valores por electrodo.
---
@@ -88,19 +88,46 @@ Los subtotales por dominio y el total no se guardan: son sumas de los puntajes d
| `eeg_con_sueno` | INTEGER | — | 0 o 1. **(análisis del EEG)** | — |
| `eeg_canales` | INTEGER | canales | Entre 1 y 256. **(análisis del EEG)** | — |
| `eeg_duracion_min` | FLOAT | minutos | Mayor que 0. **(análisis del EEG)** | — |
| `eeg_canales_amplitud` | INTEGER | canales | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
| `eeg_canales_alta_frecuencia` | INTEGER | canales | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
| `eeg_canales_correlacion` | INTEGER | canales | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
| `eeg_canales_sin_senal` | INTEGER | canales | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
| `eeg_ruido_linea_db` | FLOAT | dB | Mayor o igual que 0. Criterio de calidad. **(análisis del EEG)** | — |
| `eeg_ruido_linea_db` | FLOAT | dB | Mayor o igual que 0: la mediana del ruido de la línea eléctrica en el cuero cabelludo. **(análisis del EEG)** | — |
| `eeg_estudio` | BLOB (LONGBLOB en MySQL) | — | El archivo EDF. | — |
| `eeg_valido` | INTEGER | — | 1 válido, 0 no válido; nulo: sin analizar. **(análisis del EEG)** | — |
| `eeg_nivel` | TEXT | — | Nivel de triaje: `completo`, `sin_referencia_auricular`, `parcial` o `no_analizable`. **(análisis del EEG)** | — |
| `eeg_fraccion_limpia` | FLOAT | fracción | Entre 0 y 1: la parte del registro en ventanas limpias. **(análisis del EEG)** | — |
| `eeg_canales_malos` | INTEGER | canales | Mayor o igual que 0. **(análisis del EEG)** | — |
| `eeg_edad_meses` | FLOAT | meses | La edad a la fecha del estudio con que se compararon las métricas; nula sin fecha de nacimiento. **(análisis del EEG)** | — |
| `eeg_plan_hash` | VARCHAR(16) | — | El plan de preprocesamiento con que se analizó. **(análisis del EEG)** | — |
| `eeg_versiones` | TEXT | — | Las versiones de los módulos del análisis (`nombre=versión;…`). **(análisis del EEG)** | — |
| `eeg_analizado_en` | DATETIME | — | Cuándo se analizó. **(análisis del EEG)** | — |
| `eeg_error` | TEXT | — | Por qué el análisis no terminó; nulo si terminó. **(análisis del EEG)** | — |
Un EEG es malo cuando cualquiera de sus criterios de calidad está fuera de su umbral; uno malo no tiene resultado y
sus alteraciones no cuentan.
Un EEG es válido cuando el análisis lo dice (`eeg_valido` = 1): ninguna regla decisiva de `eeg_criterio` fuera de su
umbral y el registro dentro de las condiciones del plan de preprocesamiento. Uno no válido no tiene resultado y sus
alteraciones no cuentan.
---
## 7. Tabla `eeg_metrica` **(análisis del EEG)**
## 7. Tabla `eeg_criterio` **(análisis del EEG)**
Un renglón por cada regla de calidad que el análisis evaluó sobre un EEG: las del estudio completo y, para cada canal
malo, el motivo con su electrodo.
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `cri_id` | VARCHAR(36), llave primaria | — | — | — |
| `cri_eeg_id` | VARCHAR(36), indexado | — | — | → `eeg.eeg_id` |
| `cri_codigo` | TEXT | — | Catálogo `CriterioEeg`: del estudio `file, clean-windows, internal-coverage, bad-scalp-triage, usable-scalp, triage-level, line-noise`; de un canal `dead-channel, frozen, saturated, inf-values, own-gaps, bridge, amplitude, aux-amplitude, does-not-correlate, intermittent-contact, intermittent-bursts`. | — |
| `cri_electrodo` | TEXT | — | El canal del motivo; nulo en las reglas del estudio. | — |
| `cri_valor` | FLOAT | `cri_unidad` | El valor medido, si es un número. | — |
| `cri_valor_texto` | TEXT | — | El valor o el motivo, si es un texto (por ejemplo, el nivel de triaje). | — |
| `cri_unidad` | TEXT | — | `%`, `fraction`, `electrodes` o `dB`. | — |
| `cri_bajo` | FLOAT | `cri_unidad` | Fuera de rango por debajo de este valor. | — |
| `cri_alto` | FLOAT | `cri_unidad` | Fuera de rango por encima de este valor. | — |
| `cri_decisivo` | INTEGER | — | 0 o 1: la regla basta, por sí sola, para que el EEG no sea válido. | — |
| `cri_anormal` | INTEGER | — | 0 o 1. | — |
---
## 8. Tabla `eeg_metrica` **(análisis del EEG)**
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
@@ -108,16 +135,21 @@ sus alteraciones no cuentan.
| `met_eeg_id` | TEXT | — | — | → `eeg.eeg_id` |
| `met_codigo` | TEXT | — | Catálogo `MetricaEeg`: `RITMO_POSTERIOR, HUSOS_SUENO_N2, HUSOS_SUENO_N3, PICOS_PAROXISTICOS, GRADIENTE_ANTEROPOSTERIOR`. | — |
| `met_valor` | FLOAT | la de la métrica | Nulo: la métrica no se puede evaluar (por ejemplo, husos sin registro de sueño). | — |
Solo se guarda el valor medido: el puntaje z y el estado salen de los rangos de referencia por grupo de edad.
| `met_z` | FLOAT | puntaje z | Contra la curva de referencia de la métrica a `eeg_edad_meses`; nulo si la edad no está cubierta. | — |
| `met_fuera` | INTEGER | — | -1 debajo del percentil 5, 0 dentro, +1 arriba del percentil 95. | — |
| `met_p5` | FLOAT | la de la métrica | El percentil 5 de la curva a esa edad. | — |
| `met_mediana` | FLOAT | la de la métrica | La mediana de la curva a esa edad. | — |
| `met_p95` | FLOAT | la de la métrica | El percentil 95 de la curva a esa edad. | — |
| `met_modelo` | TEXT | — | La versión registrada de la curva de referencia. | — |
---
## 8. Tabla `eeg_metrica_electrodo` **(análisis del EEG)**
## 9. Tabla `eeg_metrica_electrodo` **(análisis del EEG)**
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `mel_id` | VARCHAR(36), llave primaria | — | — | — |
| `mel_met_id` | TEXT | — | — | → `eeg_metrica.met_id` |
| `mel_electrodo` | TEXT | — | Un electrodo del sistema 10-20 (`Fp1` … `O2`). | — |
| `mel_valor` | FLOAT | puntaje z | — | — |
| `mel_valor` | FLOAT | la de la métrica | — | — |
| `mel_z` | FLOAT | puntaje z | Contra la curva de referencia del electrodo a `eeg_edad_meses`. | — |
+1
View File
@@ -83,6 +83,7 @@ def test_tea_tables_registered():
"eeg",
"eeg_metrica",
"eeg_metrica_electrodo",
"eeg_criterio",
# indicadores_kit CDM, built from staging by the webapi.orquestacion graph.
*INDICADORES_KIT_CDM,
}
+10 -1
View File
@@ -135,7 +135,7 @@ CLINICAL_TERMS: dict[str, dict[str, object]] = {
# Columns worth looking for anywhere in the narrative, not only after a caption.
FREE_TEXT_FIELDS = frozenset(
{"cit_vph_resultado", "cit_celulas_escamosas", "bx_cin_grado", "bx_grado_histologico", "mast_birads", "nm_cie_codigo"}
{"cit_vph_resultado", "cit_celulas_escamosas", "cit_celulas_glandulares", "bx_cin_grado", "bx_grado_histologico", "mast_birads", "nm_cie_codigo"}
)
# Shape of a valid value.
@@ -372,6 +372,15 @@ CLINICAL_TERMS["cit_celulas_escamosas"].update({
"DISPLASIA LEVE": "LIEBG", "DISPLASIA MODERADA": "LIEAG", "DISPLASIA GRAVE": "LIEAG", "DISPLASIA SEVERA": "LIEAG",
"CARCINOMA IN SITU": "CIS", "NILM": "NORMAL",
})
# Glandular cells in cytology: atypical glandular cells (AGC) and adenocarcinoma.
# Adenocarcinoma in situ has no catalog value and is deliberately not listed.
CLINICAL_TERMS["cit_celulas_glandulares"] = {
"CELULAS GLANDULARES ATIPICAS": "AGC", "ATIPIA DE CELULAS GLANDULARES": "AGC",
"ATIPIA EN CELULAS GLANDULARES": "AGC", "AGC": "AGC", "ACG": "AGC",
"ADENOCARCINOMA": "ADENOCARCINOMA", "ADENOCARCINOMA ENDOCERVICAL": "ADENOCARCINOMA",
"ADENOCARCINOMA ENDOMETRIAL": "ADENOCARCINOMA",
}
SEVERITY["cit_celulas_glandulares"] = ("AGC", "ADENOCARCINOMA")
CLINICAL_TERMS["bx_cin_grado"].update({
"NIC1": "LIEBG", "NIC2": "LIEAG", "NIC3": "LIEAG", "CIN1": "LIEBG", "CIN2": "LIEAG", "CIN3": "LIEAG",
"LIEBG": "LIEBG", "LIEAG": "LIEAG", "LIE DE BAJO GRADO": "LIEBG", "LIE DE ALTO GRADO": "LIEAG",
+21
View File
@@ -3,6 +3,7 @@ from datetime import date
from extraction.document import BBox, Line
from extraction.nlp import FieldKind, FieldSpec, RecordExtractor, SegmentLine
from extraction.nlp.text import find_date, find_decimal, find_integer, fold
from extraction.nlp.vocabulary import CLINICAL_TERMS, SEVERITY, labels_for
SEXO = FieldSpec("pac_sexo", FieldKind.CHOICE, labels=("sexo",), choices={"F": "Femenino", "FEMENINO": "Femenino", "M": "Masculino"})
NACIMIENTO = FieldSpec("pac_fecha_nacimiento", FieldKind.DATE, labels=("fecha de nacimiento", "f. nac"))
@@ -23,6 +24,14 @@ CIN = FieldSpec(
scan_free_text=True,
)
OBSERVACIONES = FieldSpec("cit_observaciones", FieldKind.TEXT, labels=("observaciones",), multiline=True)
GLANDULARES = FieldSpec(
"cit_celulas_glandulares",
FieldKind.CHOICE,
labels=labels_for("cit_celulas_glandulares"),
choices=CLINICAL_TERMS["cit_celulas_glandulares"],
scan_free_text=True,
severity=SEVERITY["cit_celulas_glandulares"],
)
def lines(*texts: str, confidence: float = 1.0) -> list[SegmentLine]:
@@ -103,3 +112,15 @@ def test_low_ocr_confidence_lowers_value_confidence():
clean = RecordExtractor([SEXO]).extract(lines("Sexo: F"))["pac_sexo"].confidence
noisy = RecordExtractor([SEXO]).extract(lines("Sexo: F", confidence=0.6))["pac_sexo"].confidence
assert noisy < clean
def test_glandular_atypical_cells_wording_maps_to_agc():
"""Pins down that a cytology line naming atypical glandular cells maps to the catalog value AGC, using the vocabulary's glandular CLINICAL_TERMS as the field's choices. Fails if those terms are missing from the vocabulary, not built into the field, or mapped to another value."""
found = RecordExtractor([GLANDULARES]).extract(lines("Células glandulares: células glandulares atípicas"))
assert found["cit_celulas_glandulares"].value == "AGC"
def test_adenocarcinoma_endocervical_wording_maps_to_adenocarcinoma():
"""Pins down that a cytology line naming endocervical adenocarcinoma maps to the catalog value ADENOCARCINOMA through the vocabulary's glandular CLINICAL_TERMS. Fails if the term is missing from the vocabulary or mapped to AGC or to nothing."""
found = RecordExtractor([GLANDULARES]).extract(lines("Células glandulares: adenocarcinoma endocervical"))
assert found["cit_celulas_glandulares"].value == "ADENOCARCINOMA"
@@ -0,0 +1,37 @@
"""risk index date
Each risk keeps the index date the model scored the patient from (`evaluacion_riesgo.fecha_indice`): the model
defines its decision point, which needn't be the cohort member's. Existing risks take their member's index date in
the batch's build, the one their horizons were counted from; then the column is required.
Revision ID: a1d4e7c20b31
Revises: c3d8f5a20b47
Create Date: 2026-11-20 21:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a1d4e7c20b31'
down_revision = 'c3d8f5a20b47'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
batch_op.add_column(sa.Column('fecha_indice', sa.Date(), nullable=True))
op.execute(
"UPDATE evaluacion_riesgo SET fecha_indice = (SELECT m.fecha_indice FROM cohorte_miembro m "
"JOIN evaluacion_riesgo_lote l ON l.armado_id = m.armado_id "
"WHERE l.lote_id = evaluacion_riesgo.lote_id AND m.pac_id = evaluacion_riesgo.pac_id)"
)
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
batch_op.alter_column('fecha_indice', existing_type=sa.Date(), nullable=False)
def downgrade() -> None:
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
batch_op.drop_column('fecha_indice')
@@ -0,0 +1,32 @@
"""date of death
The patient's date of death, survival's outcome and a competing risk: `paciente.pac_fecha_defuncion`
as it arrives and `persona.fecha_defuncion` in silver. Both nullable: null while she is alive or the
date is unknown.
Revision ID: c3d8f5a20b47
Revises: f89e1f081998
Create Date: 2026-11-20 10:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c3d8f5a20b47'
down_revision = 'f89e1f081998'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column('paciente', sa.Column('pac_fecha_defuncion', sa.Date(), nullable=True))
op.add_column('persona', sa.Column('fecha_defuncion', sa.Date(), nullable=True))
def downgrade() -> None:
# Batch mode: SQLite drops a column by rebuilding its table.
with op.batch_alter_table('persona') as batch:
batch.drop_column('fecha_defuncion')
with op.batch_alter_table('paciente') as batch:
batch.drop_column('pac_fecha_defuncion')
@@ -0,0 +1,31 @@
"""date of death
The patient's date of death, survival's outcome: `paciente.pac_fecha_defuncion` as it arrives and
`persona.fecha_defuncion` in silver. Both nullable: null while she is alive or the date is unknown.
Revision ID: a9c4e2f17d38
Revises: f82b64f43abd
Create Date: 2026-11-18 19:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a9c4e2f17d38'
down_revision = 'f82b64f43abd'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column('paciente', sa.Column('pac_fecha_defuncion', sa.Date(), nullable=True))
op.add_column('persona', sa.Column('fecha_defuncion', sa.Date(), nullable=True))
def downgrade() -> None:
# Batch mode: SQLite drops a column by rebuilding its table.
with op.batch_alter_table('persona') as batch:
batch.drop_column('fecha_defuncion')
with op.batch_alter_table('paciente') as batch:
batch.drop_column('pac_fecha_defuncion')
@@ -0,0 +1,37 @@
"""risk index date
Each risk keeps the index date the model scored the patient from (`evaluacion_riesgo.fecha_indice`): the model
defines its decision point, which needn't be the cohort member's. Existing risks take their member's index date in
the batch's build, the one their horizons were counted from; then the column is required.
Revision ID: b2e5f8d31c42
Revises: a9c4e2f17d38
Create Date: 2026-11-20 21:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b2e5f8d31c42'
down_revision = 'a9c4e2f17d38'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
batch_op.add_column(sa.Column('fecha_indice', sa.Date(), nullable=True))
op.execute(
"UPDATE evaluacion_riesgo SET fecha_indice = (SELECT m.fecha_indice FROM cohorte_miembro m "
"JOIN evaluacion_riesgo_lote l ON l.armado_id = m.armado_id "
"WHERE l.lote_id = evaluacion_riesgo.lote_id AND m.pac_id = evaluacion_riesgo.pac_id)"
)
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
batch_op.alter_column('fecha_indice', existing_type=sa.Date(), nullable=False)
def downgrade() -> None:
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
batch_op.drop_column('fecha_indice')
@@ -14,6 +14,7 @@ from persistance.edges.gold.cohorts import (
CohortMember,
PatientMembership,
PatientRisk,
PendingBatch,
RiskOutsideCohort,
RiskHorizon,
change_state_in,
@@ -34,6 +35,7 @@ __all__ = [
"MeasureReportRepository",
"PatientMembership",
"PatientRisk",
"PendingBatch",
"PublicationRepository",
"ReferenceRepository",
"RiskOutsideCohort",
+49 -8
View File
@@ -114,6 +114,22 @@ class CohortRepository(Repository):
{v.variable: v.valor_codigo if v.valor_codigo is not None else v.valor_numerico
for v in values})
def pending_batches(self) -> list["PendingBatch"]:
"""Batches with no evaluation confirmed or voided yet (ADR-MD-008): created by estimating, waiting for
someone's decision. Newest first."""
lote, e = self.cohortes.EvaluacionRiesgoLote, self.cohortes.EvaluacionRiesgo
with self._session_factory() as sesion:
lotes = sesion.exec(select(lote).order_by(lote.lote_id.desc())).all()
pending = []
for fila in lotes:
latest = _latest_versions(sesion, e, fila.lote_id)
decided = sesion.exec(select(e.evaluacion_id).join(latest, _same_version(e, latest))
.where(e.lote_id == fila.lote_id, e.estado != PRELIMINAR).limit(1)).first()
if decided is None:
pending.append(PendingBatch(fila.lote_id, fila.modelo_nombre, fila.modelo_version,
fila.evaluado_en, fila.n_evaluaciones))
return pending
def current_risk(self, pac_id: int) -> "PatientRisk | None":
"""The patient's risks in the current batch: the highest `lote_id` among the patient's batches where some
evaluation's latest version is `final`. One horizon per `horizonte_anios`, at its latest version, ascending;
@@ -133,7 +149,7 @@ class CohortRepository(Repository):
batch = sesion.get(self.cohortes.EvaluacionRiesgoLote, lote_id)
return PatientRisk(lote_id, batch.modelo_nombre, batch.modelo_version, batch.evaluado_en, FINAL,
[RiskHorizon(r.horizonte_anios, r.probabilidad, r.ic_bajo, r.ic_alto, r.estado)
for r in rows])
for r in rows], rows[0].fecha_indice if rows else None, batch.desenlace)
return None
@@ -159,6 +175,18 @@ class RiskHorizon:
estado: str
@dataclass(frozen=True)
class PendingBatch:
"""A risk batch waiting for someone to confirm or void it; no evaluation has reached `final` or
`entered-in-error` yet."""
lote_id: int
modelo_nombre: str
modelo_version: str
evaluado_en: datetime
n_evaluaciones: int
@dataclass(frozen=True)
class PatientRisk:
"""A patient's risks in the current batch, with the model that produced them."""
@@ -169,6 +197,8 @@ class PatientRisk:
evaluado_en: datetime
estado_lote: str
horizontes: list[RiskHorizon]
fecha_indice: date | None = None # the model's index date for the patient, which the horizons count from
desenlace: str | None = None # the batch's outcome (FHIR `RiskAssessment.prediction.outcome`)
def _latest_versions(sesion: Session, e, lote_id: int):
@@ -256,12 +286,14 @@ def save_batch_in(
armado_id: int,
procedencia: dict,
desenlace: str,
riesgos: list[tuple[int, float, float, float | None, float | None]],
riesgos: list[tuple[int, date, float, float, float | None, float | None]],
*,
cohortes: TablasCohorte,
ahora: datetime | None = None,
) -> tuple[int, bool]:
"""Guarda los riesgos `(pac_id, horizonte_anios, probabilidad, ic_bajo, ic_alto)`. Devuelve (`lote_id`, nuevo).
"""Guarda los riesgos `(pac_id, fecha_indice, horizonte_anios, probabilidad, ic_bajo, ic_alto)`. Devuelve
(`lote_id`, nuevo). `fecha_indice` es el punto de decisión del modelo para esa paciente: una por paciente en el
lote, la misma en todos sus horizontes.
No copia nada de MLflow: guarda sus llaves (`PROVENANCE`). Puntuar lo mismo
otra vez (mismo armado, modelo y riesgos) no duplica: la huella del lote ya está.
@@ -274,8 +306,15 @@ def save_batch_in(
ajenos = sorted({pac for pac, *_ in riesgos} - miembros)
if ajenos:
raise RiskOutsideCohort(f"No son miembros del armado {armado_id}: {ajenos[:10]}.")
fechas: dict[int, set] = {}
for pac, fecha, *_ in riesgos:
if fecha is None:
raise ValueError("Un riesgo sin `fecha_indice`: el modelo debe decir desde cuándo predice.")
fechas.setdefault(pac, set()).add(fecha)
if varias := sorted(pac for pac, f in fechas.items() if len(f) > 1):
raise ValueError(f"Más de una `fecha_indice` por paciente en el lote: {len(varias)} pacientes.")
huella = _json_sha({"armado_id": armado_id, "desenlace": desenlace, **{c: procedencia[c] for c in PROVENANCE},
"riesgos": sorted(riesgos)})
"riesgos": sorted((pac, str(f), h, p, bajo, alto) for pac, f, h, p, bajo, alto in riesgos)})
lote = cohortes.EvaluacionRiesgoLote
previo = sesion.exec(select(lote).where(lote.huella == huella)).first()
if previo is not None:
@@ -287,9 +326,10 @@ def save_batch_in(
sesion.add(fila)
sesion.flush()
sesion.add_all(
cohortes.EvaluacionRiesgo(lote_id=fila.lote_id, pac_id=pac, horizonte_anios=float(h), probabilidad=float(p),
ic_bajo=bajo, ic_alto=alto, version=1, estado=PRELIMINAR, registrado_en=momento)
for pac, h, p, bajo, alto in riesgos
cohortes.EvaluacionRiesgo(lote_id=fila.lote_id, pac_id=pac, fecha_indice=fecha, horizonte_anios=float(h),
probabilidad=float(p), ic_bajo=bajo, ic_alto=alto, version=1, estado=PRELIMINAR,
registrado_en=momento)
for pac, fecha, h, p, bajo, alto in riesgos
)
sesion.commit()
except Exception:
@@ -319,7 +359,8 @@ def change_state_in(
momento = ahora or datetime.now(timezone.utc)
try:
sesion.add_all(
e(lote_id=lote_id, pac_id=v.pac_id, horizonte_anios=v.horizonte_anios, probabilidad=v.probabilidad,
e(lote_id=lote_id, pac_id=v.pac_id, fecha_indice=v.fecha_indice, horizonte_anios=v.horizonte_anios,
probabilidad=v.probabilidad,
ic_bajo=v.ic_bajo, ic_alto=v.ic_alto, version=v.version + 1, estado=estado, motivo=motivo,
registrado_en=momento)
for v in vigentes
+2
View File
@@ -34,6 +34,7 @@ from core.tea.models import (
Ados2,
Eeg,
EegMetrica,
EegCriterio,
EegMetricaElectrodo,
EvaluacionNeuropediatrica,
Mchat,
@@ -74,6 +75,7 @@ evaluacion_neuropediatrica_repository = Repository(get_tea_session, EvaluacionNe
eeg_repository = Repository(get_tea_session, Eeg)
eeg_metrica_repository = Repository(get_tea_session, EegMetrica)
eeg_metrica_electrodo_repository = Repository(get_tea_session, EegMetricaElectrodo)
eeg_criterio_repository = Repository(get_tea_session, EegCriterio)
# indicadores_kit (Core/docs/ADR-004). Se leen con get/list/count; lo que
# se escribe va por métodos de subclases (persistance/edges, por capa).
@@ -0,0 +1,90 @@
"""tea eeg analysis
What the EEG analysis writes from the stored EDF: its verdict, triage level, clean fraction, bad channels, the age it
compared the metrics at and what produced it, on `eeg`; one row per quality check in `eeg_criterio`; each metric's
z, -1/0/+1 against the age baseline and the baseline's p5/median/p95 there, on `eeg_metrica`; each electrode's z, on
`eeg_metrica_electrodo`. Only additions: nothing existing changes.
Revision ID: 16bf0b0ee3e4
Revises: b9e4d2c71a05
Create Date: 2026-11-19 13:14:08.006494
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '16bf0b0ee3e4'
down_revision = 'b9e4d2c71a05'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table('eeg_criterio',
sa.Column('cri_id', sa.String(length=36), nullable=False),
sa.Column('cri_eeg_id', sa.String(length=36), nullable=True),
sa.Column('cri_codigo', sa.Text(), nullable=True),
sa.Column('cri_electrodo', sa.Text(), nullable=True),
sa.Column('cri_valor', sa.Float(), nullable=True),
sa.Column('cri_valor_texto', sa.Text(), nullable=True),
sa.Column('cri_unidad', sa.Text(), nullable=True),
sa.Column('cri_bajo', sa.Float(), nullable=True),
sa.Column('cri_alto', sa.Float(), nullable=True),
sa.Column('cri_decisivo', sa.Integer(), nullable=True),
sa.Column('cri_anormal', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('cri_id')
)
with op.batch_alter_table('eeg_criterio', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_eeg_criterio_cri_eeg_id'), ['cri_eeg_id'], unique=False)
with op.batch_alter_table('eeg', schema=None) as batch_op:
batch_op.add_column(sa.Column('eeg_valido', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('eeg_nivel', sa.Text(), nullable=True))
batch_op.add_column(sa.Column('eeg_fraccion_limpia', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('eeg_canales_malos', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('eeg_edad_meses', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('eeg_plan_hash', sa.String(length=16), nullable=True))
batch_op.add_column(sa.Column('eeg_versiones', sa.Text(), nullable=True))
batch_op.add_column(sa.Column('eeg_analizado_en', sa.DateTime(), nullable=True))
batch_op.add_column(sa.Column('eeg_error', sa.Text(), nullable=True))
with op.batch_alter_table('eeg_metrica', schema=None) as batch_op:
batch_op.add_column(sa.Column('met_z', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('met_fuera', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('met_p5', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('met_mediana', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('met_p95', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('met_modelo', sa.Text(), nullable=True))
with op.batch_alter_table('eeg_metrica_electrodo', schema=None) as batch_op:
batch_op.add_column(sa.Column('mel_z', sa.Float(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('eeg_metrica_electrodo', schema=None) as batch_op:
batch_op.drop_column('mel_z')
with op.batch_alter_table('eeg_metrica', schema=None) as batch_op:
batch_op.drop_column('met_modelo')
batch_op.drop_column('met_p95')
batch_op.drop_column('met_mediana')
batch_op.drop_column('met_p5')
batch_op.drop_column('met_fuera')
batch_op.drop_column('met_z')
with op.batch_alter_table('eeg', schema=None) as batch_op:
batch_op.drop_column('eeg_error')
batch_op.drop_column('eeg_analizado_en')
batch_op.drop_column('eeg_versiones')
batch_op.drop_column('eeg_plan_hash')
batch_op.drop_column('eeg_edad_meses')
batch_op.drop_column('eeg_canales_malos')
batch_op.drop_column('eeg_fraccion_limpia')
batch_op.drop_column('eeg_nivel')
batch_op.drop_column('eeg_valido')
with op.batch_alter_table('eeg_criterio', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_eeg_criterio_cri_eeg_id'))
op.drop_table('eeg_criterio')
@@ -0,0 +1,37 @@
"""risk index date
Each risk keeps the index date the model scored the patient from (`evaluacion_riesgo.fecha_indice`): the model
defines its decision point, which needn't be the cohort member's. Existing risks take their member's index date in
the batch's build, the one their horizons were counted from; then the column is required.
Revision ID: c3f6a9e42d53
Revises: c4306f438b3a
Create Date: 2026-11-20 21:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c3f6a9e42d53'
down_revision = 'c4306f438b3a'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
batch_op.add_column(sa.Column('fecha_indice', sa.Date(), nullable=True))
op.execute(
"UPDATE evaluacion_riesgo SET fecha_indice = (SELECT m.fecha_indice FROM cohorte_miembro m "
"JOIN evaluacion_riesgo_lote l ON l.armado_id = m.armado_id "
"WHERE l.lote_id = evaluacion_riesgo.lote_id AND m.pac_id = evaluacion_riesgo.pac_id)"
)
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
batch_op.alter_column('fecha_indice', existing_type=sa.Date(), nullable=False)
def downgrade() -> None:
with op.batch_alter_table('evaluacion_riesgo', schema=None) as batch_op:
batch_op.drop_column('fecha_indice')
@@ -0,0 +1,32 @@
"""tea eeg criteria columns dropped
The EEG analysis writes each quality check as a row of `eeg_criterio`, so the four fixed criterion columns of `eeg`
go. Downgrade brings them back empty: the counts they held aren't kept anywhere else.
Revision ID: c4306f438b3a
Revises: 16bf0b0ee3e4
Create Date: 2026-11-19 14:09:04.196709
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c4306f438b3a'
down_revision = '16bf0b0ee3e4'
branch_labels = None
depends_on = None
COLUMNS = ('eeg_canales_amplitud', 'eeg_canales_alta_frecuencia', 'eeg_canales_correlacion', 'eeg_canales_sin_senal')
def upgrade() -> None:
with op.batch_alter_table('eeg', schema=None) as batch_op:
for column in COLUMNS:
batch_op.drop_column(column)
def downgrade() -> None:
with op.batch_alter_table('eeg', schema=None) as batch_op:
for column in COLUMNS:
batch_op.add_column(sa.Column(column, sa.Integer(), nullable=True))
+41 -6
View File
@@ -15,7 +15,7 @@ from core.cacu.indicadores.models import (CohorteArmado, CohorteExclusion, Cohor
from core.indicadores.cohortes import TablasCohorte
from sqlmodel import Session, create_engine
from persistance.edges.gold import CohortRepository, RiskHorizon
from persistance.edges.gold import CohortRepository, PendingBatch, RiskHorizon
URL = "cacu/cohorte_vigilancia"
TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote,
@@ -46,6 +46,9 @@ def repository():
return CohortRepository(lambda: Session(engine), TABLES)
D = date(2026, 3, 15) # the model's index date for patient 10, not her member's (2025-01-02)
def _batch(repository, version, risks, armado_id=2):
return repository.save_batch(armado_id, {**PROVENANCE, "modelo_version": version}, "cin2_12m", risks)[0]
@@ -63,7 +66,7 @@ def test_membership_is_in_the_latest_build_with_its_variables(repository):
def test_an_unconfirmed_batch_is_not_current(repository):
"""Pins down: a batch with only preliminary evaluations isn't shown. Fails if a risk nobody confirmed reaches the
patient's record."""
_batch(repository, "1", [(10, 1.0, 0.2, None, None)])
_batch(repository, "1", [(10, D, 1.0, 0.2, None, None)])
assert repository.current_risk(10) is None
@@ -72,21 +75,53 @@ def test_the_current_batch_is_the_newest_confirmed_one_with_its_horizons(reposit
"""Pins down: among confirmed batches the newest wins, even when a newer unconfirmed one exists; its horizons come
in ascending order with their latest state. Fails if the newest batch is taken regardless of its state, or the
horizons come unordered."""
first = _batch(repository, "1", [(10, 3.0, 0.3, None, None), (10, 1.0, 0.1, 0.05, 0.2)])
first = _batch(repository, "1", [(10, D, 3.0, 0.3, None, None), (10, D, 1.0, 0.1, 0.05, 0.2)])
repository.change_state(first, "final", "revisado")
_batch(repository, "2", [(10, 1.0, 0.9, None, None)])
_batch(repository, "2", [(10, D, 1.0, 0.9, None, None)])
risk = repository.current_risk(10)
assert (risk.lote_id, risk.modelo_version, risk.estado_lote) == (first, "1", "final")
assert (risk.lote_id, risk.modelo_version, risk.estado_lote, risk.fecha_indice) == (first, "1", "final", D)
assert risk.horizontes == [RiskHorizon(1.0, 0.1, 0.05, 0.2, "final"), RiskHorizon(3.0, 0.3, None, None, "final")]
def test_an_annulled_batch_is_no_longer_current(repository):
"""Pins down: once a confirmed batch is marked `entered-in-error`, its latest versions aren't final and it stops
being current. Fails if any version ever confirmed keeps a withdrawn risk on the record."""
first = _batch(repository, "1", [(10, 1.0, 0.1, None, None)])
first = _batch(repository, "1", [(10, D, 1.0, 0.1, None, None)])
repository.change_state(first, "final", "revisado")
repository.change_state(first, "entered-in-error", "modelo equivocado")
assert repository.current_risk(10) is None
def test_pending_batches_are_the_ones_with_no_decision_yet(repository):
"""Pins down: a batch stays pending until it's confirmed or voided, newest first, and dropping off the list is
permanent either way. Fails if a confirmed or a voided batch is still listed, or the order is reversed."""
first = _batch(repository, "1", [(10, D, 1.0, 0.1, None, None)])
second = _batch(repository, "2", [(10, D, 1.0, 0.2, None, None)])
third = _batch(repository, "3", [(10, D, 1.0, 0.3, None, None)])
repository.change_state(second, "final", "revisado")
pending = repository.pending_batches()
assert [(b.lote_id, b.modelo_version, b.n_evaluaciones) for b in pending] == [(third, "3", 1), (first, "1", 1)]
assert all(isinstance(b, PendingBatch) and b.modelo_nombre == "cacu-cin2_logistic" for b in pending)
repository.change_state(third, "entered-in-error", "modelo equivocado")
assert [b.lote_id for b in repository.pending_batches()] == [first]
def test_a_risk_needs_one_index_date_per_patient(repository):
"""Pins down: each risk carries the model's index date for its patient, kept through a change of state, and a
batch with no date or two dates for one patient is refused. Fails if the horizons could count from different dates
or from none."""
with pytest.raises(ValueError, match="sin `fecha_indice`"):
_batch(repository, "1", [(10, None, 1.0, 0.1, None, None)])
with pytest.raises(ValueError, match="Más de una"):
_batch(repository, "1", [(10, D, 1.0, 0.1, None, None), (10, date(2026, 1, 1), 3.0, 0.3, None, None)])
lote = _batch(repository, "1", [(10, D, 1.0, 0.1, None, None)])
repository.change_state(lote, "final", "revisado")
assert repository.current_risk(10).fecha_indice == D
+60 -37
View File
@@ -53,32 +53,46 @@ vars:
"C508", "C509"]
cie_antecedente: ["D05", "D050", "D051", "D057", "D059", "C50", "C500", "C501", "C502", "C503", "C504", "C505",
"C506", "C508", "C509"]
# Each patient's clinical scenario (models/cama/silver/cama_procedimientos_inferidos.sql), one of two: a patient
# is in post-treatment from her first evidence of a kind `postratamiento_evidencias` names, and under observation
# ("en observación") otherwise. The timeline keeps that evidence as an `escenario_postratamiento` fact with its
# kind in `valor_codigo`; being under observation has no fact.
# egreso a note of one of `tipos_nota_egreso` with one of `cie_tumor_maligno`, or on or after her diagnosis
# nota a note with one of `cie_tumor_maligno` by one of `tratamiento_especialidades`, after her diagnosis
# Her diagnosis is her first evidence of a kind `diagnostico_evidencias` names. cie: a note with one of
# `cie_tumor_maligno` (an in situ carcinoma isn't one), whoever wrote it; biopsia: a report of one of
# `grados_malignos`.
escenarios:
postratamiento_evidencias: ["egreso"]
tipos_nota_egreso: ["EGRESO"]
tratamiento_especialidades: ["CIRUGIA_ONCOLOGICA", "ONCOLOGIA_MEDICA"]
diagnostico_evidencias: ["cie"]
cie_tumor_maligno: ["C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509"]
grados_malignos: ["CARCINOMA_INVASOR"]
especialidades_diagnostico: ["CIRUGIA_ONCOLOGICA"]
horizonte_toma_diagnostico_dias: 180
birads_gravedad: ["B1", "B2", "B3", "B0", "B4", "B4A", "B4B", "B4C", "B5", "B6"]
# Biopsy grades from least to most severe (models/cama/gold/eventos/cama_resultado_biopsia.sql): the keys of
# cama.catalogos.biopsia.
biopsia_gravedad: ["BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"]
# The grades that count as cancer in the detection rate (models/cama/gold/eventos/cama_deteccion_biopsia.sql): the
# values of the parameter cama.biopsia_cancer (a test keeps them equal).
grados_cancer: ["CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"]
# The analysis' stratifiers (models/cama/silver/cama_estratificadores.sql), from the catalog's provisional results
# read from reports; placeholders until the domain expert validates them. `estadios`: each clinical stage's
# group; `etapa_temprana`: the groups counted as early, the rest of the known ones advanced. The surrogate
# molecular subtype: HER2 3+ is HER2-positive; HER2 0 or 1+ with both receptors negative, triple negative; with a
# positive receptor, luminal A when Ki-67 is under `ki67_corte` % and progesterone positive with at least
# `rp_corte` % (or no percentage), luminal B when Ki-67 is at least `ki67_corte` % or progesterone falls short;
# without Ki-67, none. `tamano_t`: T by the lesion's largest diameter in mm, each up to its bound.
# group; `etapa_temprana`: the groups counted as early, the rest of the known ones advanced. `tamano_t`: T by the
# lesion's largest diameter in mm, each up to its bound.
# The biopsy grades that are an invasive cancer (models/cama/gold/eventos/cama_cancer_invasor.sql).
grados_invasor: ["CARCINOMA_INVASOR"]
estratos:
estadios: {E0: "0", EI: "i", EIIA: "ii", EIIB: "ii", EIIIA: "iii", EIIIB: "iii", EIIIC: "iii", EIV: "iv"}
etapa_temprana: ["0", "i", "ii"]
her2_positivo: ["H3"]
her2_negativo: ["H0", "H1"]
ki67_corte: 20
rp_corte: 20
tamano_t: [{t: "t1", hasta_mm: 20}, {t: "t2", hasta_mm: 50}, {t: "t3", hasta_mm: null}]
# TEA's rules (models/tea). The cohort: children whose first M-CHAT was at `edad_min_meses` to `edad_max_meses`
# completed months (days / `dias_por_mes`, rounded to one decimal, then truncated); `ventanas`, the age groups of
# that age. A confirmation is a neuropediatrics note with one of `cie_tea` (without the dot, compared exactly).
# An EEG is bad when any quality criterion passes its threshold (`calidad`); a metric is altered when its z-score
# against the reference of the child's age group at the EEG is at least `alteracion_z` away from 0.
# The references, thresholds and `alteracion_z` are placeholders until the domain expert validates them.
# Whether an EEG is valid, and whether a metric is altered (outside its age baseline's p5-p95), is the EEG
# analysis's: the baselines are the trained models in production, which the domain expert validates.
tea:
edad_min_meses: 16
edad_max_meses: 36
@@ -88,37 +102,46 @@ vars:
- {clave: "24_29", desde: 24, hasta: 29}
- {clave: "30_36", desde: 30, hasta: 36}
cie_tea: ["F840"]
alteracion_z: 2
calidad:
canales_amplitud: 2
canales_alta_frecuencia: 2
canales_correlacion: 2
canales_sin_senal: 2
ruido_linea_db: 8
# Reference range of each metric by age group at the EEG: (metric, group, min, max). The mean is the middle of
# the range and the standard deviation a quarter of its width.
referencias:
- ["ritmo_posterior", "16_23", 4.5, 7.0]
- ["ritmo_posterior", "24_29", 5.0, 7.5]
- ["ritmo_posterior", "30_36", 5.5, 8.5]
- ["husos_sueno_n2", "16_23", 2.5, 6.5]
- ["husos_sueno_n2", "24_29", 2.25, 6.25]
- ["husos_sueno_n2", "30_36", 2.0, 6.0]
- ["husos_sueno_n3", "16_23", 0.75, 2.75]
- ["husos_sueno_n3", "24_29", 0.5, 2.5]
- ["husos_sueno_n3", "30_36", 0.5, 2.5]
- ["picos_paroxisticos", "16_23", 0.0, 1.0]
- ["picos_paroxisticos", "24_29", 0.0, 1.0]
- ["picos_paroxisticos", "30_36", 0.0, 1.0]
- ["gradiente_anteroposterior", "16_23", 2.0, 3.5]
- ["gradiente_anteroposterior", "24_29", 1.75, 3.25]
- ["gradiente_anteroposterior", "30_36", 1.5, 3.0]
# CaMa's survival cohort (models/cama/cohorts/survival): the surgeries that are its procedure of interest
# (ESCISIONAL includes a lumpectomy). Provisional, to be decided with the domain expert.
survival_cohort:
recruitment_start: "2018-01-01"
recruitment_end: "2027-01-01"
cutoff: "2026-12-31"
surgeries: ["ESCISIONAL", "SEGMENTECTOMIA", "MASTECTOMIA_TOTAL", "MASTECTOMIA_RADICAL_MODIFICADA"]
# The surveillance cohort's rules (models/cacu/cohorts/surveillance).
# CaCu's recruitment window and cut-off, once: every CaCu cohort takes them (YAML merge key), so the post-colposcopy
# and total cohorts (and the scenarios indexed in their pipelines) recruit as the surveillance cohort does.
cacu_window: &cacu_window
recruitment_start: "2024-01-01"
recruitment_end: "2027-01-01"
cutoff: "2026-12-31"
surveillance_cohort:
<<: *cacu_window
event_grades: ["LIEAG", "CIS", "CARCINOMA"]
# The post-colposcopy cohorts (models/cacu/cohorts/post_colposcopy, one per visit k; KPNC's post-colposcopy
# tables, Cheung et al. 2020): indexed at the first colposcopy's result (k = 0) or at the k-th surveillance visit
# after it, stratified by the result that referred the patient (within `referral_lookback_days` before the
# colposcopy; provisional). `hysterectomy_cie`: provisional, ICD-10 Z90.7 is the absence of any genital organ.
post_colposcopy_cohort:
<<: *cacu_window
event_grades: ["LIEAG", "CIS", "CARCINOMA"]
referral_lookback_days: 365
hysterectomy_cie: ["Z907"]
# The total cohort (models/cacu/cohorts/total): every patient with an event up to the cut-off, with no rules, for
# models that apply their own; its recruitment window is carried in its parameters for their index.
total_cohort:
<<: *cacu_window
# The post-treatment cohort (models/cacu/cohorts/post_treatment; KPNC's post-treatment tables): the first cytology
# more than `index_after_days` after the first treatment, stratified by the biopsy before it (within
# `pretreatment_lookback_days`).
post_treatment_cohort:
recruitment_start: "2024-01-01"
recruitment_end: "2027-01-01"
cutoff: "2026-12-31"
event_grades: ["LIEAG", "CIS", "CARCINOMA"]
index_after_days: 90
pretreatment_lookback_days: 365
# models/<project>/silver: what dbt derives from silver's procedimiento and observacion_clinica, compiled as
# CTEs inside the models that use them (no objects in the database), except the timeline, a view.
# models/<project>/gold/<family>: one view per indicator, a folder per family as in the kit.
@@ -0,0 +1,90 @@
{#
The post-colposcopy cohorts, one per visit k (KPNC's post-colposcopy tables; Cheung et al. 2020,
doi:10.1097/LGT.0000000000000528): k = 0 is the colposcopy's result (below CIN2), k ≥ 1 the k-th surveillance visit
after it. Every cohort has the same rules; only the index changes. A new visit is a folder `visit_<k>` whose models
call these macros with its k (see models/cacu/cohorts/post_colposcopy/README.md).
Parameters: the `post_colposcopy_cohort` var.
#}
{# The index of visit k: the colposcopy's result (k = 0) or visit k, if it falls in the recruitment window. #}
{% macro cacu_post_colposcopy_index(k) -%}
{%- set p = var('post_colposcopy_cohort') -%}
{%- if k == 0 %}
select pac_id, fecha_resultado as fecha_indice, fuente_tabla as indice_fuente_tabla, fuente_id as indice_fuente_id,
fecha_colposcopia, fecha_resultado, ordenes_sin_resultado
from {{ ref('cacu_post_colposcopy_episode') }}
where fecha_resultado >= '{{ p.recruitment_start }}' and fecha_resultado < '{{ p.recruitment_end }}'
{%- else %}
select pac_id, fecha as fecha_indice, fuente_tabla as indice_fuente_tabla, fuente_id as indice_fuente_id,
fecha_colposcopia, fecha_resultado, ordenes_sin_resultado
from {{ ref('cacu_post_colposcopy_visits') }}
where numero = {{ k }} and fecha >= '{{ p.recruitment_start }}' and fecha < '{{ p.recruitment_end }}'
{%- endif %}
{%- endmacro %}
{# Every patient of the domain: where the cohort's attrition starts. #}
{% macro cacu_post_colposcopy_population() -%}
select pac_id from {{ source('silver', 'persona') }}
{%- endmacro %}
{#
One exclusion rule over the cohort's index model `index` (a model name). Each reads only the index and the data.
- biopsia_sin_resultado a biopsy ordered at the colposcopy has no report: its result is unknown
- cin2_hasta_el_indice a biopsy with the outcome up to the index (the colposcopy found it, or it came before)
- antecedente_cacu a note with a cervical cancer ICD-10 up to the index (`antecedente`)
- histerectomia a note with an ICD-10 of `hysterectomy_cie` up to the index
- tratamiento_previo treated up to the index: she belongs to the post-treatment cohort
- sin_referencia no cytology or HPV result in the `referral_lookback_days` up to the colposcopy
- sin_cotest the index sample lacks an HPV result or a cytology result (squamous or glandular)
#}
{% macro cacu_post_colposcopy_exclusion(rule, index) -%}
{%- set p = var('post_colposcopy_cohort') -%}
{%- if rule == 'biopsia_sin_resultado' %}
select pac_id from {{ ref(index) }} where ordenes_sin_resultado > 0
{%- elif rule in ('cin2_hasta_el_indice', 'antecedente_cacu', 'histerectomia', 'tratamiento_previo') %}
select distinct c.pac_id
from {{ ref(index) }} as c
join {{ ref('cacu_linea_de_tiempo') }} as e on e.pac_id = c.pac_id
where e.fecha <= c.fecha_indice
{%- if rule == 'cin2_hasta_el_indice' %}
and e.tipo = 'biopsia' and e.valor_codigo in ('{{ p.event_grades | join("', '") }}')
{%- elif rule == 'antecedente_cacu' %}
and e.tipo = 'antecedente'
{%- elif rule == 'histerectomia' %}
and e.tipo = 'nota_medica' and e.valor_codigo in ('{{ p.hysterectomy_cie | join("', '") }}')
{%- else %}
and e.tipo = 'tratamiento'
{%- endif %}
{%- elif rule == 'sin_referencia' %}
select c.pac_id
from {{ ref(index) }} as c
join {{ source('silver', 'dim_fecha') }} as dc on dc.fecha = c.fecha_colposcopia
where not exists (
select 1
from {{ ref('cacu_linea_de_tiempo') }} as e
join {{ source('silver', 'dim_fecha') }} as de on de.fecha = e.fecha
where e.pac_id = c.pac_id
and e.tipo in ('bethesda', 'glandular', 'vph')
and e.valor_codigo is not null
and de.dia_num <= dc.dia_num
and dc.dia_num - de.dia_num <= {{ p.referral_lookback_days }}
)
{%- elif rule == 'sin_cotest' %}
select c.pac_id
from {{ ref(index) }} as c
where not exists (
select 1 from {{ ref('cacu_linea_de_tiempo') }} as e
where e.pac_id = c.pac_id and e.fuente_tabla = c.indice_fuente_tabla and e.fuente_id = c.indice_fuente_id
and e.tipo = 'vph' and e.valor_codigo is not null and e.fecha <= '{{ p.cutoff }}'
)
or not exists (
select 1 from {{ ref('cacu_linea_de_tiempo') }} as e
where e.pac_id = c.pac_id and e.fuente_tabla = c.indice_fuente_tabla and e.fuente_id = c.indice_fuente_id
and e.tipo in ('bethesda', 'glandular') and e.valor_codigo is not null and e.fecha <= '{{ p.cutoff }}'
)
{%- else %}
{{ exceptions.raise_compiler_error("unknown post-colposcopy rule: " ~ rule) }}
{%- endif %}
{%- endmacro %}
+14 -3
View File
@@ -31,9 +31,20 @@
end
{%- endmacro %}
{# A bounded number of the EEG's quality: within its threshold of `tea.calidad`. #}
{% macro tea_criterio_bueno(columna, umbral) -%}
({{ columna }} is not null and {{ columna }} <= {{ var('tea')['calidad'][umbral] }})
{# The EEG's metrics and quality checks as the catalog names them: `eeg.<metric>`, `eeg.calidad_<check>`. The checks
are the EEG analysis's: study-wide ones on the recording, channel ones on a `parte` per bad channel. #}
{% macro tea_metricas() -%}
{{ return(['ritmo_posterior', 'husos_sueno_n2', 'husos_sueno_n3', 'picos_paroxisticos', 'gradiente_anteroposterior']) }}
{%- endmacro %}
{% macro tea_criterios_estudio() -%}
{{ return(['clean_windows', 'internal_coverage', 'bad_scalp_triage', 'usable_scalp', 'triage_level', 'line_noise',
'file']) }}
{%- endmacro %}
{% macro tea_criterios_canal() -%}
{{ return(['dead_channel', 'frozen', 'saturated', 'inf_values', 'own_gaps', 'bridge', 'amplitude', 'aux_amplitude',
'does_not_correlate', 'intermittent_contact', 'intermittent_bursts']) }}
{%- endmacro %}
{# The later of two values when both are known, else null: a step reached after the previous one is dated by the
@@ -0,0 +1,238 @@
version: 2
# The post-colposcopy cohorts (KPNC's post-colposcopy tables; Cheung et al. 2020, doi:10.1097/LGT.0000000000000528):
# one per visit k in `visit_<k>/`, read as the surveillance cohort's are (`models cohorts build` chains the
# exclusions in `order`; each reads only the index date and the data). The two models here are shared by all of them
# and belong to no cohort. Rules: macros/cacu_post_colposcopy.sql. Parameters: the `post_colposcopy_cohort` var.
models:
- name: cacu_post_colposcopy_episode
description: >
The patient's first colposcopy and when its result is known (the last report of the biopsies ordered that day,
or the colposcopy's date with none ordered: provisionally taken as below CIN2), and how many of those orders
have no report.
config: {materialized: ephemeral}
- name: cacu_post_colposcopy_visits
description: >
The surveillance visits (cytology samples) after the first colposcopy's result is known and before any later
colposcopy, numbered from 1.
config: {materialized: ephemeral}
unit_tests:
- name: the_colposcopy_result_is_the_last_report_of_its_biopsies
description: >
Pins down: patient 1's result date is the later of the two reports of the biopsies ordered on her first
colposcopy's day; the biopsy of her second colposcopy doesn't count. Patient 2 had no biopsy ordered, so her
result date is the colposcopy's (provisionally below CIN2). Patient 3's order has no report, so it is counted
as unknown. Fails if the episode takes a later colposcopy, a biopsy of another day, or stops counting the
unreported orders.
model: cacu_post_colposcopy_episode
overrides:
vars:
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
given:
- input: ref('cacu_linea_de_tiempo')
format: sql
rows: |
select 1 as pac_id, '2025-01-10' as fecha, 'colposcopia' as tipo, null as valor_codigo, 'n' as fuente_tabla, 'c1' as fuente_id
union all select 1, '2025-01-10', 'orden_biopsia', null, 'b', 'o1'
union all select 1, '2025-01-10', 'orden_biopsia', null, 'b', 'o2'
union all select 1, '2025-01-20', 'biopsia', 'LIEBG', 'b', 'o1'
union all select 1, '2025-01-31', 'biopsia', 'NEGATIVO', 'b', 'o2'
union all select 1, '2025-06-01', 'colposcopia', null, 'n', 'c2'
union all select 1, '2025-06-01', 'orden_biopsia', null, 'b', 'o3'
union all select 1, '2025-06-20', 'biopsia', 'LIEBG', 'b', 'o3'
union all select 2, '2025-03-01', 'colposcopia', null, 'n', 'c3'
union all select 3, '2025-04-01', 'colposcopia', null, 'n', 'c4'
union all select 3, '2025-04-01', 'orden_biopsia', null, 'b', 'o4'
expect:
format: sql
rows: |
select 1 as pac_id, '2025-01-10' as fecha_colposcopia, 'n' as fuente_tabla, 'c1' as fuente_id,
'2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado
union all select 2, '2025-03-01', 'n', 'c3', '2025-03-01', 0
union all select 3, '2025-04-01', 'n', 'c4', '2025-04-01', 1
- name: visits_follow_the_result_and_stop_at_the_next_colposcopy
description: >
Pins down: patient 1's sample on the colposcopy's day and the one before her result date aren't visits; the
two after it are visits 1 and 2; the one after her second colposcopy is not a visit. Fails if visits start
before the result is known or continue after a re-referral to colposcopy.
model: cacu_post_colposcopy_visits
overrides:
vars:
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
given:
- input: ref('cacu_linea_de_tiempo')
format: sql
rows: |
select 1 as pac_id, '2025-01-10' as fecha, 'colposcopia' as tipo, 'n' as fuente_tabla, 'c1' as fuente_id
union all select 1, '2025-01-10', 'citologia', 'm', 'a'
union all select 1, '2025-01-20', 'citologia', 'm', 'b'
union all select 1, '2025-07-01', 'citologia', 'm', 'c'
union all select 1, '2026-01-15', 'citologia', 'm', 'd'
union all select 1, '2026-03-01', 'colposcopia', 'n', 'c2'
union all select 1, '2026-09-01', 'citologia', 'm', 'e'
- input: ref('cacu_post_colposcopy_episode')
format: sql
rows: |
select 1 as pac_id, '2025-01-10' as fecha_colposcopia, 'n' as fuente_tabla, 'c1' as fuente_id,
'2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado
expect:
format: sql
rows: |
select 1 as pac_id, '2025-07-01' as fecha, 'm' as fuente_tabla, 'c' as fuente_id, '2025-01-10' as fecha_colposcopia,
'2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado, 1 as numero
union all select 1, '2026-01-15', 'm', 'd', '2025-01-10', '2025-01-31', 0, 2
- name: visit_1_index_is_the_first_visit_in_the_window
description: >
Pins down: patient 1's index is her visit 1; patient 2's visit 1 falls after the recruitment window, so she has
no index even though her visit 2 would. Fails if the cohort of visit 1 takes another visit or ignores the window.
model: cacu_post_colposcopy_v1_index_date
overrides:
vars:
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
given:
- input: ref('cacu_post_colposcopy_visits')
format: sql
rows: |
select 1 as pac_id, '2025-07-01' as fecha, 'm' as fuente_tabla, 'c' as fuente_id, '2025-01-10' as fecha_colposcopia,
'2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado, 1 as numero
union all select 1, '2025-12-01', 'm', 'd', '2025-01-10', '2025-01-31', 0, 2
union all select 2, '2026-02-01', 'm', 'f', '2025-06-01', '2025-06-01', 0, 1
expect:
format: sql
rows: |
select 1 as pac_id, '2025-07-01' as fecha_indice, 'm' as indice_fuente_tabla, 'c' as indice_fuente_id,
'2025-01-10' as fecha_colposcopia, '2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado
- name: visit_0_index_is_the_colposcopy_result
description: >
Pins down: the cohort of visit 0 is indexed at the date the colposcopy's result is known, in the window.
Fails if it takes the colposcopy's date when a biopsy was reported later.
model: cacu_post_colposcopy_v0_index_date
overrides:
vars:
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
given:
- input: ref('cacu_post_colposcopy_episode')
format: sql
rows: |
select 1 as pac_id, '2025-01-10' as fecha_colposcopia, 'n' as fuente_tabla, 'c1' as fuente_id,
'2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado
union all select 2, '2024-12-20', 'n', 'c2', '2024-12-30', 0
expect:
format: sql
rows: |
select 1 as pac_id, '2025-01-31' as fecha_indice, 'n' as indice_fuente_tabla, 'c1' as indice_fuente_id,
'2025-01-10' as fecha_colposcopia, '2025-01-31' as fecha_resultado, 0 as ordenes_sin_resultado
- name: sin_cotest_needs_hpv_and_cytology_of_the_index_sample
description: >
Pins down: patient 1's index sample has an HPV and a Bethesda result, so she stays; patient 2's has only HPV and
patient 3's only cytology, so both are flagged; patient 4's HPV belongs to another sample, so she is flagged.
Fails if a result of another sample, or either result alone, counts as a cotest.
model: cacu_post_colposcopy_v1_excl_sin_cotest
overrides:
vars:
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
given:
- input: ref('cacu_post_colposcopy_v1_index_date')
format: sql
rows: |
select 1 as pac_id, '2025-07-01' as fecha_indice, 'm' as indice_fuente_tabla, 'a' as indice_fuente_id
union all select 2, '2025-07-01', 'm', 'b'
union all select 3, '2025-07-01', 'm', 'c'
union all select 4, '2025-07-01', 'm', 'd'
- input: ref('cacu_linea_de_tiempo')
format: sql
rows: |
select 1 as pac_id, '2025-07-10' as fecha, 'vph' as tipo, 'NEGATIVO' as valor_codigo, 'm' as fuente_tabla, 'a' as fuente_id
union all select 1, '2025-07-12', 'bethesda', 'NORMAL', 'm', 'a'
union all select 2, '2025-07-10', 'vph', 'POSITIVO', 'm', 'b'
union all select 3, '2025-07-12', 'bethesda', 'ASC-US', 'm', 'c'
union all select 4, '2025-07-12', 'bethesda', 'NORMAL', 'm', 'd'
union all select 4, '2025-03-10', 'vph', 'POSITIVO', 'm', 'z'
expect:
format: sql
rows: |
select 2 as pac_id union all select 3 union all select 4
- name: cin2_counts_up_to_the_index_date
description: >
Pins down: a CIN2+ biopsy reported on the index date (visit 0: the colposcopy found it) excludes patient 1;
patient 2's LIEAG comes after her index, so she stays. Fails if `cin2_hasta_el_indice` stops including the
index date or reads biopsies after it.
model: cacu_post_colposcopy_v0_excl_cin2_hasta_el_indice
overrides:
vars:
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
given:
- input: ref('cacu_post_colposcopy_v0_index_date')
format: sql
rows: |
select 1 as pac_id, '2025-01-31' as fecha_indice union all select 2, '2025-01-31'
- input: ref('cacu_linea_de_tiempo')
format: sql
rows: |
select 1 as pac_id, '2025-01-31' as fecha, 'biopsia' as tipo, 'LIEAG' as valor_codigo
union all select 2, '2025-08-01', 'biopsia', 'LIEAG'
expect:
format: sql
rows: |
select 1 as pac_id
- name: histerectomia_reads_the_configured_icd10
description: >
Pins down: patient 1's note with Z907 before her index excludes her; patient 2's note has another code and
patient 3's Z907 comes after her index, so both stay. Fails if the rule ignores `hysterectomy_cie` or the date.
model: cacu_post_colposcopy_v1_excl_histerectomia
overrides:
vars:
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
given:
- input: ref('cacu_post_colposcopy_v1_index_date')
format: sql
rows: |
select 1 as pac_id, '2025-07-01' as fecha_indice union all select 2, '2025-07-01' union all select 3, '2025-07-01'
- input: ref('cacu_linea_de_tiempo')
format: sql
rows: |
select 1 as pac_id, '2024-05-01' as fecha, 'nota_medica' as tipo, 'Z907' as valor_codigo
union all select 2, '2024-05-01', 'nota_medica', 'N871'
union all select 3, '2025-09-01', 'nota_medica', 'Z907'
expect:
format: sql
rows: |
select 1 as pac_id
- name: sin_referencia_looks_back_from_the_colposcopy
description: >
Pins down: patient 1's HPV result 100 days before her colposcopy is her referral, so she stays. Patient 2's
only result is 400 days before (past the lookback) and patient 3's is after the colposcopy, so both are
flagged. Fails if the lookback, its direction or the result types change.
model: cacu_post_colposcopy_v1_excl_sin_referencia
overrides:
vars:
post_colposcopy_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], referral_lookback_days: 365, hysterectomy_cie: ["Z907"]}
given:
- input: ref('cacu_post_colposcopy_v1_index_date')
format: sql
rows: |
select 1 as pac_id, '2025-12-01' as fecha_colposcopia union all select 2, '2025-12-01'
union all select 3, '2025-12-01'
- input: ref('cacu_linea_de_tiempo')
format: sql
rows: |
select 1 as pac_id, '2025-08-23' as fecha, 'vph' as tipo, 'POSITIVO' as valor_codigo
union all select 2, '2024-10-27', 'bethesda', 'ASC-US'
union all select 3, '2025-12-20', 'bethesda', 'LIEBG'
- input: source('silver', 'dim_fecha')
format: sql
rows: |
select '2025-12-01' as fecha, 400 as dia_num union all select '2025-08-23', 300
union all select '2024-10-27', 0 union all select '2025-12-20', 419
expect:
format: sql
rows: |
select 2 as pac_id union all select 3
@@ -0,0 +1,40 @@
{#
The patient's first colposcopy and when its result is known: one row per patient with a colposcopy up to the
cut-off. Only the first one opens the post-colposcopy sequence (Cheung et al. 2020: referred to colposcopy for the
first time). Its biopsies are the orders on the colposcopy's day (a reported biopsy shares its order's source row).
- `fecha_resultado`: the last report of those biopsies; with no biopsy ordered, the colposcopy's own date.
PROVISIONAL: a colposcopy without a biopsy order is taken as below CIN2 (normal impression), which assumes the
colposcopic impression misses no CIN2+.
- `ordenes_sin_resultado`: orders of the episode with no report up to the cut-off (result unknown).
#}
{% set p = var('post_colposcopy_cohort') %}
with eventos as (
select pac_id, fecha, tipo, valor_codigo, fuente_tabla, fuente_id
from {{ ref('cacu_linea_de_tiempo') }}
where fecha <= '{{ p.cutoff }}'
),
colposcopias as (
select pac_id, fecha, fuente_tabla, fuente_id,
row_number() over (partition by pac_id order by fecha, fuente_tabla, fuente_id) as posicion
from eventos
where tipo = 'colposcopia'
),
primera as (
select pac_id, fecha as fecha_colposcopia, fuente_tabla, fuente_id from colposcopias where posicion = 1
),
ordenes as (
select o.pac_id, o.fuente_tabla, o.fuente_id, max(b.fecha) as fecha_reporte
from eventos as o
join primera as c on c.pac_id = o.pac_id and o.fecha = c.fecha_colposcopia
left join eventos as b
on b.tipo = 'biopsia' and b.pac_id = o.pac_id and b.fuente_tabla = o.fuente_tabla and b.fuente_id = o.fuente_id
where o.tipo = 'orden_biopsia'
group by o.pac_id, o.fuente_tabla, o.fuente_id
)
select
c.pac_id, c.fecha_colposcopia, c.fuente_tabla, c.fuente_id,
coalesce((select max(o.fecha_reporte) from ordenes as o where o.pac_id = c.pac_id), c.fecha_colposcopia)
as fecha_resultado,
(select count(*) from ordenes as o where o.pac_id = c.pac_id and o.fecha_reporte is null) as ordenes_sin_resultado
from primera as c
@@ -0,0 +1,31 @@
{#
The surveillance visits after the first colposcopy, numbered 1, 2, … per patient: every cytology sample (an HPV
result shares its sample's source row) after the colposcopy's result is known and before any later colposcopy,
which closes the sequence (a re-referral; Cheung et al. 2020 model only the first). The post-colposcopy cohort of
visit k takes visit k as its index (`cacu_post_colposcopy_index`).
#}
{% set p = var('post_colposcopy_cohort') %}
with eventos as (
select pac_id, fecha, tipo, fuente_tabla, fuente_id
from {{ ref('cacu_linea_de_tiempo') }}
where fecha <= '{{ p.cutoff }}'
),
episodio as (
select * from {{ ref('cacu_post_colposcopy_episode') }}
),
cierre as (
select ep.pac_id, min(e.fecha) as fecha
from episodio as ep
join eventos as e on e.pac_id = ep.pac_id and e.tipo = 'colposcopia' and e.fecha > ep.fecha_resultado
group by ep.pac_id
)
select
t.pac_id, t.fecha, t.fuente_tabla, t.fuente_id,
ep.fecha_colposcopia, ep.fecha_resultado, ep.ordenes_sin_resultado,
row_number() over (partition by t.pac_id order by t.fecha, t.fuente_id) as numero
from eventos as t
join episodio as ep on ep.pac_id = t.pac_id
left join cierre on cierre.pac_id = t.pac_id
where t.tipo = 'citologia'
and t.fecha > ep.fecha_resultado
and (cierre.fecha is null or t.fecha < cierre.fecha)
@@ -0,0 +1,36 @@
version: 2
# Post-colposcopy cohort of visit 0 (macros/cacu_post_colposcopy.sql). Parameters: the `post_colposcopy_cohort` var.
models:
- name: cacu_post_colposcopy_v0_population
description: Every patient of the domain.
config:
materialized: ephemeral
meta:
cohort: cacu/cohorte_post_colposcopia_visita_0
kind: population
# Changing a rule changes the cohort: bump `version` (stored with every build).
version: "0.2.0"
cutoff: "{{ var('post_colposcopy_cohort')['cutoff'] }}"
parameters: "{{ var('post_colposcopy_cohort') | tojson }}"
- name: cacu_post_colposcopy_v0_index_date
description: "The colposcopy's result (below CIN2): the last report of the biopsies ordered at the patient's first colposcopy, or the colposcopy itself if none was ordered, if it falls in the recruitment window."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: index}}
- name: cacu_post_colposcopy_v0_excl_biopsia_sin_resultado
description: "A biopsy ordered at the colposcopy has no report up to the cut-off: the colposcopy's result is unknown."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: exclusion, name: biopsia_sin_resultado, order: 1}}
- name: cacu_post_colposcopy_v0_excl_cin2_hasta_el_indice
description: "A biopsy with the outcome up to the index date: the colposcopy found CIN2+, or it came before."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: exclusion, name: cin2_hasta_el_indice, order: 2}}
- name: cacu_post_colposcopy_v0_excl_antecedente_cacu
description: "A note with a cervical cancer ICD-10 (antecedente) up to the index date: a known history of CIN2+."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: exclusion, name: antecedente_cacu, order: 3}}
- name: cacu_post_colposcopy_v0_excl_histerectomia
description: "A note with an ICD-10 of hysterectomy_cie up to the index date (Cheung et al. 2020 exclude hysterectomy)."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: exclusion, name: histerectomia, order: 4}}
- name: cacu_post_colposcopy_v0_excl_tratamiento_previo
description: "Treated up to the index date: she belongs to the post-treatment cohort."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: exclusion, name: tratamiento_previo, order: 5}}
- name: cacu_post_colposcopy_v0_excl_sin_referencia
description: "No cytology or HPV result in the referral_lookback_days up to the colposcopy: the referral grade is unknown."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_0, kind: exclusion, name: sin_referencia, order: 6}}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('antecedente_cacu', 'cacu_post_colposcopy_v0_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('biopsia_sin_resultado', 'cacu_post_colposcopy_v0_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('cin2_hasta_el_indice', 'cacu_post_colposcopy_v0_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('histerectomia', 'cacu_post_colposcopy_v0_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('sin_referencia', 'cacu_post_colposcopy_v0_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('tratamiento_previo', 'cacu_post_colposcopy_v0_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_index(0) }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_population() }}
@@ -0,0 +1,39 @@
version: 2
# Post-colposcopy cohort of visit 1 (macros/cacu_post_colposcopy.sql). Parameters: the `post_colposcopy_cohort` var.
models:
- name: cacu_post_colposcopy_v1_population
description: Every patient of the domain.
config:
materialized: ephemeral
meta:
cohort: cacu/cohorte_post_colposcopia_visita_1
kind: population
# Changing a rule changes the cohort: bump `version` (stored with every build).
version: "0.2.0"
cutoff: "{{ var('post_colposcopy_cohort')['cutoff'] }}"
parameters: "{{ var('post_colposcopy_cohort') | tojson }}"
- name: cacu_post_colposcopy_v1_index_date
description: "The first surveillance visit (cytology sample) after the first colposcopy's result is known, before any later colposcopy, if it falls in the recruitment window."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: index}}
- name: cacu_post_colposcopy_v1_excl_biopsia_sin_resultado
description: "A biopsy ordered at the colposcopy has no report up to the cut-off: the colposcopy's result is unknown."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: biopsia_sin_resultado, order: 1}}
- name: cacu_post_colposcopy_v1_excl_cin2_hasta_el_indice
description: "A biopsy with the outcome up to the index date: the colposcopy found CIN2+, or it came before."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: cin2_hasta_el_indice, order: 2}}
- name: cacu_post_colposcopy_v1_excl_antecedente_cacu
description: "A note with a cervical cancer ICD-10 (antecedente) up to the index date: a known history of CIN2+."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: antecedente_cacu, order: 3}}
- name: cacu_post_colposcopy_v1_excl_histerectomia
description: "A note with an ICD-10 of hysterectomy_cie up to the index date (Cheung et al. 2020 exclude hysterectomy)."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: histerectomia, order: 4}}
- name: cacu_post_colposcopy_v1_excl_tratamiento_previo
description: "Treated up to the index date: she belongs to the post-treatment cohort."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: tratamiento_previo, order: 5}}
- name: cacu_post_colposcopy_v1_excl_sin_referencia
description: "No cytology or HPV result in the referral_lookback_days up to the colposcopy: the referral grade is unknown."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: sin_referencia, order: 6}}
- name: cacu_post_colposcopy_v1_excl_sin_cotest
description: "The index sample lacks an HPV result or a cytology result (squamous or glandular): KPNC's current result is a cotest."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_1, kind: exclusion, name: sin_cotest, order: 7}}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('antecedente_cacu', 'cacu_post_colposcopy_v1_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('biopsia_sin_resultado', 'cacu_post_colposcopy_v1_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('cin2_hasta_el_indice', 'cacu_post_colposcopy_v1_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('histerectomia', 'cacu_post_colposcopy_v1_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('sin_cotest', 'cacu_post_colposcopy_v1_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('sin_referencia', 'cacu_post_colposcopy_v1_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('tratamiento_previo', 'cacu_post_colposcopy_v1_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_index(1) }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_population() }}
@@ -0,0 +1,39 @@
version: 2
# Post-colposcopy cohort of visit 2 (macros/cacu_post_colposcopy.sql). Parameters: the `post_colposcopy_cohort` var.
models:
- name: cacu_post_colposcopy_v2_population
description: Every patient of the domain.
config:
materialized: ephemeral
meta:
cohort: cacu/cohorte_post_colposcopia_visita_2
kind: population
# Changing a rule changes the cohort: bump `version` (stored with every build).
version: "0.2.0"
cutoff: "{{ var('post_colposcopy_cohort')['cutoff'] }}"
parameters: "{{ var('post_colposcopy_cohort') | tojson }}"
- name: cacu_post_colposcopy_v2_index_date
description: "The second surveillance visit after the first colposcopy's result is known, before any later colposcopy, if it falls in the recruitment window."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_2, kind: index}}
- name: cacu_post_colposcopy_v2_excl_biopsia_sin_resultado
description: "A biopsy ordered at the colposcopy has no report up to the cut-off: the colposcopy's result is unknown."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_2, kind: exclusion, name: biopsia_sin_resultado, order: 1}}
- name: cacu_post_colposcopy_v2_excl_cin2_hasta_el_indice
description: "A biopsy with the outcome up to the index date: the colposcopy found CIN2+, or it came before."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_2, kind: exclusion, name: cin2_hasta_el_indice, order: 2}}
- name: cacu_post_colposcopy_v2_excl_antecedente_cacu
description: "A note with a cervical cancer ICD-10 (antecedente) up to the index date: a known history of CIN2+."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_2, kind: exclusion, name: antecedente_cacu, order: 3}}
- name: cacu_post_colposcopy_v2_excl_histerectomia
description: "A note with an ICD-10 of hysterectomy_cie up to the index date (Cheung et al. 2020 exclude hysterectomy)."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_2, kind: exclusion, name: histerectomia, order: 4}}
- name: cacu_post_colposcopy_v2_excl_tratamiento_previo
description: "Treated up to the index date: she belongs to the post-treatment cohort."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_2, kind: exclusion, name: tratamiento_previo, order: 5}}
- name: cacu_post_colposcopy_v2_excl_sin_referencia
description: "No cytology or HPV result in the referral_lookback_days up to the colposcopy: the referral grade is unknown."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_2, kind: exclusion, name: sin_referencia, order: 6}}
- name: cacu_post_colposcopy_v2_excl_sin_cotest
description: "The index sample lacks an HPV result or a cytology result (squamous or glandular): KPNC's current result is a cotest."
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_colposcopia_visita_2, kind: exclusion, name: sin_cotest, order: 7}}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('antecedente_cacu', 'cacu_post_colposcopy_v2_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('biopsia_sin_resultado', 'cacu_post_colposcopy_v2_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('cin2_hasta_el_indice', 'cacu_post_colposcopy_v2_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('histerectomia', 'cacu_post_colposcopy_v2_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('sin_cotest', 'cacu_post_colposcopy_v2_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('sin_referencia', 'cacu_post_colposcopy_v2_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_exclusion('tratamiento_previo', 'cacu_post_colposcopy_v2_index_date') }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_index(2) }}
@@ -0,0 +1 @@
{{ cacu_post_colposcopy_population() }}
@@ -0,0 +1,84 @@
version: 2
# The post-treatment cohort, one query per rule, read as the surveillance cohort's are. Parameters: the
# `post_treatment_cohort` var in dbt_project.yml. A treatment is the timeline's inferred `tratamiento`
# (cacu_procedimientos_inferidos).
models:
- name: cacu_post_treatment_all_patients
description: Every patient of the domain.
config:
materialized: ephemeral
meta:
cohort: cacu/cohorte_post_tratamiento
kind: population
# Changing a rule changes the cohort: bump `version` (stored with every build).
version: "0.1.0"
cutoff: "{{ var('post_treatment_cohort')['cutoff'] }}"
parameters: "{{ var('post_treatment_cohort') | tojson }}"
- name: cacu_post_treatment_index_date
description: >
First cytology past the days after the patient's first treatment, if it falls in the recruitment window. Sets
the index date; keeps the treatment's date.
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_tratamiento, kind: index}}
- name: cacu_post_treatment_excl_no_pretreatment_biopsy
description: No reported biopsy in the lookback up to the treatment, so the pre-treatment stratum is unknown.
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_tratamiento, kind: exclusion, name: no_pretreatment_biopsy, order: 1}}
- name: cacu_post_treatment_excl_event_before_index
description: Biopsy with the outcome between the treatment and the index date, a lesion found before the first post-treatment test.
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_tratamiento, kind: exclusion, name: event_before_index, order: 2}}
- name: cacu_post_treatment_excl_no_index_result
description: The index cytology has neither a cytology nor an HPV result, so there are no predictors.
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_post_tratamiento, kind: exclusion, name: no_index_result, order: 3}}
unit_tests:
- name: post_treatment_index_is_the_first_cytology_past_the_days_after_treatment
description: >
Pins down: patient 1's cytology 60 days after her treatment is too early; the one at 180 days is her index, with
her first treatment's date. Patient 2 was never treated. Fails if the index stops waiting `index_after_days` or
takes a later treatment.
model: cacu_post_treatment_index_date
overrides:
vars:
post_treatment_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], index_after_days: 90, pretreatment_lookback_days: 365}
given:
- input: ref('cacu_linea_de_tiempo')
format: sql
rows: |
select 1 as pac_id, 'tratamiento' as tipo, '2025-01-01' as fecha, 't' as fuente_tabla, 'x1' as fuente_id
union all select 1, 'tratamiento', '2025-02-01', 't', 'x2'
union all select 1, 'citologia', '2025-03-02', 't', 'a'
union all select 1, 'citologia', '2025-06-30', 't', 'b'
union all select 2, 'citologia', '2025-06-30', 't', 'c'
- input: source('silver', 'dim_fecha')
format: sql
rows: |
select '2025-01-01' as fecha, 0 as dia_num union all select '2025-02-01', 31
union all select '2025-03-02', 60 union all select '2025-06-30', 180
expect:
format: sql
rows: |
select 1 as pac_id, '2025-06-30' as fecha_indice, 't' as indice_fuente_tabla, 'b' as indice_fuente_id,
'2025-01-01' as fecha_tratamiento
- name: event_before_index_is_between_treatment_and_index
description: >
Pins down: patient 1's CIN2+ biopsy between her treatment and her index is flagged. Patient 2's is before the
treatment (the one treated) and patient 3's on the index date, so neither is. Fails if the interval's ends change.
model: cacu_post_treatment_excl_event_before_index
overrides:
vars:
post_treatment_cohort: {recruitment_start: "2025-01-01", recruitment_end: "2026-01-01", cutoff: "2026-12-31", event_grades: ["LIEAG"], index_after_days: 90, pretreatment_lookback_days: 365}
given:
- input: ref('cacu_post_treatment_index_date')
format: sql
rows: |
select 1 as pac_id, '2025-01-01' as fecha_tratamiento, '2025-07-01' as fecha_indice
union all select 2, '2025-01-01', '2025-07-01' union all select 3, '2025-01-01', '2025-07-01'
- input: ref('cacu_linea_de_tiempo')
format: sql
rows: |
select 1 as pac_id, 'biopsia' as tipo, '2025-03-01' as fecha, 'LIEAG' as valor_codigo
union all select 2, 'biopsia', '2024-12-01', 'LIEAG'
union all select 3, 'biopsia', '2025-07-01', 'LIEAG'
expect:
rows:
- {pac_id: 1}
@@ -0,0 +1,3 @@
{# Every patient of the domain: where the cohort's attrition starts. #}
select pac_id
from {{ source('silver', 'persona') }}
@@ -0,0 +1,10 @@
{# Candidates with a biopsy showing the outcome after their treatment and before their index date: a persistent or
recurrent lesion found before the first post-treatment test. #}
{% set p = var('post_treatment_cohort') %}
select distinct c.pac_id
from {{ ref('cacu_post_treatment_index_date') }} as c
join {{ ref('cacu_linea_de_tiempo') }} as e on e.pac_id = c.pac_id
where e.tipo = 'biopsia'
and e.fecha > c.fecha_tratamiento
and e.fecha < c.fecha_indice
and e.valor_codigo in ('{{ p.event_grades | join("', '") }}')
@@ -0,0 +1,14 @@
{# Candidates whose index cytology has neither a cytology result (squamous or glandular) nor an HPV result. #}
{% set p = var('post_treatment_cohort') %}
select c.pac_id
from {{ ref('cacu_post_treatment_index_date') }} as c
where not exists (
select 1
from {{ ref('cacu_linea_de_tiempo') }} as e
where e.pac_id = c.pac_id
and e.tipo in ('bethesda', 'glandular', 'vph')
and e.fuente_tabla = c.indice_fuente_tabla
and e.fuente_id = c.indice_fuente_id
and e.fecha <= '{{ p.cutoff }}'
and e.valor_codigo is not null
)
@@ -0,0 +1,18 @@
{#
Candidates with no reported biopsy in the `pretreatment_lookback_days` up to their treatment: the biopsy before
treatment, which sets the stratum, is unknown.
#}
{% set p = var('post_treatment_cohort') %}
select c.pac_id
from {{ ref('cacu_post_treatment_index_date') }} as c
join {{ source('silver', 'dim_fecha') }} as dt on dt.fecha = c.fecha_tratamiento
where not exists (
select 1
from {{ ref('cacu_linea_de_tiempo') }} as e
join {{ source('silver', 'dim_fecha') }} as de on de.fecha = e.fecha
where e.pac_id = c.pac_id
and e.tipo = 'biopsia'
and e.valor_codigo is not null
and de.dia_num <= dt.dia_num
and dt.dia_num - de.dia_num <= {{ p.pretreatment_lookback_days }}
)
@@ -0,0 +1,27 @@
{#
The first cytology more than `index_after_days` after the patient's first treatment, up to the cut-off, if it falls
in the recruitment window. Sets the index date and keeps the treatment's date for the rules. Days are differences
of `dim_fecha.dia_num`.
#}
{% set p = var('post_treatment_cohort') %}
with treatment as (
select pac_id, min(fecha) as fecha
from {{ ref('cacu_linea_de_tiempo') }}
where tipo = 'tratamiento' and fecha <= '{{ p.cutoff }}'
group by pac_id
),
cytologies as (
select
l.pac_id, l.fecha, l.fuente_tabla, l.fuente_id, t.fecha as fecha_tratamiento,
row_number() over (partition by l.pac_id order by l.fecha, l.fuente_id) as position
from {{ ref('cacu_linea_de_tiempo') }} as l
join treatment as t on t.pac_id = l.pac_id
join {{ source('silver', 'dim_fecha') }} as dl on dl.fecha = l.fecha
join {{ source('silver', 'dim_fecha') }} as dt on dt.fecha = t.fecha
where l.tipo = 'citologia' and l.fecha <= '{{ p.cutoff }}'
and dl.dia_num - dt.dia_num > {{ p.index_after_days }}
)
select pac_id, fecha as fecha_indice, fuente_tabla as indice_fuente_tabla, fuente_id as indice_fuente_id,
fecha_tratamiento
from cytologies
where position = 1 and fecha >= '{{ p.recruitment_start }}' and fecha < '{{ p.recruitment_end }}'
@@ -13,6 +13,8 @@ models:
meta:
cohort: cacu/cohorte_vigilancia
kind: population
# Changing a rule changes the cohort: bump `version` (stored with every build).
version: "0.2.0"
cutoff: "{{ var('surveillance_cohort')['cutoff'] }}"
parameters: "{{ var('surveillance_cohort') | tojson }}"
- name: cacu_surveillance_index_date
@@ -24,6 +26,9 @@ models:
- name: cacu_surveillance_excl_no_index_result
description: The index cytology has neither a cytology nor an HPV result, so there are no predictors.
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_vigilancia, kind: exclusion, name: no_index_result, order: 2}}
- name: cacu_surveillance_variables
description: The index sample's Bethesda (`pap_0`) and HPV (`hpv_0`) results, stored with each build.
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_vigilancia, kind: variables}}
unit_tests:
- name: prior_event_flags_an_earlier_biopsy_with_the_outcome
@@ -53,9 +58,10 @@ unit_tests:
- {pac_id: 1}
- name: no_index_result_ignores_results_of_other_cytologies
description: >
Pins down: patient 1 has a result on its index cytology and patient 2 has an HPV result there, so neither is
flagged. Patient 3's only result belongs to another cytology and patient 4's has no value, so both are. Fails if the
rule stops matching the index cytology or counts an empty result.
Pins down: patient 1 has a result on its index cytology, patient 2 an HPV result there and patient 5 only a
glandular one (AGC), so none is flagged. Patient 3's only result belongs to another cytology and patient 4's has
no value, so both are. Fails if the rule stops matching the index cytology, counts an empty result or ignores
the glandular result.
model: cacu_surveillance_excl_no_index_result
overrides:
vars:
@@ -66,7 +72,7 @@ unit_tests:
rows: |
select 1 as pac_id, 'citologiacervical' as indice_fuente_tabla, 'a' as indice_fuente_id
union all select 2, 'citologiacervical', 'b' union all select 3, 'citologiacervical', 'c'
union all select 4, 'citologiacervical', 'd'
union all select 4, 'citologiacervical', 'd' union all select 5, 'citologiacervical', 'e'
- input: ref('cacu_linea_de_tiempo')
format: sql
rows: |
@@ -74,6 +80,7 @@ unit_tests:
union all select 2, 'vph', 'citologiacervical', 'b', '2025-01-01', 'POSITIVO'
union all select 3, 'bethesda', 'citologiacervical', 'other', '2025-01-01', 'NORMAL'
union all select 4, 'bethesda', 'citologiacervical', 'd', '2025-01-01', null
union all select 5, 'glandular', 'citologiacervical', 'e', '2025-01-01', 'AGC'
expect:
rows:
- {pac_id: 3}
@@ -1,4 +1,4 @@
{# Candidates whose index cytology has neither a cytology result nor an HPV result. #}
{# Candidates whose index cytology has neither a cytology result (squamous or glandular) nor an HPV result. #}
{% set p = var('surveillance_cohort') %}
select c.pac_id
from {{ ref('cacu_surveillance_index_date') }} as c
@@ -6,7 +6,7 @@ where not exists (
select 1
from {{ ref('cacu_linea_de_tiempo') }} as e
where e.pac_id = c.pac_id
and e.tipo in ('bethesda', 'vph')
and e.tipo in ('bethesda', 'glandular', 'vph')
and e.fuente_tabla = c.indice_fuente_tabla
and e.fuente_id = c.indice_fuente_id
and e.fecha <= '{{ p.cutoff }}'
@@ -0,0 +1,15 @@
{#
The variables the build stores for each patient with an index (long: one row per variable), from her index sample:
`pap_0` (squamous Bethesda) and `hpv_0` (HPV). The WebApp's patient record shows them. The interval coding (`c`,
`l`, `r`) is the model's (`cin2_pim`), not a cohort rule.
#}
{% set p = var('surveillance_cohort') %}
select c.pac_id,
case e.tipo when 'bethesda' then 'pap_0' else 'hpv_0' end as variable,
min(e.valor_codigo) as valor_codigo,
cast(null as {{ dbt.type_float() }}) as valor_numerico
from {{ ref('cacu_surveillance_index_date') }} as c
join {{ ref('cacu_linea_de_tiempo') }} as e
on e.pac_id = c.pac_id and e.fuente_tabla = c.indice_fuente_tabla and e.fuente_id = c.indice_fuente_id
where e.tipo in ('bethesda', 'vph') and e.valor_codigo is not null and e.fecha <= '{{ p.cutoff }}'
group by c.pac_id, e.tipo
@@ -0,0 +1,41 @@
version: 2
# The total cohort: every patient with an event up to the cut-off, at her first event, with no rules. For models
# whose cohort rules are too involved for SQL: they read this cohort and the timeline and apply their own rules,
# which then belong to the model (and its tests), not to a cohort. Parameters: the `total_cohort` var.
models:
- name: cacu_total_population
description: Every patient of the domain.
config:
materialized: ephemeral
meta:
cohort: cacu/cohorte_total
kind: population
# Changing a rule changes the cohort: bump `version` (stored with every build).
version: "0.1.0"
cutoff: "{{ var('total_cohort')['cutoff'] }}"
parameters: "{{ var('total_cohort') | tojson }}"
- name: cacu_total_index_date
description: The patient's first event in the timeline up to the cut-off. Sets the index date.
config: {materialized: ephemeral, meta: {cohort: cacu/cohorte_total, kind: index}}
unit_tests:
- name: total_index_is_the_first_event_up_to_the_cutoff
description: >
Pins down: patient 1's index is her earliest event, whatever its type; patient 2's only event is after the
cut-off, so she has no index. Fails if the index takes a later event, one type only, or ignores the cut-off.
model: cacu_total_index_date
overrides:
vars:
total_cohort: {cutoff: "2026-12-31"}
given:
- input: ref('cacu_linea_de_tiempo')
format: sql
rows: |
select 1 as pac_id, '2025-05-01' as fecha, 'citologia' as tipo, 't' as fuente_tabla, 'b' as fuente_id
union all select 1, '2024-02-01', 'nota_medica', 'n', 'a'
union all select 2, '2027-03-01', 'citologia', 't', 'c'
expect:
format: sql
rows: |
select 1 as pac_id, '2024-02-01' as fecha_indice, 'n' as indice_fuente_tabla, 'a' as indice_fuente_id
@@ -0,0 +1,15 @@
{#
Every patient with at least one event in the timeline up to the cut-off, indexed at her first event (the earliest,
ties broken by source). No recruitment window and no exclusions: a model whose rules can't be written as SQL
starts from this cohort and applies them in its own pipeline, over the timeline.
#}
{% set p = var('total_cohort') %}
with eventos as (
select pac_id, fecha, fuente_tabla, fuente_id,
row_number() over (partition by pac_id order by fecha, fuente_tabla, fuente_id) as posicion
from {{ ref('cacu_linea_de_tiempo') }}
where fecha <= '{{ p.cutoff }}'
)
select pac_id, fecha as fecha_indice, fuente_tabla as indice_fuente_tabla, fuente_id as indice_fuente_id
from eventos
where posicion = 1
@@ -0,0 +1,2 @@
{# Every patient of the domain: where the cohort's attrition starts. #}
select pac_id from {{ source('silver', 'persona') }}
@@ -1,5 +1,7 @@
-- One row per member of the surveillance cohort build that the current batch of risk estimates scored, with her
-- index date and the probability of her estimate in force, null if she has none. The current batch is the latest one
-- One row per member of the surveillance cohort build that the current batch of risk estimates scored, with the
-- index date of her estimate (`evaluacion_riesgo.fecha_indice`: the model's decision point, which dates the period)
-- and the probability of her estimate in force, null if she has none. A member the batch never scored keeps her
-- member's index date, so she still falls in a period as no data. The current batch is the latest one
-- of the cohort with some estimate in force; an estimate is in force when its latest version, at the horizon
-- `riesgos_horizonte_banda`, is `final` (a later `entered-in-error` version voids it). When a member and an estimate
-- became known: the build's and the estimate's registration.
@@ -8,6 +10,7 @@ with recientes as (
select
e.lote_id,
e.pac_id,
e.fecha_indice,
e.probabilidad,
e.estado,
e.registrado_en,
@@ -20,6 +23,11 @@ vigentes as (
select lote_id, pac_id, probabilidad, registrado_en from recientes where lugar = 1 and estado = 'final'
),
-- the index date of each scored member's estimate, whatever its state (a voided one still dates her)
fechas as (
select lote_id, pac_id, max(fecha_indice) as fecha_indice from recientes group by lote_id, pac_id
),
lote_vigente as (
select max(l.lote_id) as lote_id
from {{ source('oro', 'evaluacion_riesgo_lote') }} l
@@ -30,7 +38,7 @@ lote_vigente as (
select
m.pac_id,
m.fecha_indice,
coalesce(f.fecha_indice, m.fecha_indice) as fecha_indice,
a.armado_en as miembro_conocido_en,
v.probabilidad,
v.registrado_en as evaluacion_conocida_en
@@ -39,3 +47,4 @@ join {{ source('oro', 'evaluacion_riesgo_lote') }} l on l.lote_id = lv.lote_id
join {{ source('oro', 'cohorte_armado') }} a on a.armado_id = l.armado_id
join {{ source('oro', 'cohorte_miembro') }} m on m.armado_id = l.armado_id
left join vigentes v on v.lote_id = lv.lote_id and v.pac_id = m.pac_id
left join fechas f on f.lote_id = lv.lote_id and f.pac_id = m.pac_id
@@ -51,13 +51,6 @@ metrics:
meta:
measure_url: cacu/CACU_RIESGO_BANDA
version: 0.1.0
ficha:
codigo: RIESGO
para: Médico
unidad: pacientes
pregunta: ¿Cómo se reparten las pacientes en vigilancia por su riesgo estimado de CIN2+?
definicion: 'Pacientes de la cohorte de vigilancia con citología índice en el semestre, por la banda de su riesgo
estimado de CIN2+ (lote confirmado más reciente). «Sin dato»: sin evaluación confirmada.'
scoring: composition
basis: paciente
grupo: TOTAL
@@ -101,29 +101,6 @@ metrics:
meta:
measure_url: cacu/CACU_EU13
version: 0.3.2
referencias:
- tipo: citation
etiqueta: European Guidelines for QA in Cervical Cancer Screening, 2ª ed. (2008)
ref: indicador 13
descripcion_poblaciones:
initial-population: Pacientes con al menos una citología tomada en el periodo.
denominator: 'Las de la población inicial: todas las pacientes tamizadas en el periodo, sin importar el resultado
de su citología.'
numerator: De ellas, las que tienen una biopsia reportada a la fecha de corte con grado LIEAG (CIN 2 y 3), carcinoma
in situ o carcinoma invasor, originada por una de sus citologías del periodo. Cada paciente cuenta una vez.
figuras_detalle:
fig_c1_puntos:
descripcion: Un punto por periodo con el porcentaje de todas las pacientes tamizadas del periodo que tienen
una lesión confirmada por biopsia, con su intervalo de confianza al 95 %.
como_leer:
- El denominador son todas las pacientes tamizadas del periodo, tengan o no una citología anormal o una biopsia.
No es la «Tasa de confirmación histopatológica», que se calcula sobre las mujeres con citología de alto grado
y biopsia.
- 'El punto es el porcentaje; la barra vertical, su intervalo de confianza de Wilson al 95 %: con pocas pacientes
es ancho y el valor es poco preciso.'
- 'El periodo es el de la citología, no el del reporte de la biopsia: el valor de un periodo reciente puede
subir mientras lleguen reportes.'
- Un periodo sin punto tiene muy pocas pacientes tamizadas para mostrarse.
scoring: proportion
basis: paciente
grupo: principal
@@ -164,53 +141,6 @@ metrics:
meta:
measure_url: cacu/CACU_CONFIRMACION_CITOLOGIA
version: 0.1.2
ficha:
codigo: CONFIRMACION_CITOLOGIA
para: Médico
unidad: pacientes
pregunta: De las pacientes con citología de alto grado (ASC-H, LIEAG o carcinoma in situ) y biopsia, ¿en cuántas
confirma la biopsia una lesión de LIEAG o más, según su resultado citológico?
definicion: 'Pacientes con citología tomada en el semestre cuya última citología con resultado y calidad de espécimen
satisfactoria es ASC-H, LIEAG o carcinoma in situ, por el grado de la biopsia que esa citología originó (la
más grave, si hay varias). «Sin biopsia aún»: no tiene biopsia reportada a la fecha de corte. «Sin dato»: la
biopsia se reportó sin grado.'
nota: 'El porcentaje de cada resultado citológico se calcula sobre las pacientes de ese resultado con biopsia:
las que no la tienen aún no entran. Con «LIEAG o más» es el valor predictivo positivo de la citología.'
descripcion_poblaciones:
initial-population: Pacientes con citología tomada en el periodo cuya última citología con resultado a la fecha
de corte y calidad de espécimen satisfactoria es ASC-H, LIEAG o carcinoma in situ (sistema Bethesda). Cada una
cuenta en el grado de la biopsia más grave originada por esa citología y reportada a la fecha de corte; en «Sin
biopsia aún» si no tiene ninguna, o en «Sin dato» si la biopsia no trae grado.
figuras_detalle:
fig_c2_barras:
descripcion: A un lado de la dona, un punto por resultado citológico (ASC-H, LIEAG, carcinoma in situ) con el
porcentaje de mujeres con biopsia cuyo grado está en lo seleccionado en la dona, y su intervalo de confianza
de Wilson al 95 %.
como_leer:
- El denominador de cada fila son las mujeres de ese resultado citológico con biopsia reportada a la fecha de
corte; las que no tienen biopsia aún no entran.
- 'Con «LIEAG o más» seleccionado, el punto es la proporción de verdaderos positivos: el valor predictivo positivo
de ese resultado citológico.'
- 'Con «Normal» seleccionado, es la proporción de falsos positivos: la biopsia no encontró lesión.'
- 'La barra horizontal es el intervalo de Wilson al 95 %: con pocas mujeres es ancho y el valor es poco preciso.'
- Una fila marcada «Suprimido» o «Dato oculto» tiene muy pocas mujeres para mostrarse; no es cero.
- Se lee en un solo periodo; por omisión, el semestre más reciente. El valor de un periodo reciente puede cambiar
mientras lleguen reportes.
fig_c2_donas:
descripcion: 'Dona de dos anillos con el grado de la biopsia de las mujeres con citología de alto grado: el
interior separa «LIEAG o más» de «Menor que LIEAG» y el exterior abre cada grupo en sus grados.'
como_leer:
- Cada mujer cuenta una vez, en el grado de la biopsia que originó su última citología del periodo con resultado
y calidad de espécimen satisfactoria; si hay varias, la más grave.
- '«LIEAG o más»: LIEAG (CIN 2 y 3), carcinoma in situ y carcinoma invasor; es el mismo umbral de la «Tasa de
detección histopatológica».'
- 'Sin selección, la vista vuelve a «LIEAG o más»: al centro va el número de mujeres de lo seleccionado sobre
las que tienen biopsia.'
- Un clic en un grupo o en un grado lo selecciona, y los puntos de al lado lo siguen; el centro regresa a «LIEAG
o más».
- '«Sin biopsia aún» se informa fuera de la dona: mujeres sin biopsia reportada a la fecha de corte. «Sin dato»:
la biopsia se reportó sin grado.'
- Una celda «Suprimido» tiene muy pocas mujeres para mostrarse; no es cero.
scoring: composition
basis: paciente
grupo: TOTAL
@@ -105,21 +105,6 @@ metrics:
meta:
measure_url: cacu/IND1
version: 0.3.2
descripcion_poblaciones:
initial-population: Pacientes con al menos una citología tomada en el periodo.
denominator: Las de la población inicial.
numerator: De ellas, las que tienen al menos una citología del periodo con resultado ASC-US, LIEBG, ASC-H, LIEAG
o carcinoma in situ. Cada paciente cuenta una vez.
figuras_detalle:
fig_c1_puntos:
descripcion: Un punto por periodo con el porcentaje de pacientes con citología en el periodo que tienen al menos
un resultado anómalo, con su intervalo de confianza al 95 %.
como_leer:
- 'El punto es el porcentaje; la barra vertical, su intervalo de confianza de Wilson al 95 %: con pocas pacientes
es ancho y el valor es poco preciso.'
- 'Menos es mejor: un valor que baja indica menos pacientes con resultados anómalos.'
- Una paciente con varias citologías anómalas en el periodo cuenta una vez.
- Un periodo sin punto tiene muy pocas pacientes para mostrarse.
scoring: proportion
basis: paciente
grupo: principal
@@ -141,48 +126,6 @@ metrics:
meta:
measure_url: cacu/CACU_EU7
version: 0.3.3
ficha:
codigo: EU7
para: Médico
unidad: pacientes
pregunta: ¿Cómo se distribuyen las pacientes por resultado citológico?
definicion: 'Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado
y calidad de espécimen satisfactoria. «Sin dato»: resultado no disponible o de calidad de espécimen insatisfactoria
a la fecha de corte.'
referencias:
- tipo: citation
etiqueta: European Guidelines for QA in Cervical Cancer Screening, 2ª ed. (2008)
ref: indicador 7
descripcion_poblaciones:
initial-population: Pacientes con al menos una citología tomada en el periodo. Cada una cuenta en el resultado
de su última citología con resultado y calidad de espécimen satisfactoria, o en «Sin dato» si su resultado no
está disponible o la calidad del espécimen es insatisfactoria a la fecha de corte.
figuras_detalle:
fig_c2_barras:
descripcion: Barras 100 % apiladas, una por escenario clínico (el estatus de seguimiento de la paciente al inicio
del periodo), con la proporción de pacientes en cada resultado citológico.
como_leer:
- Cada barra es el 100 % de las pacientes de ese escenario con resultado disponible; «Sin dato» no entra.
- 'Siguen lo seleccionado en la dona: muestran solo ese grupo o esa categoría, sobre el mismo denominador.'
- 'Un escenario marcado «Suprimido» o «No disponible» no es cero: tiene muy pocas pacientes para mostrarse o
no hay dato.'
- 'Importante: cada escenario tiene su propio denominador; al comparar escenarios, revise cuántas pacientes
tiene cada uno.'
fig_c2_donas:
descripcion: 'Dona de dos anillos con las pacientes del periodo: el interior separa «Anormal» de «Sin anomalía»
y el exterior abre cada grupo en sus categorías Bethesda.'
como_leer:
- Cada paciente cuenta una vez, en el resultado de su última citología del periodo con resultado y calidad de
espécimen satisfactoria.
- Cada segmento es la proporción de pacientes de su categoría.
- '«Anormal»: ASC-US, LIEBG, ASC-H, LIEAG y carcinoma in situ; «Sin anomalía»: Normal.'
- Al centro va el número de pacientes del grupo seleccionado; sin selección, el total.
- Un clic en un grupo lo abre en sus categorías; un clic en una categoría la resalta.
- El centro (o «Volver») regresa de la categoría al grupo y del grupo al total.
- '«Sin dato» se informa fuera de la dona: pacientes con citología en el periodo con resultado no disponible
o de calidad de espécimen insatisfactoria a la fecha de corte.'
- Una celda «Suprimido» tiene muy pocas pacientes para mostrarse; no es cero.
- Se lee en un solo periodo; por omisión, el semestre más reciente.
scoring: composition
basis: paciente
grupo: TOTAL
@@ -236,31 +179,6 @@ metrics:
meta:
measure_url: cacu/CACU_EU_TIEMPO_REPORTE
version: 0.2.1
ficha:
codigo: TIEMPO_REPORTE
para: Médico
unidad: citologías
pregunta: ¿Cuántos días pasan de la toma de la citología a su resultado?
definicion: Días naturales de la toma de cada citología del semestre a su resultado, a la fecha de corte.
nota: Días de la toma al resultado. La caja va del primer al tercer cuartil y la línea es la mediana; no se dibuja
cada citología. No cuenta las que siguen dentro del horizonte sin resultado.
descripcion_poblaciones:
initial-population: 'Citologías tomadas en el periodo que ya se pueden medir: con resultado a la fecha de corte,
o sin él y con el horizonte vencido (`cacu.horizontes.toma_reporte_dias`).'
measure-observation: De ellas, las que tienen resultado a la fecha de corte, con los días naturales de la toma
al resultado.
figuras_detalle:
fig_c3r_caja:
descripcion: 'Una caja por periodo con los días naturales de la toma de cada citología a su resultado: primer
cuartil, mediana y tercer cuartil.'
como_leer:
- 'La línea central es la mediana: la mitad de las citologías llegó en ese número de días o menos.'
- La caja va del primer al tercer cuartil (la mitad central de las citologías); no se dibujan extremos ni citologías
sueltas.
- Menos días es mejor.
- Al pasar el cursor se ve n, el número de citologías medidas.
- 'Solo entran las citologías que ya se pueden medir: las que todavía esperan resultado dentro del horizonte
se miden después, así que la caja de un periodo reciente puede cambiar.'
scoring: continuous-variable
basis: examen
grupo: TOTAL
@@ -295,37 +213,6 @@ metrics:
meta:
measure_url: cacu/CACU_DIAS_TOMA_DIAGNOSTICO
version: 0.2.3
ficha:
codigo: DIAS_DX
para: Médico
unidad: citologías
pregunta: ¿Cuántos días pasan de la toma de la citología al diagnóstico?
definicion: Días naturales de la toma de cada citología del semestre a la primera nota médica posterior con un
diagnóstico CIE-10 que la resuelve (normal, benigno, lesión o cáncer), de una especialidad que diagnostica,
dentro del horizonte y a la fecha de corte. No entran las de pacientes con un diagnóstico de cáncer cervicouterino
anterior a la toma.
nota: Días de la toma al diagnóstico. La caja va del primer al tercer cuartil y la línea es la mediana. No cuenta
las que siguen dentro del horizonte sin diagnóstico; las que lo pasaron sin diagnóstico cuentan en los excluidos.
descripcion_poblaciones:
initial-population: 'Citologías tomadas en el periodo que ya se pueden medir, sin las de pacientes con un diagnóstico
de cáncer cervicouterino anterior a la toma: con diagnóstico a la fecha de corte, o sin él y con más de 180
días desde la toma.'
measure-observation: De ellas, las que tienen una nota que las resuelve (con un diagnóstico CIE-10 normal, de
VPH, de lesión o de cáncer cervicouterino, escrita por la clínica de la mujer y colposcopia o por cirugía oncológica),
con los días naturales de la toma a esa nota.
figuras_detalle:
fig_c3r_caja:
descripcion: 'Una caja por periodo con los días naturales de la toma de cada citología a la primera nota médica
que la resuelve: primer cuartil, mediana y tercer cuartil.'
como_leer:
- 'La línea central es la mediana: la mitad de las citologías llegó en ese número de días o menos.'
- La caja va del primer al tercer cuartil (la mitad central de las citologías); no se dibujan extremos ni citologías
sueltas.
- Menos días es mejor.
- Al pasar el cursor se ve n, el número de citologías medidas.
- No entran las citologías de pacientes con un diagnóstico previo de cáncer cervicouterino.
- Las que todavía esperan su nota dentro del horizonte se miden después, así que la caja de un periodo reciente
puede cambiar.
scoring: continuous-variable
basis: examen
grupo: TOTAL
@@ -16,8 +16,12 @@ models:
fuentes:
- {estudio_id: "citologia", clase: "toma", resultado_id: "citologia.calidad_muestra", clase_de_linea: "procedimiento", tipo: "citologia", codigo: "citologia_cervical"}
- {estudio_id: "citologia", clase: "reporte", resultado_id: "citologia.bethesda", clase_de_linea: "medicion", tipo: "bethesda", codigo: "bethesda"}
- {estudio_id: "citologia", clase: "reporte", resultado_id: "citologia.celulas_glandulares", clase_de_linea: "medicion", tipo: "glandular"}
- {estudio_id: "vph", clase: "reporte", resultado_id: "vph.resultado", clase_de_linea: "medicion", tipo: "vph", codigo: "vph"}
- {estudio_id: "vph", clase: "reporte", resultado_id: "vph.genotipo_16_18", clase_de_linea: "medicion", tipo: "vph_genotipo_16_18", valor: "numerico"}
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.grado", clase_de_linea: "medicion", tipo: "biopsia", codigo: "cin"}
- {estudio_id: null, clase: "orden", resultado_id: null, clase_de_linea: "orden", tipo: "orden", columna: "codigo_fuente"}
# A biopsy order as such: the post-colposcopy cohorts tell an order still without a report (same source row
# as its `biopsia`) from a colposcopy with no biopsy taken.
- {estudio_id: "biopsia", clase: "orden", resultado_id: null, clase_de_linea: "orden", tipo: "orden_biopsia"}
- {estudio_id: "nota_medica", clase: "encuentro", resultado_id: "nota_medica.diagnostico", clase_de_linea: "diagnostico", tipo: "nota_medica"}
@@ -0,0 +1,77 @@
version: 2
# The survival cohort, one query per rule, compiled and chained by `models cohorts build` like CaCu's surveillance
# cohort. Whoever has the procedure of interest enters, a surgery of a kind in `surgeries`, its date the index: its
# report is where the catalog's covariates are (histology, receptors, size, nodes, margins), while the needle biopsy
# before it only says whether there is a carcinoma. The one filter keeps the patients in post-treatment. Parameters:
# the `survival_cohort` var in dbt_project.yml.
models:
- name: cama_survival_all_patients
description: Every patient of the domain.
config:
materialized: ephemeral
meta:
cohort: cama/cohorte_supervivencia
kind: population
cutoff: "{{ var('survival_cohort')['cutoff'] }}"
parameters: "{{ var('survival_cohort') | tojson }}"
- name: cama_survival_index_date
description: First breast surgery of a kind in `surgeries`, if it falls in the recruitment window. Sets the index date.
config: {materialized: ephemeral, meta: {cohort: cama/cohorte_supervivencia, kind: index}}
- name: cama_survival_excl_not_post_treatment
description: Not in post-treatment by the cut-off (no `escenario_postratamiento` in the timeline).
config: {materialized: ephemeral, meta: {cohort: cama/cohorte_supervivencia, kind: exclusion, name: not_post_treatment, order: 1}}
unit_tests:
- name: survival_index_is_the_first_therapeutic_surgery_in_the_window
description: >
Pins down: patient 1's index is her first surgery of a listed kind, not the earlier one of another kind; patient
2's two surgeries on one day give one index, the lower `fuente_id`; patient 3's first surgery falls before the
window, so she has no index even with a later one; patient 4 has only a radiotherapy. Fails if the index stops
filtering by kind, ordering by date or applying the window to the first surgery only.
model: cama_survival_index_date
overrides:
vars:
survival_cohort: {recruitment_start: "2020-01-01", recruitment_end: "2027-01-01", cutoff: "2026-12-31", surgeries: ["SEGMENTECTOMIA", "MASTECTOMIA_TOTAL"]}
given:
- input: ref('cama_linea_de_tiempo')
format: sql
rows: |
select 1 as pac_id, '2023-01-10' as fecha, 'cirugia' as tipo, 'ESCISIONAL' as valor_codigo, 'cx' as fuente_tabla, 'a' as fuente_id
union all select 1, '2023-03-01', 'cirugia', 'SEGMENTECTOMIA', 'cx', 'b'
union all select 2, '2024-05-05', 'cirugia', 'MASTECTOMIA_TOTAL', 'cx', 'd'
union all select 2, '2024-05-05', 'cirugia', 'MASTECTOMIA_TOTAL', 'cx', 'c'
union all select 3, '2019-06-01', 'cirugia', 'SEGMENTECTOMIA', 'cx', 'e'
union all select 3, '2021-06-01', 'cirugia', 'MASTECTOMIA_TOTAL', 'cx', 'f'
union all select 4, '2024-01-01', 'radioterapia', 'ADYUVANTE', 'rt', 'g'
expect:
format: sql
rows: |
select 1 as pac_id, '2023-03-01' as fecha_indice, 'cx' as indice_fuente_tabla, 'b' as indice_fuente_id
union all select 2, '2024-05-05', 'cx', 'c'
- name: survival_keeps_only_patients_in_post_treatment
description: >
Pins down: patient 1 entered post-treatment before the cut-off, so she stays; patient 2 is only in control,
patient 3's post-treatment starts after the cut-off and patient 4 has no scenario, so the three are flagged.
Fails if the filter reads another scenario or ignores the cut-off.
model: cama_survival_excl_not_post_treatment
overrides:
vars:
survival_cohort: {recruitment_start: "2020-01-01", recruitment_end: "2027-01-01", cutoff: "2026-12-31", surgeries: ["SEGMENTECTOMIA"]}
given:
- input: ref('cama_survival_index_date')
format: sql
rows: |
select 1 as pac_id, '2024-03-01' as fecha_indice union all select 2, '2024-03-01'
union all select 3, '2024-03-01' union all select 4, '2024-03-01'
- input: ref('cama_linea_de_tiempo')
format: sql
rows: |
select 1 as pac_id, '2024-03-10' as fecha, 'escenario_postratamiento' as tipo
union all select 2, '2024-02-01', 'antecedente'
union all select 3, '2027-02-01', 'escenario_postratamiento'
expect:
rows:
- {pac_id: 2}
- {pac_id: 3}
- {pac_id: 4}
@@ -0,0 +1,3 @@
{# Every patient of the domain: where the cohort's attrition starts. #}
select pac_id
from {{ source('silver', 'persona') }}
@@ -0,0 +1,12 @@
{# Candidates not in post-treatment by the cut-off: no `escenario_postratamiento` fact in their timeline
(`cama_procedimientos_inferidos`, rules in `cama.escenarios`). #}
{% set p = var('survival_cohort') %}
select c.pac_id
from {{ ref('cama_survival_index_date') }} as c
where not exists (
select 1
from {{ ref('cama_linea_de_tiempo') }} as e
where e.pac_id = c.pac_id
and e.tipo = 'escenario_postratamiento'
and e.fecha <= '{{ p.cutoff }}'
)
@@ -0,0 +1,14 @@
{# The patient's first breast surgery of a kind in `surgeries` up to the cut-off, if it falls in the recruitment window:
where the surgical report gives the covariates. A surgery per breast on the same day is one index; the lower
`fuente_id` names it. #}
{% set p = var('survival_cohort') %}
with surgeries as (
select
pac_id, fecha, fuente_tabla, fuente_id,
row_number() over (partition by pac_id order by fecha, fuente_id) as position
from {{ ref('cama_linea_de_tiempo') }}
where tipo = 'cirugia' and valor_codigo in {{ sql_list(p.surgeries) }} and fecha <= '{{ p.cutoff }}'
)
select pac_id, fecha as fecha_indice, fuente_tabla as indice_fuente_tabla, fuente_id as indice_fuente_id
from surgeries
where position = 1 and fecha >= '{{ p.recruitment_start }}' and fecha < '{{ p.recruitment_end }}'
@@ -44,19 +44,19 @@ semantic_models:
metrics:
- name: cama_birads_cancer_invasor
label: "BI-RADS de los cánceres invasores"
label: "BI-RADS de la mastografía previa a un cáncer invasor"
description: >-
De las pacientes con una biopsia reportada en el periodo con carcinoma invasor, cuántas tenían cada BI-RADS en la
mastografía que originó su biopsia más reciente, por edad y por las características del tumor: estadio clínico,
etapa, subtipo molecular y tamaño. Las características vienen de los reportes leídos por texto y son
provisionales. «Sin dato»: la biopsia no se ligó a una mastografía con BI-RADS.
mastografía que originó su biopsia más reciente. No se desglosa por las características del tumor: describen el
cáncer, no esa mastografía (Estadio y tamaño tienen sus propias medidas). «Sin dato»: la biopsia no se ligó a una
mastografía con BI-RADS.
type: simple
type_params:
measure: pacientes_con_cancer_invasor
config:
meta:
measure_url: cama/CAMA_BIRADS_CANCER_INVASOR
version: 0.1.0
version: 0.2.0
scoring: composition
basis: paciente
grupo: TOTAL
@@ -71,52 +71,3 @@ metrics:
elige: ultimo_valido
valido: "{% raw %}{{ Dimension('cancer__birads') }} is not null{% endraw %}"
orden: [fecha_reporte, fuente_id]
# The tumour's stratifiers: what cama_estratificadores held by the event cut-off (the stage or the subtype
# is usually written after the biopsy). The first value that holds wins: the most advanced, or for the
# subtype the one with the worst prognosis, when the reports disagree.
estratos:
grupo_edad:
tipo: edad_al_inicio_del_periodo
nacimiento: fecha_nacimiento
estadio:
tipo: linea_de_tiempo_al_corte
etiqueta: Estadio clínico
linea: cama_estratificadores
valores:
- {valor: IV, etiqueta: Estadio IV, si: [{estadio_iv: true}]}
- {valor: III, etiqueta: Estadio III, si: [{estadio_iii: true}]}
- {valor: II, etiqueta: Estadio II, si: [{estadio_ii: true}]}
- {valor: I, etiqueta: Estadio I, si: [{estadio_i: true}]}
- {valor: "0", etiqueta: Estadio 0, si: [{estadio_0: true}]}
resto: SIN_DATO
resto_etiqueta: Sin dato
etapa:
tipo: linea_de_tiempo_al_corte
etiqueta: Etapa
linea: cama_estratificadores
valores:
- {valor: AVANZADA, etiqueta: Avanzada (III a IV), si: [{etapa_avanzada: true}]}
- {valor: TEMPRANA, etiqueta: Temprana (0 a II), si: [{etapa_temprana: true}]}
resto: SIN_DATO
resto_etiqueta: Sin dato
clasificacion:
tipo: linea_de_tiempo_al_corte
etiqueta: Subtipo molecular
linea: cama_estratificadores
valores:
- {valor: TN, etiqueta: Triple negativo, si: [{subtipo_triple_negativo: true}]}
- {valor: HER2, etiqueta: HER2 positivo, si: [{subtipo_her2: true}]}
- {valor: LUM_B, etiqueta: Luminal B, si: [{subtipo_luminal_b: true}]}
- {valor: LUM_A, etiqueta: Luminal A, si: [{subtipo_luminal_a: true}]}
resto: SIN_DATO
resto_etiqueta: Sin dato
tamano:
tipo: linea_de_tiempo_al_corte
etiqueta: Tamaño tumoral (T)
linea: cama_estratificadores
valores:
- {valor: T3, etiqueta: "> 5 cm (T3)", si: [{tamano_t3: true}]}
- {valor: T2, etiqueta: "> 2 a 5 cm (T2)", si: [{tamano_t2: true}]}
- {valor: T1, etiqueta: "≤ 2 cm (T1)", si: [{tamano_t1: true}]}
resto: SIN_DATO
resto_etiqueta: Sin dato
@@ -0,0 +1,16 @@
-- One row per biopsy report, dated by the report, flagged for the detection rate: `con_resultado` when its grade is one
-- of `vars.cama.biopsia_gravedad` (benign, in situ or invasive; a report without a grade, or with one the catalog doesn't
-- know, has none) and `maligno` when it is one of `vars.cama.grados_cancer` (the keys of the parameter
-- `cama.biopsia_cancer`). The flags are of the model, not rows of the parameter table, so a database that already holds
-- the other CaMa views answers the measure with only this view added.
select
r.procedimiento_id,
r.fuente_id,
r.pac_id,
r.fecha_reporte,
r.grado,
r.reporte_conocido_en,
case when r.grado in {{ sql_list(var('cama')['biopsia_gravedad']) }} then 1 else 0 end as con_resultado,
case when r.grado in {{ sql_list(var('cama')['grados_cancer']) }} then 1 else 0 end as maligno
from {{ ref('cama_reportes_biopsia') }} r
@@ -0,0 +1,88 @@
version: 2
models:
- name: cama_deteccion_biopsia
description: "Reportes de biopsia de mama fechados por el reporte, con las marcas de resultado conocido y de resultado maligno."
config:
materialized: view
semantic_models:
- name: cama_deteccion_biopsia
description: "Breast biopsy reports with the flags of a known and of a malignant result: what the detection rate counts."
model: ref('cama_deteccion_biopsia')
defaults:
agg_time_dimension: fecha_reporte
entities:
- name: biopsia_deteccion
type: primary
expr: procedimiento_id
- name: paciente
type: foreign
expr: pac_id
dimensions:
- name: fecha_reporte
type: time
type_params:
time_granularity: day
- name: reporte_conocido_en
type: time
type_params:
time_granularity: day
- name: grado
type: categorical
- name: con_resultado
type: categorical
- name: maligno
type: categorical
measures:
- name: reportes_de_biopsia
description: "Distinct biopsy reports: each report counts, not each patient."
agg: count_distinct
expr: procedimiento_id
metrics:
- name: cama_tasa_deteccion_histopatologica_denominador
label: "Reportes de biopsia con resultado conocido"
type: simple
type_params:
measure: reportes_de_biopsia
filter: "{{ Dimension('biopsia_deteccion__con_resultado') }} = 1"
config:
meta:
poblaciones_fhir: [initial-population, denominator]
fechada_en: [fecha_reporte]
conocida_en: [reporte_conocido_en]
- name: cama_tasa_deteccion_histopatologica_numerador
label: "De ellos, con resultado maligno"
type: simple
type_params:
measure: reportes_de_biopsia
filter: "{{ Dimension('biopsia_deteccion__maligno') }} = 1"
config:
meta:
poblaciones_fhir: [numerator]
fechada_en: [fecha_reporte]
conocida_en: [reporte_conocido_en]
- name: cama_tasa_deteccion_histopatologica
# dbt wants labels unique in the project; the title on screen is `meta.titulo`.
label: "CaMa: tasa de detección histopatológica"
description: >-
De los reportes de biopsia de mama fechados en el periodo con un resultado conocido (benigno, carcinoma in situ o
carcinoma invasor), cuántos son malignos (carcinoma in situ o invasor). La unidad es el reporte de biopsia, no la
paciente; los reportes sin grado no entran. Es una proporción entre las biopsias con resultado: no es una tasa
sobre las mujeres tamizadas ni la proporción de mastografías de sospecha que tienen biopsia
(CAMA_CONFIRMACION_BIRADS45).
type: ratio
type_params:
numerator: cama_tasa_deteccion_histopatologica_numerador
denominator: cama_tasa_deteccion_histopatologica_denominador
config:
meta:
measure_url: cama/CAMA_TASA_DETECCION_HISTOPATOLOGICA
titulo: "Tasa de detección histopatológica"
version: 0.1.0
scoring: proportion
basis: examen
grupo: principal
contrato: C1
tipos_periodo: [semestre, mes]
@@ -51,17 +51,12 @@ metrics:
meta:
measure_url: cama/CAMA_BIOPSIAS
version: 0.2.0
ficha:
codigo: BIOPSIAS
para: Médico
unidad: biopsias
pregunta: ¿Cómo se distribuyen las biopsias reportadas por su grado histológico?
definicion: 'Biopsias reportadas en el semestre, por su grado histológico. «Sin dato»: el reporte no trae grado.'
scoring: composition
basis: examen
grupo: TOTAL
contrato: C2
tipos_periodo: [semestre, mes]
figuras: [fig_c2_donas, fig_c2_barras]
poblaciones_fhir: [measure-observation]
conocida_en: [reporte_conocido_en]
# One row per report: its grade.
@@ -71,3 +66,10 @@ metrics:
elige: ultimo_valido
valido: "{% raw %}{{ Dimension('biopsia__grado') }} is not null{% endraw %}"
orden: [fecha_reporte]
# The captions and colours of `cama.catalogos.biopsia` and `cama.catalogos.sin_dato`. A grade outside them
# (DESCONOCIDO) is published as it comes.
etiquetas:
BENIGNO: {etiqueta: "Benigno", color: "#9DBFE3"}
CARCINOMA_IN_SITU: {etiqueta: "Carcinoma in situ", color: "#D98E4A"}
CARCINOMA_INVASOR: {etiqueta: "Carcinoma invasor", color: "#7A2E0E"}
SIN_DATO: {etiqueta: "Sin dato", color: "#C9CDD2"}
@@ -0,0 +1,44 @@
-- One row per mammogram's report and each biopsy report it led to (one row with nulls when it led to none): the grain of
-- the measures that cross a mammogram's BI-RADS with the result of its biopsy. A biopsy counts for the mammogram that
-- led to it (mammogram -> biopsy order -> biopsy report), of the same patient. When each became known: the start of the
-- loads that wrote them. `biopsia_gravedad` orders a patient's biopsies from least to most severe by
-- `vars.cama.biopsia_gravedad`: 0 for a grade the catalog doesn't know, -1 for a report without one, null when the
-- mammogram led to none. `birads_gravedad` orders BI-RADS as `cama_tomas_mastografia` does.
{% set r = var('cama') %}
select
m.procedimiento_id,
m.fuente_id,
m.pac_id,
m.fecha_toma,
toma.inicio as toma_conocida_en,
m.fecha_reporte,
m.birads,
case
{%- for b in r['birads_gravedad'] %}
when m.birads = '{{ b }}' then {{ loop.index }}
{%- endfor %}
else 0
end as birads_gravedad,
reporte.inicio as reporte_conocido_en,
b.fuente_id as biopsia_fuente_id,
b.fecha_reporte as biopsia_fecha_reporte,
b.grado as biopsia_grado,
case
when b.procedimiento_id is null then null
when b.grado is null then -1
{%- for grado in r['biopsia_gravedad'] %}
when b.grado = '{{ grado }}' then {{ loop.index }}
{%- endfor %}
else 0
end as biopsia_gravedad,
biopsia.inicio as biopsia_conocida_en
from {{ ref('cama_mastografias') }} m
join {{ source('silver', 'carga') }} toma
on toma.carga_id = m.toma_carga_id
left join {{ source('silver', 'carga') }} reporte
on reporte.carga_id = m.reporte_carga_id and m.reporte_id is not null
left join {{ ref('cama_biopsias') }} b
on b.toma_id = m.procedimiento_id and b.pac_id = m.pac_id
left join {{ source('silver', 'carga') }} biopsia
on biopsia.carga_id = b.reporte_carga_id
@@ -0,0 +1,120 @@
version: 2
models:
- name: cama_resultado_biopsia
description: "Mastografías con su reporte y el grado de cada biopsia que originaron, con cuándo se supo de cada uno."
config:
materialized: view
semantic_models:
- name: cama_resultado_biopsia
description: "Mammograms with their BI-RADS and the grade of the biopsies they led to: what the histopathological result by BI-RADS counts over."
model: ref('cama_resultado_biopsia')
defaults:
agg_time_dimension: fecha_toma
entities:
- name: mastografia_biopsia
type: primary
expr: "procedimiento_id || '-' || coalesce(fecha_reporte, '') || '-' || coalesce(biopsia_fuente_id, '')"
- name: paciente
type: foreign
expr: pac_id
dimensions:
- name: fecha_toma
type: time
type_params:
time_granularity: day
- name: toma_conocida_en
type: time
type_params:
time_granularity: day
- name: fecha_reporte
type: time
type_params:
time_granularity: day
- name: reporte_conocido_en
type: time
type_params:
time_granularity: day
- name: biopsia_fecha_reporte
type: time
type_params:
time_granularity: day
- name: biopsia_conocida_en
type: time
type_params:
time_granularity: day
- name: birads
type: categorical
- name: birads_gravedad
type: categorical
- name: biopsia_grado
type: categorical
- name: biopsia_gravedad
type: categorical
- name: biopsia_fuente_id
type: categorical
- name: fuente_id
type: categorical
measures:
- name: pacientes_con_mastografia_birads
description: "Distinct patients: each counts once per period, however many mammograms or biopsies."
agg: count_distinct
expr: pac_id
metrics:
- name: cama_histopatologia_birads
label: "CaMa: resultado histopatológico por categoría BI-RADS"
description: >-
De las pacientes con una mastografía del periodo con BI-RADS 4, 5 o 6 reportado, cada una en la más grave de sus
mastografías (la misma regla de CAMA_BIRADS456_PACIENTE), cuántas tienen cada resultado en la biopsia que esa
mastografía originó y que se reportó a la fecha de corte (la más grave; entre iguales, la más reciente), por
categoría BI-RADS. «Sin biopsia reportada»: la mastografía no tiene biopsia reportada al corte; «Sin dato»: la
biopsia no trae grado. A la fecha de corte, sin un plazo máximo: una paciente «sin biopsia» puede pasar a un
resultado mientras lleguen reportes.
type: simple
type_params:
measure: pacientes_con_mastografia_birads
config:
meta:
measure_url: cama/CAMA_HISTOPATOLOGIA_BIRADS
titulo: "Resultado histopatológico por categoría BI-RADS"
version: 0.1.0
scoring: composition
basis: paciente
grupo: TOTAL
contrato: C2
tipos_periodo: [semestre, mes]
poblaciones_fhir: [measure-observation]
conocida_en: [toma_conocida_en]
parametros:
birads_4_a_6: cama.birads_4_a_6
categoria:
valor: biopsia_grado
sin_dato: SIN_DATO
elige: mas_grave
valido: "{% raw %}{{ Dimension('mastografia_biopsia__birads') }} is not null{% endraw %}"
fechada_en: [fecha_reporte]
conocida_en: [reporte_conocido_en]
orden: [birads_gravedad, fuente_id]
admite: "{% raw %}{{ Dimension('mastografia_biopsia__birads') }} in :birads_4_a_6{% endraw %}"
seguimiento:
existe: biopsia_fecha_reporte
fechada_en: [biopsia_fecha_reporte]
conocida_en: [biopsia_conocida_en]
orden: [biopsia_gravedad, biopsia_fecha_reporte, biopsia_fuente_id]
sin_seguimiento: SIN_BIOPSIA
# The captions and colours of cama.catalogos.biopsia and cama.catalogos.sin_dato; a grade outside them is
# published as it comes.
etiquetas:
BENIGNO: {etiqueta: "Benigno", color: "#9DBFE3"}
CARCINOMA_IN_SITU: {etiqueta: "Carcinoma in situ", color: "#D98E4A"}
CARCINOMA_INVASOR: {etiqueta: "Carcinoma invasor", color: "#7A2E0E"}
SIN_BIOPSIA: {etiqueta: "Sin biopsia reportada", color: "#C9CDD2"}
SIN_DATO: {etiqueta: "Sin dato", color: "#C9CDD2"}
estratos:
# The BI-RADS of the mammogram that gave the patient her place.
birads:
tipo: del_elegido
etiqueta: Categoría BI-RADS
valor: birads
@@ -0,0 +1,73 @@
-- One row per mammogram that has a report: the grain of the time from the mammogram's result to the diagnosis. No
-- period and no cut-off here: they're the question's. The diagnosis is the first diagnosing note of the patient dated
-- on or after the report (a `diagnostico` of the patient's timeline: a diagnosis ICD-10 of `cama.cie_diagnostico`
-- written by a specialty of `cama.especialidades_diagnostico`) and within the horizon of the report. It is a note of
-- the patient, not a link to this mammogram's episode: the notes carry no episode. It is not the date of a biopsy.
-- Days are differences of `dim_fecha.dia_num`. When the report and the note became known: the start of the loads that
-- wrote them. A breast cancer note (`antecedente`) before the mammogram leaves it out, as in the time from the
-- mammogram to the diagnosis.
{% set r = var('cama') %}
-- One observation per mammogram: its earliest dated report, ties by the report's platform identity.
-- Later corrections do not move the observation to another period or duplicate it.
with ordenadas as (
select procedimiento_id, fuente_id, pac_id, fecha_toma, fecha_reporte, reporte_carga_id,
row_number() over (partition by procedimiento_id order by fecha_reporte, reporte_id, reporte_carga_id) as lugar
from {{ ref('cama_mastografias') }}
where reporte_id is not null and fecha_reporte is not null
),
reportada as (
select procedimiento_id, fuente_id, pac_id, fecha_toma, fecha_reporte, reporte_carga_id
from ordenadas where lugar = 1
),
resuelve as (
select m.procedimiento_id, min(l.fecha) as fecha_diagnostico
from reportada m
join {{ ref('cama_linea_de_tiempo') }} l
on l.pac_id = m.pac_id and l.tipo = 'diagnostico' and l.fecha >= m.fecha_reporte
join {{ source('silver', 'dim_fecha') }} dl on dl.fecha = l.fecha
join {{ source('silver', 'dim_fecha') }} dr on dr.fecha = m.fecha_reporte
where dl.dia_num - dr.dia_num < {{ r['horizonte_toma_diagnostico_dias'] }}
group by m.procedimiento_id
),
diagnostico as (
select r.procedimiento_id, r.fecha_diagnostico, min(l.conocida_en) as diagnostico_conocido_en
from resuelve r
join reportada m on m.procedimiento_id = r.procedimiento_id
join {{ ref('cama_linea_de_tiempo') }} l
on l.pac_id = m.pac_id and l.tipo = 'diagnostico' and l.fecha = r.fecha_diagnostico
group by r.procedimiento_id, r.fecha_diagnostico
),
primer_antecedente as (
select pac_id, min(fecha) as fecha
from {{ ref('cama_linea_de_tiempo') }}
where tipo = 'antecedente'
group by pac_id
)
select
m.procedimiento_id,
m.fuente_id,
m.pac_id,
m.fecha_toma,
m.fecha_reporte,
reporte.inicio as reporte_conocido_en,
dia_reporte.dia_num as reporte_dia,
dx.fecha_diagnostico,
dx.diagnostico_conocido_en,
dia_diagnostico.dia_num - dia_reporte.dia_num as dias_reporte_diagnostico,
case when antecedente.fecha < m.fecha_toma then 1 else 0 end as con_antecedente
from reportada m
join {{ source('silver', 'carga') }} reporte
on reporte.carga_id = m.reporte_carga_id
join {{ source('silver', 'dim_fecha') }} dia_reporte
on dia_reporte.fecha = m.fecha_reporte
left join diagnostico dx
on dx.procedimiento_id = m.procedimiento_id
left join {{ source('silver', 'dim_fecha') }} dia_diagnostico
on dia_diagnostico.fecha = dx.fecha_diagnostico
left join primer_antecedente antecedente
on antecedente.pac_id = m.pac_id
@@ -0,0 +1,87 @@
version: 2
models:
- name: cama_resultado_diagnostico
description: "Mastografías con reporte y la primera nota diagnóstica de la paciente a partir de ese reporte, con sus fechas y su conocimiento."
config:
materialized: view
semantic_models:
- name: cama_resultado_diagnostico
description: "Mammograms with a report and the first diagnosing note on or after it: what the time from result to diagnosis counts."
model: ref('cama_resultado_diagnostico')
defaults:
agg_time_dimension: fecha_reporte
entities:
- name: resultado_diagnostico
type: primary
expr: procedimiento_id
- name: paciente
type: foreign
expr: pac_id
dimensions:
- name: fecha_reporte
type: time
type_params:
time_granularity: day
- name: reporte_conocido_en
type: time
type_params:
time_granularity: day
- name: fecha_diagnostico
type: time
type_params:
time_granularity: day
- name: diagnostico_conocido_en
type: time
type_params:
time_granularity: day
- name: reporte_dia
type: categorical
- name: dias_reporte_diagnostico
type: categorical
- name: con_antecedente
type: categorical
- name: fuente_id
type: categorical
measures:
- name: mastografias_con_reporte
description: "Distinct mammograms by platform procedure identity, through their earliest report."
agg: count_distinct
expr: procedimiento_id
metrics:
- name: cama_dias_resultado_diagnostico
label: "CaMa: tiempo de resultado a diagnóstico"
description: >-
Días naturales del reporte de cada mastografía fechado en el periodo a la primera nota médica diagnóstica de la
paciente a partir de ese reporte: un diagnóstico CIE-10 de la lista (normal, benigno, lesión o cáncer), escrito
por una de las especialidades que diagnostican, dentro del horizonte y a la fecha de corte. La nota es de la
paciente, no está ligada a la mastografía (las notas no traen episodio) y no es la fecha de la biopsia. Las
mastografías sin nota en el horizonte no se miden. Se excluyen las de pacientes con un diagnóstico de cáncer de
mama anterior a la toma.
type: simple
type_params:
measure: mastografias_con_reporte
filter: "{{ Dimension('resultado_diagnostico__con_antecedente') }} = 0"
config:
meta:
measure_url: cama/CAMA_DIAS_RESULTADO_DIAGNOSTICO
titulo: "Tiempo de resultado a diagnóstico"
version: 0.1.0
scoring: continuous-variable
basis: examen
grupo: TOTAL
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [reporte_conocido_en]
observacion:
valor: dias_reporte_diagnostico
fechada_en: [fecha_diagnostico]
conocida_en: [diagnostico_conocido_en]
horizonte:
dias: "{{ var('cama')['horizonte_toma_diagnostico_dias'] }}"
dia_inicio: reporte_dia
@@ -83,18 +83,12 @@ metrics:
meta: &birads_por_paciente
measure_url: cama/CAMA_BIRADS
version: 0.2.0
ficha:
codigo: BIRADS
para: Médico
unidad: pacientes
pregunta: ¿Cómo se distribuyen las pacientes por categoría de BI-RADS?
definicion: 'Pacientes con mastografía tomada en el semestre, por la categoría de BI-RADS más grave de sus mastografías.
«Sin dato»: ninguna tiene reporte con BI-RADS.'
scoring: composition
basis: paciente
grupo: TOTAL
contrato: C2
tipos_periodo: [semestre, mes]
figuras: [fig_c2_donas, fig_c2_barras]
poblaciones_fhir: [measure-observation]
conocida_en: [toma_conocida_en]
# Each patient's most severe BI-RADS among her mammograms of the period reported by the cut-off; one without a
@@ -107,6 +101,19 @@ metrics:
fechada_en: [fecha_reporte]
conocida_en: [reporte_conocido_en]
orden: [birads_gravedad, fuente_id]
# The captions and colours of `cama.catalogos.birads` and `cama.catalogos.sin_dato`, in their order. A BI-RADS 4
# without subcategory is no declared category: a report that counts one publishes it as it comes.
etiquetas: &etiquetas_birads
B0: {etiqueta: "BI-RADS 0", color: "#8A9199"}
B1: {etiqueta: "BI-RADS 1", color: "#9DBFE3"}
B2: {etiqueta: "BI-RADS 2", color: "#2F6DB3"}
B3: {etiqueta: "BI-RADS 3", color: "#E8C28E"}
B4A: {etiqueta: "BI-RADS 4A", color: "#E0A060"}
B4B: {etiqueta: "BI-RADS 4B", color: "#CF7D3C"}
B4C: {etiqueta: "BI-RADS 4C", color: "#C26A2B"}
B5: {etiqueta: "BI-RADS 5", color: "#B55A1F"}
B6: {etiqueta: "BI-RADS 6", color: "#7A2E0E"}
SIN_DATO: {etiqueta: "Sin dato", color: "#C9CDD2"}
- name: cama_birads_456_paciente
label: "Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6"
description: >-
@@ -119,12 +126,6 @@ metrics:
meta:
<<: *birads_por_paciente
measure_url: cama/CAMA_BIRADS456_PACIENTE
ficha:
codigo: BIRADS456P
para: Médico
unidad: pacientes
pregunta: ¿Cómo se distribuyen las pacientes por categoría de BI-RADS 4, 5 y 6?
definicion: Pacientes cuyo BI-RADS más grave entre sus mastografías del semestre es 4, 5 o 6.
parametros:
birads_4_a_6: cama.birads_4_a_6
categoria:
@@ -137,6 +138,13 @@ metrics:
orden: [birads_gravedad, fuente_id]
# After choosing the most severe: a patient with B6 and B4 counts in B6.
admite: "{% raw %}{{ Dimension('mastografia__birads') }} in :birads_4_a_6{% endraw %}"
# `cama.catalogos.birads_4_a_6`: what `admite` lets through, so no «Sin dato».
etiquetas: &etiquetas_birads_4_a_6
B4A: {etiqueta: "BI-RADS 4A", color: "#E0A060"}
B4B: {etiqueta: "BI-RADS 4B", color: "#CF7D3C"}
B4C: {etiqueta: "BI-RADS 4C", color: "#C26A2B"}
B5: {etiqueta: "BI-RADS 5", color: "#B55A1F"}
B6: {etiqueta: "BI-RADS 6", color: "#7A2E0E"}
- name: cama_birads_456_mastografia
label: "Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6"
description: "Cuántas mastografías tomadas en el periodo tienen BI-RADS 4, 5 o 6, cada una con su categoría."
@@ -148,17 +156,12 @@ metrics:
meta:
measure_url: cama/CAMA_BIRADS456_MASTOGRAFIA
version: 0.2.0
ficha:
codigo: BIRADS456M
para: Médico
unidad: mastografías
pregunta: ¿Cómo se distribuyen las mastografías por categoría de BI-RADS 4, 5 y 6?
definicion: Mastografías tomadas en el semestre con BI-RADS 4, 5 o 6, cada una con su categoría.
scoring: composition
basis: examen
grupo: TOTAL
contrato: C2
tipos_periodo: [semestre, mes]
figuras: [fig_c2_donas, fig_c2_barras]
poblaciones_fhir: [measure-observation]
conocida_en: [toma_conocida_en]
parametros:
@@ -171,6 +174,7 @@ metrics:
fechada_en: [fecha_reporte]
conocida_en: [reporte_conocido_en]
orden: [birads_gravedad]
etiquetas: *etiquetas_birads_4_a_6
- name: cama_eu38a
label: "Días de la toma de la mastografía a su resultado"
description: >-
@@ -184,20 +188,13 @@ metrics:
meta:
measure_url: cama/CAMA_EU38A
version: 0.2.1
ficha:
codigo: EU38A
para: Médico
unidad: mastografías
pregunta: ¿Cuántos días pasan de la toma de la mastografía a su resultado?
definicion: Días naturales de la toma de cada mastografía del semestre a su resultado, a la fecha de corte.
nota: Días de la toma al resultado. La caja va del primer al tercer cuartil y la línea es la mediana; no se dibuja
cada mastografía. No cuenta las que siguen dentro del horizonte sin resultado.
scoring: continuous-variable
basis: examen
grupo: TOTAL
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [toma_conocida_en]
parametros:
@@ -223,17 +220,6 @@ metrics:
config:
meta:
measure_url: cama/CAMA_DIAS_TOMA_DIAGNOSTICO
ficha:
codigo: DIAS_DX
para: Médico
unidad: mastografías
pregunta: ¿Cuántos días pasan de la toma de la mastografía al diagnóstico?
definicion: Días naturales de la toma de cada mastografía del semestre a la primera nota médica posterior con
un diagnóstico CIE-10 que la resuelve (normal, benigno, lesión o cáncer), de una especialidad que diagnostica,
dentro del horizonte y a la fecha de corte. No entran las de pacientes con un diagnóstico de cáncer de mama
anterior a la toma.
nota: Días de la toma al diagnóstico. La caja va del primer al tercer cuartil y la línea es la mediana. No cuenta
las que siguen dentro del horizonte sin diagnóstico; las que lo pasaron sin diagnóstico cuentan en los excluidos.
titulo: "Tiempo de tamizaje a diagnóstico"
version: 0.2.2
scoring: continuous-variable
@@ -242,6 +228,7 @@ metrics:
contrato: C3r
improvement_notation: decrease
tipos_periodo: [semestre, mes]
figuras: [fig_c3r_caja]
poblaciones_fhir: [initial-population]
conocida_en: [toma_conocida_en]
observacion:
@@ -0,0 +1,7 @@
version: 2
# Views the WebApi reads, not measures: the cycle creates them with the event models (`lee_la_webapi`).
models:
- name: cama_cohorte_birads
description: "Mastografías con BI-RADS reportado y los reportes de biopsia que originaron: los candidatos de la cohorte BI-RADS de la lista de seguimiento."
config: {materialized: view, meta: {lee_la_webapi: true}}
@@ -0,0 +1,27 @@
-- The candidates of the BI-RADS cohort for the follow-up list: one row per mammogram with a reported BI-RADS and
-- each biopsy report that mammogram led to (one row with nulls when it led to none). The cohort itself depends on the
-- cut-off asked for (each patient's latest mammogram reported by it, kept when its BI-RADS is 4 to 6), and a view takes
-- no parameter, so the WebApi picks the rows by date as it does for the other follow-up lists. Nothing here is
-- derived from a rule that isn't in silver: dates and codes are the source's.
select
m.pac_id,
m.procedimiento_id,
m.fuente_id,
m.fecha_toma,
m.reporte_id,
m.fecha_reporte,
m.birads,
p.fecha_nacimiento,
b.procedimiento_id as biopsia_id,
b.fuente_id as biopsia_fuente_id,
b.fecha_reporte as biopsia_fecha_reporte,
b.grado as biopsia_grado
from {{ ref('cama_mastografias') }} m
join {{ source('silver', 'persona') }} p
on p.pac_id = m.pac_id
left join {{ ref('cama_biopsias') }} b
on b.toma_id = m.procedimiento_id and b.pac_id = m.pac_id
where m.birads is not null
and m.fecha_toma is not null
and m.fecha_reporte is not null
@@ -1,8 +1,7 @@
{# Each patient's stratifiers for the analysis, as timeline facts (`pac_id`, `tipo`, `fecha`, `conocida_en`): what a
measure's `linea_de_tiempo_*` strata ask about. Derived from cama_linea_de_tiempo's lines read from reports, by the
rules in `vars.cama.estratos`: the clinical stage's group and early or advanced stage (from a note), the surrogate
molecular subtype (from one pathology report's receptors, HER2 and Ki-67 together) and the lesion's T (from a
mammography report). A fact is dated and known as the lines it comes from. A view, like the timeline. #}
rules in `vars.cama.estratos`: the clinical stage's group and early or advanced stage (from a note) and the lesion's
T (from a mammography report). A fact is dated and known as the lines it comes from. A view, like the timeline. #}
{{ config(materialized = 'view') }}
{%- set e = var('cama')['estratos'] -%}
@@ -28,37 +27,6 @@ estadio as (
where tipo = 'estadio_clinico'
),
reporte as (
select
pac_id, fecha, fuente_tabla, fuente_id,
max(conocida_en) as conocida_en,
max(case when tipo = 'receptor_estrogeno' then valor_codigo end) as re,
max(case when tipo = 'receptor_progesterona' then valor_codigo end) as rp,
max(case when tipo = 'receptor_progesterona_pct' then valor_numerico end) as rp_pct,
max(case when tipo = 'her2' then valor_codigo end) as her2,
max(case when tipo = 'ki67_pct' then valor_numerico end) as ki67
from linea
where tipo in ('receptor_estrogeno', 'receptor_progesterona', 'receptor_progesterona_pct', 'her2', 'ki67_pct')
group by pac_id, fecha, fuente_tabla, fuente_id
),
subtipo as (
select
pac_id, fecha, conocida_en,
case
when her2 in {{ sql_list(e['her2_positivo']) }} then 'subtipo_her2'
when her2 not in {{ sql_list(e['her2_negativo']) }} or her2 is null then null
when re = 'NEGATIVO' and rp = 'NEGATIVO' then 'subtipo_triple_negativo'
when re = 'POSITIVO' or rp = 'POSITIVO' then
case
when ki67 is null then null
when ki67 < {{ e['ki67_corte'] }} and rp = 'POSITIVO'
and (rp_pct is null or rp_pct >= {{ e['rp_corte'] }}) then 'subtipo_luminal_a'
else 'subtipo_luminal_b'
end
end as subtipo
from reporte
),
tamano as (
select
@@ -77,6 +45,4 @@ select pac_id, estadio as tipo, fecha, conocida_en from estadio where estadio is
union all
select pac_id, etapa as tipo, fecha, conocida_en from estadio where etapa is not null
union all
select pac_id, subtipo as tipo, fecha, conocida_en from subtipo where subtipo is not null
union all
select pac_id, t as tipo, fecha, conocida_en from tamano
@@ -1,8 +1,26 @@
{# A view, not ephemeral like the other silver models: cohorts query it. Its sources: cama_linea_de_tiempo.yml;
the procedures silver doesn't hold but its notes imply (diagnosis, antecedent): cama_procedimientos_inferidos. #}
the procedures silver doesn't hold but its notes imply (diagnosis, antecedent) and the clinical scenario of each
patient: cama_procedimientos_inferidos; her birth and death, from `persona`. #}
{{ config(materialized = 'view') }}
{{ linea_de_tiempo(config.get('meta')['fuentes']) }}
union all
select pac_id, fecha, conocida_en, clase, tipo, codigo, valor_codigo, valor_numerico, fuente_tabla, fuente_id
from {{ ref('cama_procedimientos_inferidos') }}
{#- `persona` holds staging's current value, with no load of its own: it's known as of the latest load. #}
{%- for tipo, columna in [('nacimiento', 'fecha_nacimiento'), ('defuncion', 'fecha_defuncion')] %}
union all
select
persona.pac_id as pac_id,
persona.{{ columna }} as fecha,
(select max(carga.inicio) from {{ source('silver', 'carga') }} carga) as conocida_en,
{{ as_text("'persona'") }} as clase,
{{ as_text("'" ~ tipo ~ "'") }} as tipo,
{{ as_text("'" ~ tipo ~ "'") }} as codigo,
{{ as_text('null') }} as valor_codigo,
cast(null as {{ dbt.type_float() }}) as valor_numerico,
{{ as_text("'persona'") }} as fuente_tabla,
{{ as_text('persona.pac_id') }} as fuente_id
from {{ source('silver', 'persona') }} persona
where persona.{{ columna }} is not null
{%- endfor %}
@@ -29,5 +29,28 @@ models:
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.her2", clase_de_linea: "medicion", tipo: "her2"}
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.ki67_pct", clase_de_linea: "medicion", tipo: "ki67_pct", valor: "numerico"}
- {estudio_id: "nota_medica", clase: "encuentro", resultado_id: "nota_medica.estadio_clinico", clase_de_linea: "medicion", tipo: "estadio_clinico"}
# The surgical report and staging: the covariates of the survival cohort (`cama/cohorte_supervivencia`).
- {estudio_id: "biopsia", clase: "toma", resultado_id: "biopsia.lateralidad", clase_de_linea: "medicion", tipo: "lateralidad"}
- {estudio_id: "biopsia", clase: "toma", resultado_id: "biopsia.localizacion", clase_de_linea: "medicion", tipo: "localizacion"}
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.her2_fish", clase_de_linea: "medicion", tipo: "her2_fish"}
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.tamano_tumor_mm", clase_de_linea: "medicion", tipo: "tamano_tumor_mm", valor: "numerico"}
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.invasion_linfovascular", clase_de_linea: "medicion", tipo: "invasion_linfovascular"}
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.ganglios_positivos", clase_de_linea: "medicion", tipo: "ganglios_positivos", valor: "numerico"}
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.pt", clase_de_linea: "medicion", tipo: "pt"}
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.pn", clase_de_linea: "medicion", tipo: "pn"}
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.margenes", clase_de_linea: "medicion", tipo: "margenes"}
- {estudio_id: "biopsia", clase: "reporte", resultado_id: "biopsia.multifocalidad", clase_de_linea: "medicion", tipo: "multifocalidad"}
- {estudio_id: "nota_medica", clase: "encuentro", resultado_id: "nota_medica.m", clase_de_linea: "medicion", tipo: "metastasis"}
# A mammogram's findings, each a part dated by its report.
- {estudio_id: "mastografia", clase: "parte", resultado_id: "mastografia.tipo_hallazgo", clase_de_linea: "medicion", tipo: "tipo_hallazgo"}
- {estudio_id: "mastografia", clase: "parte", resultado_id: "mastografia.margen_masa", clase_de_linea: "medicion", tipo: "margen_masa"}
- {estudio_id: "prueba_genetica", clase: "reporte", resultado_id: "prueba_genetica.brca1", clase_de_linea: "medicion", tipo: "brca1"}
- {estudio_id: "prueba_genetica", clase: "reporte", resultado_id: "prueba_genetica.brca2", clase_de_linea: "medicion", tipo: "brca2"}
- {estudio_id: "sociodemografico", clase: "parte", resultado_id: "sociodemografico.estado_civil", clase_de_linea: "medicion", tipo: "estado_civil"}
# Treatment, when it was done: one row per course (a surgery per breast), its value the kind or the intent.
- {estudio_id: "cirugia", clase: "encuentro", resultado_id: "cirugia.tipo_cirugia", clase_de_linea: "procedimiento", tipo: "cirugia"}
- {estudio_id: "cirugia", clase: "encuentro", resultado_id: "cirugia.lateralidad", clase_de_linea: "medicion", tipo: "cirugia_lateralidad"}
- {estudio_id: "radioterapia", clase: "encuentro", resultado_id: "radioterapia.intencion", clase_de_linea: "procedimiento", tipo: "radioterapia"}
- {estudio_id: "quimioterapia", clase: "encuentro", resultado_id: "quimioterapia.intencion", clase_de_linea: "procedimiento", tipo: "quimioterapia"}
- {estudio_id: null, clase: "orden", resultado_id: null, clase_de_linea: "orden", tipo: "orden", columna: "codigo_fuente"}
- {estudio_id: "nota_medica", clase: "encuentro", resultado_id: "nota_medica.diagnostico", clase_de_linea: "diagnostico", tipo: "nota_medica"}

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