Compare commits

..

37 Commits

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-22 00:23:42 -06:00
48 changed files with 2098 additions and 117 deletions
+72
View File
@@ -49,6 +49,78 @@ class BiopsiaMama(CaMaModel, table=True):
default=None,
sa_column=sa.Column(sa.Text),
)
bx_tipo_histologico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_grado_nottingham: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_receptor_estrogeno: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_receptor_estrogeno_pct: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
bx_receptor_progesterona: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_receptor_progesterona_pct: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
bx_her2: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_her2_fish: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_ki67_pct: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
bx_tamano_tumor_mm: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
bx_ganglios_positivos: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
bx_invasion_linfovascular: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_multifocalidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_margenes: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_pt: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_pn: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_lateralidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_localizacion: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
bx_pdf_blob: Optional[bytes] = Field(
default=None,
sa_column=sa.Column(FileBlob),
+12
View File
@@ -58,5 +58,17 @@ class Mastografia(CaMaModel, table=True):
sa_column=sa.Column(sa.Text),
description="enlace o referencia a la interpretación del radiólogo; formato pendiente",
)
mast_densidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
mast_margen_masa: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
mast_tipo_hallazgo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
+4
View File
@@ -5,6 +5,8 @@ from core.cama.biopsia_mama.model import BiopsiaMama
from core.cama.nota_medica.model import NotaMedica
from core.cama.biometria_hematica.model import BiometriaHematica
from core.cama.episodio_clinico.model import EpisodioClinico
from core.cama.tratamiento_mama.model import TratamientoMama
from core.cama.seguimiento_mama.model import SeguimientoMama
__all__ = [
"Paciente",
@@ -14,4 +16,6 @@ __all__ = [
"NotaMedica",
"BiometriaHematica",
"EpisodioClinico",
"TratamientoMama",
"SeguimientoMama",
]
+8
View File
@@ -69,6 +69,14 @@ class NotaMedica(CaMaModel, table=True):
default=None,
sa_column=sa.Column(sa.Text),
)
nm_estadio_clinico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_metastasis: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
nm_tratamiento_texto: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
+48
View File
@@ -33,6 +33,54 @@ class Paciente(CaMaModel, table=True):
default=None,
sa_column=sa.Column(sa.Date),
)
pac_estado_civil: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_raza: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_brca1: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_brca2: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_estado_menopausico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_pam50: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_subtipo_clinico: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_cluster_integrativo: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_celularidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_carga_mutacional: Optional[float] = Field(
default=None,
sa_column=sa.Column(sa.Float),
)
pac_ki67_categoria: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_fuente: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
pac_codigo_postal: Optional[str] = Field(
default=None,
sa_column=sa.Column(
+39
View File
@@ -0,0 +1,39 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import HOSPITAL_ID_LENGTH
class SeguimientoMama(CaMaModel, table=True):
"""
Un hecho del seguimiento de la paciente: una recaída o el último contacto, con su fecha.
`seg_tipo` es el estudio del catálogo (`recurrencia`, `ultimo_contacto`); `seg_detalle`, su resultado:
el sitio de la recaída.
"""
seg_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="rellenado por el loader via lookup en paciente.pac_id_hospital",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
)
seg_tipo: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
)
seg_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
seg_detalle: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
+43
View File
@@ -0,0 +1,43 @@
from datetime import date
from typing import Optional
import sqlalchemy as sa
from sqlmodel import Field
from core.cama.base import CaMaModel
from core.columns import HOSPITAL_ID_LENGTH
class TratamientoMama(CaMaModel, table=True):
"""
Un tratamiento del cáncer de mama: una cirugía, un curso de radioterapia o uno de quimioterapia, con su fecha.
`trat_tipo` es el estudio del catálogo (`cirugia`, `radioterapia`, `quimioterapia`); `trat_detalle`, su resultado:
el tipo de cirugía o la intención del curso.
"""
trat_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, primary_key=True, autoincrement=True),
)
pac_id: Optional[int] = Field(
default=None,
sa_column=sa.Column(sa.Integer, index=True),
description="rellenado por el loader via lookup en paciente.pac_id_hospital",
)
pac_id_hospital: str = Field(
sa_column=sa.Column(sa.String(HOSPITAL_ID_LENGTH), index=True, nullable=False),
)
trat_tipo: str = Field(
sa_column=sa.Column(sa.Text, nullable=False),
)
trat_fecha: Optional[date] = Field(
default=None,
sa_column=sa.Column(sa.Date),
)
trat_detalle: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
trat_lateralidad: Optional[str] = Field(
default=None,
sa_column=sa.Column(sa.Text),
)
+152 -8
View File
@@ -118,7 +118,6 @@ etiquetas_fuente = ["Tamaño de la lesión", "Tamaño del nódulo", "Diámetro m
[mastografia.resultados.localizacion]
etiqueta = "Localización en la mama"
tipo_valor = "codigo"
sistema = "CIE-10"
provisional = true
etiquetas_fuente = ["Localización", "Cuadrante", "Sitio"]
valores = [
@@ -170,7 +169,6 @@ valores = [
[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 = [
@@ -208,7 +206,6 @@ valores = [
[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
@@ -415,7 +412,6 @@ etiquetas_fuente = ["Ganglios positivos", "Ganglios con metástasis", "Ganglios
[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 = [
@@ -439,7 +435,6 @@ valores = [
[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 = [
@@ -460,6 +455,7 @@ 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"] },
{ valor = "SIN_CIRUGIA", etiqueta = "Sin cirugía" },
]
[biopsia.resultados.multicentricidad]
@@ -536,7 +532,6 @@ valores = [
[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 = [
@@ -560,7 +555,6 @@ valores = [
[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 = [
@@ -574,7 +568,6 @@ valores = [
[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 = [
@@ -709,6 +702,34 @@ valores = [
{ valor = "VIUDA", etiqueta = "Viuda", alias = ["Viuda", "Viudo", "V"] },
]
[sociodemografico.resultados.raza]
etiqueta = "Raza"
tipo_valor = "codigo"
etiquetas_fuente = ["Raza"]
valores = [
{ valor = "BLANCA", etiqueta = "Blanca", alias = ["Blanca", "Blanco"] },
{ valor = "NEGRA", etiqueta = "Negra", alias = ["Negra", "Negro"] },
{ valor = "OTRA", etiqueta = "Otra (indígena americana, asiática o de las islas del Pacífico)", alias = ["Otra", "Indígena", "Asiática"] },
]
[sociodemografico.resultados.estado_menopausico]
etiqueta = "Estado menopáusico"
tipo_valor = "codigo"
valores = [
{ valor = "PREMENOPAUSIA", etiqueta = "Premenopausia" },
{ valor = "POSMENOPAUSIA", etiqueta = "Posmenopausia" },
]
[sociodemografico.resultados.fuente]
etiqueta = "Fuente del registro"
tipo_valor = "codigo"
valores = [
{ valor = "METABRIC", etiqueta = "METABRIC" },
{ valor = "SCANB", etiqueta = "SCAN-B" },
{ valor = "SEER", etiqueta = "SEER" },
{ valor = "ISSSTELEON", etiqueta = "ISSSTELEON" },
]
# 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]
@@ -765,6 +786,9 @@ valores = [
{ valor = "SEGMENTECTOMIA", etiqueta = "Segmentectomía o cuadrantectomía" },
{ valor = "MASTECTOMIA_TOTAL", etiqueta = "Mastectomía total" },
{ valor = "MASTECTOMIA_RADICAL_MODIFICADA", etiqueta = "Mastectomía radical modificada" },
{ valor = "SIN_CIRUGIA", etiqueta = "Sin cirugía" },
{ valor = "DESTRUCCION_LOCAL", etiqueta = "Destrucción local" },
{ valor = "CIRUGIA_NO_ESPECIFICADA", etiqueta = "Cirugía sin especificar" },
]
[cirugia.resultados.cirugia_axilar]
@@ -786,6 +810,7 @@ valores = [
{ valor = "NEOADYUVANTE", etiqueta = "Neoadyuvante" },
{ valor = "ADYUVANTE", etiqueta = "Adyuvante" },
{ valor = "PALIATIVA", etiqueta = "Paliativa" },
{ valor = "NINGUNA", etiqueta = "Sin tratamiento" },
]
[radioterapia.resultados.lateralidad]
@@ -812,6 +837,7 @@ valores = [
{ valor = "NEOADYUVANTE", etiqueta = "Neoadyuvante" },
{ valor = "ADYUVANTE", etiqueta = "Adyuvante" },
{ valor = "PALIATIVA", etiqueta = "Paliativa" },
{ valor = "NINGUNA", etiqueta = "Sin tratamiento" },
]
[quimioterapia.resultados.fecha_fin]
@@ -864,3 +890,121 @@ valores = [
# 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)
# Molecular and clinical profile of the tumour as the registry gives it.
[perfil_molecular]
etiqueta = "Perfil molecular y clínico del tumor"
[perfil_molecular.resultados.pam50]
etiqueta = "Subtipo PAM50"
tipo_valor = "codigo"
valores = [
{ valor = "LUMA", etiqueta = "Luminal A" },
{ valor = "LUMB", etiqueta = "Luminal B" },
{ valor = "HER2", etiqueta = "HER2-enriquecido" },
{ valor = "BASAL", etiqueta = "Basal" },
{ valor = "CLAUDIN_LOW", etiqueta = "Claudin-low" },
{ valor = "NORMAL", etiqueta = "Normal-like" },
{ valor = "NC", etiqueta = "No clasificado" },
]
[perfil_molecular.resultados.subtipo_clinico]
etiqueta = "Subtipo clínico"
tipo_valor = "codigo"
valores = [
{ valor = "LUMINAL_A", etiqueta = "Luminal A" },
{ valor = "LUMINAL_B_HER2_NEG", etiqueta = "Luminal B HER2 negativo" },
{ valor = "LUMINAL_B_HER2_POS", etiqueta = "Luminal B HER2 positivo" },
{ valor = "BASAL_LIKE", etiqueta = "Basal-like" },
{ valor = "NO_LUMINAL_HER2_POS", etiqueta = "No luminal HER2 positivo" },
{ valor = "LUMINAL_NO_DETERMINADO", etiqueta = "Luminal sin determinar" },
{ valor = "RE_NEG_NO_DETERMINADO", etiqueta = "RE negativo sin determinar" },
]
[perfil_molecular.resultados.cluster_integrativo]
etiqueta = "Clúster integrativo"
tipo_valor = "codigo"
valores = [
{ valor = "IC1", etiqueta = "Clúster 1" },
{ valor = "IC2", etiqueta = "Clúster 2" },
{ valor = "IC3", etiqueta = "Clúster 3" },
{ valor = "IC4ERP", etiqueta = "Clúster 4 RE+" },
{ valor = "IC4ERN", etiqueta = "Clúster 4 RE-" },
{ valor = "IC5", etiqueta = "Clúster 5" },
{ valor = "IC6", etiqueta = "Clúster 6" },
{ valor = "IC7", etiqueta = "Clúster 7" },
{ valor = "IC8", etiqueta = "Clúster 8" },
{ valor = "IC9", etiqueta = "Clúster 9" },
{ valor = "IC10", etiqueta = "Clúster 10" },
]
[perfil_molecular.resultados.celularidad]
etiqueta = "Celularidad"
tipo_valor = "codigo"
valores = [
{ valor = "ALTA", etiqueta = "Alta" },
{ valor = "MODERADA", etiqueta = "Moderada" },
{ valor = "BAJA", etiqueta = "Baja" },
]
[perfil_molecular.resultados.carga_mutacional]
etiqueta = "Carga mutacional (número de mutaciones)"
tipo_valor = "numero"
[perfil_molecular.resultados.ki67_categoria]
etiqueta = "Ki-67 por categoría"
tipo_valor = "codigo"
valores = [
{ valor = "BAJO", etiqueta = "Bajo" },
{ valor = "INTERMEDIO", etiqueta = "Intermedio" },
{ valor = "ALTO", etiqueta = "Alto" },
]
[hormonoterapia]
etiqueta = "Hormonoterapia"
[hormonoterapia.resultados.intencion]
etiqueta = "Intención"
tipo_valor = "codigo"
valores = [
{ valor = "NEOADYUVANTE", etiqueta = "Neoadyuvante" },
{ valor = "ADYUVANTE", etiqueta = "Adyuvante" },
{ valor = "PALIATIVA", etiqueta = "Paliativa" },
{ valor = "NINGUNA", etiqueta = "Sin tratamiento" },
]
[anti_her2]
etiqueta = "Tratamiento anti-HER2"
[anti_her2.resultados.intencion]
etiqueta = "Intención"
tipo_valor = "codigo"
valores = [
{ valor = "NEOADYUVANTE", etiqueta = "Neoadyuvante" },
{ valor = "ADYUVANTE", etiqueta = "Adyuvante" },
{ valor = "PALIATIVA", etiqueta = "Paliativa" },
{ valor = "NINGUNA", etiqueta = "Sin tratamiento" },
]
[recurrencia]
etiqueta = "Recaída"
[recurrencia.resultados.sitio]
etiqueta = "Sitio de la recaída"
tipo_valor = "codigo"
valores = [
{ valor = "LOCAL", etiqueta = "Local" },
{ valor = "REGIONAL", etiqueta = "Regional" },
{ valor = "A_DISTANCIA", etiqueta = "A distancia" },
{ valor = "NO_ESPECIFICADO", etiqueta = "Sin especificar" },
]
[ultimo_contacto]
etiqueta = "Último contacto"
[ultimo_contacto.resultados.estado]
etiqueta = "Estado en el último contacto"
tipo_valor = "codigo"
valores = [
{ valor = "VIVA", etiqueta = "Viva" },
]
+43
View File
@@ -26,6 +26,37 @@ ADOS2_ITEMS = (
)
# The ADOS-2 algorithm items by what they measure: one code per item, the same in every module, with its label,
# domain and its column code in each module that scores it. A column code is not one item across modules (`sa_b5` is
# gaze integration in the Toddler module, shared enjoyment in Module 1, showing in Module 2), so the association
# model's outcomes (`relacion_ados2.rel_resultado`) carry these codes, or `CSS` for the total severity score.
ADOS2_ITEM_MEANINGS = {
"ados2_item_01": ("Vocalización espontánea dirigida a otros", "SA", {"TODDLER": "sa_a2", "MODULO_1": "sa_a2"}),
"ados2_item_02": ("Señalar", "SA", {"TODDLER": "sa_a7", "MODULO_1": "sa_a7", "MODULO_2": "sa_a6"}),
"ados2_item_03": ("Gestos", "SA", {"TODDLER": "sa_a8", "MODULO_1": "sa_a8", "MODULO_2": "sa_a7"}),
"ados2_item_04": ("Contacto visual inusual", "SA", {"TODDLER": "sa_b1", "MODULO_1": "sa_b1", "MODULO_2": "sa_b1"}),
"ados2_item_05": ("Expresiones faciales dirigidas a otros", "SA", {"TODDLER": "sa_b4", "MODULO_1": "sa_b3", "MODULO_2": "sa_b2"}),
"ados2_item_06": ("Integración de la mirada con otras conductas", "SA", {"TODDLER": "sa_b5", "MODULO_1": "sa_b4"}),
"ados2_item_07": ("Disfrute compartido en la interacción", "SA", {"TODDLER": "sa_b6", "MODULO_1": "sa_b5", "MODULO_2": "sa_b3"}),
"ados2_item_08": ("Respuesta al nombre", "SA", {"TODDLER": "sa_b7"}),
"ados2_item_09": ("Búsqueda de atención cuando se le ignora", "SA", {"TODDLER": "sa_b8"}),
"ados2_item_10": ("Pedir", "SA", {"TODDLER": "sa_b9"}),
"ados2_item_11": ("Mostrar", "SA", {"TODDLER": "sa_b12", "MODULO_1": "sa_b9", "MODULO_2": "sa_b5"}),
"ados2_item_12": ("Iniciación espontánea de la atención conjunta", "SA", {"TODDLER": "sa_b13", "MODULO_1": "sa_b10", "MODULO_2": "sa_b6"}),
"ados2_item_13": ("Respuesta a la atención conjunta", "SA", {"TODDLER": "sa_b14", "MODULO_1": "sa_b11"}),
"ados2_item_14": ("Calidad de los acercamientos sociales", "SA", {"TODDLER": "sa_b15", "MODULO_1": "sa_b12", "MODULO_2": "sa_b8"}),
"ados2_item_15": ("Cantidad de acercamientos sociales al cuidador", "SA", {"TODDLER": "sa_b16b"}),
"ados2_item_16": ("Cantidad de comunicación social recíproca", "SA", {"MODULO_2": "sa_b11"}),
"ados2_item_17": ("Calidad general de la relación", "SA", {"TODDLER": "sa_b18", "MODULO_2": "sa_b12"}),
"ados2_item_18": ("Entonación de vocalizaciones o verbalizaciones", "RRB", {"TODDLER": "rrb_a3", "MODULO_1": "rrb_a3"}),
"ados2_item_19": ("Uso estereotipado o idiosincrático de palabras", "RRB", {"MODULO_1": "rrb_a5", "MODULO_2": "rrb_a4"}),
"ados2_item_20": ("Interés sensorial inusual", "RRB", {"TODDLER": "rrb_d1", "MODULO_1": "rrb_d1", "MODULO_2": "rrb_d1"}),
"ados2_item_21": ("Manierismos de manos y dedos", "RRB", {"TODDLER": "rrb_d2", "MODULO_1": "rrb_d2", "MODULO_2": "rrb_d2"}),
"ados2_item_22": ("Intereses repetitivos o conductas estereotipadas", "RRB", {"TODDLER": "rrb_d5", "MODULO_1": "rrb_d4", "MODULO_2": "rrb_d4"}),
}
ADOS2_CSS = "CSS"
def _uuid() -> str:
return str(uuid.uuid4())
@@ -220,6 +251,18 @@ class EegMetricaElectrodo(TeaModel, table=True):
mel_z: Optional[float] = _float()
class EegMetricaZona(TeaModel, table=True):
"""A metric's value over one scalp zone (the `tea` library's zones), with its z against the zone's baseline."""
__tablename__ = "eeg_metrica_zona"
mez_id: Optional[str] = _id()
mez_met_id: Optional[str] = _text()
mez_zona: Optional[str] = Field(default=None, sa_column=sa.Column(sa.String(32)))
mez_valor: Optional[float] = _float()
mez_z: Optional[float] = _float()
class RelacionAdos2(TeaModel, table=True):
"""One association of an EEG alteration in a scalp zone with an ADOS-2 outcome, per fitted model version."""
+23 -6
View File
@@ -7,7 +7,7 @@ la unidad (cuando aplica) y la validación que cumple cada una al importarse. El
campo es opcional y la validación ocurre en los esquemas de importación (`WebApi/webapi/imports/schemas/tea`).
Las columnas marcadas **(análisis del EEG)** las escribe el análisis del EEG (la biblioteca `tea`) a partir del EDF
guardado: veredicto, criterios de calidad, canales, duración, sueño, métricas y valores por electrodo. Las dos
guardado: veredicto, criterios de calidad, canales, duración, sueño, métricas y valores por electrodo y por zona. Las dos
tablas de asociación con el ADOS-2 las escribe el modelo de asociación (también la biblioteca `tea`), y mientras
este llega la API de importación carga renglones de desarrollo igual que el resto del staging.
@@ -159,7 +159,24 @@ malo, el motivo con su electrodo.
---
## 10. Tabla `relacion_ados2`
## 10. Tabla `eeg_metrica_zona` **(análisis del EEG)**
El valor de una métrica en una zona del cuero cabelludo y su z contra la curva de referencia de esa zona. Las zonas
son las de la biblioteca `tea` (`tea.contracts.ZONES`): `frontal_izq` (Fp1, F3, F7), `frontal_der` (Fp2, F4, F8),
`frontal_media` (Fz), `central` (C3, Cz, C4), `parietal` (P3, Pz, P4), `temporal_izq` (T3, T5), `temporal_der`
(T4, T6) y `occipital` (O1, O2). Es lo que lee el modelo de asociación con el ADOS-2.
| Variable | Tipo | Unidad | Validación | Llave foránea |
|---|---|---|---|---|
| `mez_id` | VARCHAR(36), llave primaria | — | — | — |
| `mez_met_id` | TEXT | — | — | → `eeg_metrica.met_id` |
| `mez_zona` | VARCHAR(32) | — | El código de la zona. | — |
| `mez_valor` | FLOAT | la de la métrica por electrodo de la zona | — | — |
| `mez_z` | FLOAT | puntaje z | Contra la curva de referencia de la zona a `eeg_edad_meses`. | — |
---
## 11. Tabla `relacion_ados2`
Un renglón por versión del modelo y asociación: la razón de momios, en la cohorte, de una alteración del EEG en una
zona del cuero cabelludo contra el desenlace de un reactivo o dominio del ADOS-2. La llave natural
@@ -174,10 +191,10 @@ biblioteca `tea` unen renglones al cargar una versión del modelo.
| `rel_validado` | INTEGER | — | 0 o 1: validado por el experto de dominio. | — |
| `rel_n_cohorte` | INTEGER | pacientes | Mayor que 0: el tamaño de la cohorte con que se ajustó el modelo. | — |
| `rel_biomarcador` | VARCHAR(32) | — | Catálogo `MetricaEeg`: la métrica del EEG asociada. | — |
| `rel_zona` | VARCHAR(32) | — | El código de la zona del cuero cabelludo, el de la biblioteca `tea`. | — |
| `rel_zona` | VARCHAR(32) | — | El código de la zona del cuero cabelludo, el de la biblioteca `tea` (los de `eeg_metrica_zona`), `posterior` para el ritmo posterior o `global` para el gradiente. | — |
| `rel_tipo` | TEXT | — | Catálogo `NivelRelacionAdos2`: `item, dominio`. El nivel que relaciona esta asociación. | — |
| `rel_resultado` | VARCHAR(32) | — | El código del reactivo del ADOS-2 (los de `ADOS2_ITEMS`) o del dominio. | — |
| `rel_evento` | TEXT | — | El evento de desenlace como umbral legible por máquina sobre el puntaje del desenlace: `>=2` (el puntaje del reactivo, o el total del algoritmo del dominio). | — |
| `rel_resultado` | VARCHAR(32) | — | Un reactivo del ADOS-2 por lo que mide, el mismo en todos los módulos (`ados2_item_01` … `ados2_item_22`, `ADOS2_ITEM_MEANINGS`: un mismo código de reactivo es otro reactivo en otro módulo), o `CSS`, el puntaje de severidad calibrado total. | — |
| `rel_evento` | TEXT | — | El evento de desenlace como umbral legible por máquina sobre el puntaje del desenlace: `>=1` (el puntaje de algoritmo del reactivo en el módulo del niño) o `>=8` (el CSS). | — |
| `rel_or` | FLOAT | razón de momios | Mayor que 0. | — |
| `rel_ic_inf` | FLOAT | razón de momios | El límite inferior del intervalo de confianza; menor o igual que `rel_ic_sup`. | — |
| `rel_ic_sup` | FLOAT | razón de momios | El límite superior del intervalo de confianza. | — |
@@ -185,7 +202,7 @@ biblioteca `tea` unen renglones al cargar una versión del modelo.
---
## 11. Tabla `relacion_ados2_paciente`
## 12. Tabla `relacion_ados2_paciente`
Un renglón por EEG y renglón del modelo: el z del paciente para la asociación y la probabilidad que el modelo le
asigna. La pareja (`rap_rel_id`, `rap_eeg_id`) es única. El desenlace observado no se guarda: se lee del ADOS-2 del
+1
View File
@@ -83,6 +83,7 @@ def test_tea_tables_registered():
"eeg",
"eeg_metrica",
"eeg_metrica_electrodo",
"eeg_metrica_zona",
"eeg_criterio",
"relacion_ados2",
"relacion_ados2_paciente",
+6
View File
@@ -12,6 +12,7 @@ rest of the platform: WebApi gives it the fields to look for and stores what it
| Records | `segmentation.py`, `records.py` | Pages split into records (by patient key, by page count, whole document) and records of the same key merged; the most confident value wins and confident disagreements are kept as conflicts. |
| Letterhead | `template.py` | Margin lines that repeat across different patients' documents are the issuer's, and fill nothing. |
| Candidates | `nlp/extractors.py` | Every reading of every field, each with how it was found (`ExtractedValue.features`): `LabeledValueExtractor` (caption and value, in columns too), `PatternExtractor` (values with a known shape), `FreeTextMentionExtractor` (catalog terms in prose), `MeasurementExtractor` (a number with its unit after its concept). |
| Score tables | `nlp/score_tables.py` | Finds the ADOS-2 table, infers its variant from the item captions, and reads the positioned scores. |
| Context | `nlp/context.py` | Whether the report affirms, denies, supposes, quotes from history or from the clinical request each mention (ConText and NegEx), and which section it sits in. |
| Choice | `nlp/ranking.py` | One value per field: the most confident (`HeuristicRanker`) or a ranker learned from corrections (`LearnedRanker`). |
| Measurement | `nlp/evaluation.py` | Precision, recall and F1 per field against an answer key. |
@@ -22,6 +23,11 @@ what a denied mention means for a presence field (`NEGATED_VALUES`), units (`UNI
about (`SUBJECTS`), section headings and trigger phrases. A report format with a caption or a term the extractor
doesn't know is fixed there, without code changes.
Score-table layouts live in `SCORE_TABLES` in `nlp/vocabulary.py`. The extractor uses headings and item coverage
to locate the table, including a restricted-behavior block continued on the next page. Item captions determine
the module. Printed totals and the stated module are confidence checks. Ambiguous item sets leave the fields
empty and expose `modulo_ambiguo` on the extracted record.
## What the rules do
- **Assertions.** A mention preceded, within its clause, by a negation ("sin", "negativo para"), a hypothetical
+11 -1
View File
@@ -93,6 +93,8 @@ class LabelIndex:
label before them, without being read themselves."""
def __init__(self, lines: Sequence[SegmentLine], specs: Iterable[FieldSpec]):
self.score_tables: dict[str, dict[str, ExtractedValue]] = {}
self.flags: set[str] = set()
self.lines = list(lines)
self.folded = [line.folded for line in self.lines]
self.hits: list[list[LabelHit]] = [_label_hits(line, tuple(specs)) for line in self.lines]
@@ -671,11 +673,15 @@ class MeasurementExtractor(FieldExtractor):
yield ExtractedValue(value, confidence, self.method, line.text[match.start() : match.end()], line.evidence(), features)
from extraction.nlp.score_tables import ScoreTableExtractor
DEFAULT_EXTRACTORS: tuple[FieldExtractor, ...] = (
LabeledValueExtractor(),
PatternExtractor(),
FreeTextMentionExtractor(),
MeasurementExtractor(),
ScoreTableExtractor(),
)
@@ -690,13 +696,17 @@ class RecordExtractor:
self.extractors = list(extractors)
self.ranker = ranker or HeuristicRanker()
def candidates(self, lines: Sequence[SegmentLine]) -> dict[str, list[ExtractedValue]]:
def candidates(
self, lines: Sequence[SegmentLine], *, flags: set[str] | None = None
) -> dict[str, list[ExtractedValue]]:
index = LabelIndex(lines, self.specs)
found: dict[str, list[ExtractedValue]] = {}
for spec in self.specs:
proposed = [candidate for extractor in self.extractors for candidate in extractor.candidates(spec, index)]
if proposed:
found[spec.name] = describe_candidates(proposed)
if flags is not None:
flags.update(index.flags)
return found
def choose(self, candidates: dict[str, list[ExtractedValue]]) -> dict[str, ExtractedValue]:
+1
View File
@@ -97,4 +97,5 @@ class ExtractedValue:
"line": self.evidence.line,
"bbox": self.evidence.bbox,
"assertion": self.features.get("assertion"),
**{flag: True for flag in ("totales_no_cuadran", "modulo_no_coincide") if self.features.get(flag)},
}
+258
View File
@@ -0,0 +1,258 @@
"""Read item scores from positioned rows in clinical tables."""
import re
from collections.abc import Iterator
from dataclasses import dataclass
from functools import cached_property
from itertools import groupby
from extraction.nlp.extractors import FieldExtractor, LabelIndex, SegmentLine, _folded_label, _fuzzy_hits
from extraction.nlp.fields import Evidence, ExtractedValue, FieldSpec
from extraction.nlp.text import fold
from extraction.nlp.vocabulary import SCORE_TABLES
COLUMN_TOLERANCE = 0.025
@dataclass(frozen=True)
class ScoreTable:
"""Captions, score syntax, and variant-specific column mappings."""
anchors: tuple[str, ...]
continuation_anchors: tuple[str, ...]
end_markers: tuple[str, ...]
variants: dict[str, dict[str, str]]
totals: dict[str, tuple[str, ...]]
value_pattern: str
missing_token: str
metadata: dict[str, dict[str, str]]
printed_metadata: dict[str, tuple[str, str]]
unmapped_items: dict[str, dict[str, str]]
aliases: dict[str, tuple[str, ...]]
@cached_property
def total_groups(self) -> dict[str, tuple[str, ...]]:
return {_folded_label(label): prefixes for label, prefixes in self.totals.items()}
@cached_property
def captions(self) -> dict[str, dict[str, str]]:
return {
variant: {
_folded_label(caption): name
for label, name in fields.items()
for caption in (label, *self.aliases.get(label, ()))
}
for variant, fields in self.variants.items()
}
@cached_property
def descriptions(self) -> frozenset[str]:
return frozenset(label for captions in self.captions.values() for label in captions)
@cached_property
def fields(self) -> frozenset[str]:
items = {name for fields in self.variants.values() for name in fields.values()}
return frozenset(items.union(*(fields.keys() for fields in self.metadata.values())))
def match(self, caption: str) -> frozenset[str]:
if caption in self.descriptions:
return frozenset((caption,))
scores = {
label: hit.score
for label in self.descriptions
for hit in _fuzzy_hits(caption, label, label)
if hit.start == 0 and hit.end == len(caption)
}
best = max(scores.values(), default=0.0)
return frozenset(label for label, score in scores.items() if score == best)
@dataclass(frozen=True)
class _Row:
caption: str
token: str
evidence: Evidence
labels: frozenset[str]
@dataclass(frozen=True)
class _Page:
lines: list[SegmentLine]
rows: list[_Row]
anchored: bool
restricted: bool
ended: bool
class ScoreTableExtractor(FieldExtractor):
"""Propose scores from the item set that best explains a table."""
method = "tabla_puntajes"
def __init__(self):
self.tables = {name: ScoreTable(**config) for name, config in SCORE_TABLES.items()}
def candidates(self, spec: FieldSpec, index: LabelIndex) -> Iterator[ExtractedValue]:
for name, table in self.tables.items():
if spec.name not in table.fields:
continue
if name not in index.score_tables:
values, flags = self._read(table, index.lines)
index.score_tables[name] = values
index.flags.update(flags)
candidate = index.score_tables[name].get(spec.name)
if candidate is not None:
yield candidate
def _read(self, table: ScoreTable, lines: list[SegmentLine]) -> tuple[dict[str, ExtractedValue], set[str]]:
pages = [_read_page(table, list(group)) for _, group in
groupby(lines, key=lambda line: (line.document, line.page_number))]
best = None
ambiguous = False
for position, page in enumerate(pages):
following = pages[position + 1] if position + 1 < len(pages) else None
rows = page.rows
if (
following and page.rows and not page.restricted and not page.ended
and following.restricted and following.lines[0].document == page.lines[0].document
and following.lines[0].page_number == page.lines[0].page_number + 1
):
rows = rows + following.rows
if not any(row.labels for row in rows):
continue
ranked = sorted(
((_coverage(table, variant, rows), variant) for variant in table.variants),
reverse=True,
)
score, variant = ranked[0]
tied = len(ranked) > 1 and score == ranked[1][0]
if score < (0.5 if page.anchored else 0.75):
ambiguous |= tied or score < 0.5
continue
priority = (score, page.anchored)
if best is None or priority > best[0]:
best = priority, variant, tied, page, rows
if best is None:
return {}, {"modulo_ambiguo"} if ambiguous else set()
_, variant, tied, page, rows = best
if tied:
return {}, {"modulo_ambiguo"}
return self._values(table, variant, page, rows)
def _values(
self, table: ScoreTable, variant: str, page: _Page, rows: list[_Row]
) -> tuple[dict[str, ExtractedValue], set[str]]:
scores = {}
subtotal_items = {}
totals = {}
features = {}
for row in rows:
if row.token == table.missing_token:
continue
value = int(row.token)
if row.caption in table.total_groups:
totals.setdefault(table.total_groups[row.caption], []).append(value)
continue
if field := _field_for(table, variant, row):
scores.setdefault(field, (value, row.token, row.evidence))
elif prefix := _unmapped_prefix(table, variant, row):
subtotal_items[row.caption] = (prefix, value)
expected = set(table.total_groups.values())
totals_match = bool(totals) and expected == totals.keys()
for prefixes, printed in totals.items():
actual = sum(value for field, (value, _, _) in scores.items() if field.startswith(prefixes))
actual += sum(value for prefix, value in subtotal_items.values() if prefix in prefixes)
totals_match &= all(value == actual for value in printed)
confidence = 0.95 if totals_match else 0.6
if not totals_match:
features["totales_no_cuadran"] = True
evidence = next(row.evidence for row in rows if _field_for(table, variant, row))
for field, value in table.metadata.get(variant, {}).items():
if field in table.printed_metadata:
pattern, format_value = table.printed_metadata[field]
printed = next((match for line in page.lines if (match := re.search(pattern, line.folded))), None)
if printed and format_value.format(printed[1]) != value:
features["modulo_no_coincide"] = True
scores[field] = (value, str(value), evidence)
if features.get("modulo_no_coincide"):
confidence *= 0.8
return {
field: ExtractedValue(value, confidence, self.method, raw, source, features)
for field, (value, raw, source) in scores.items()
}, set(features)
def _field_for(table: ScoreTable, variant: str, row: _Row) -> str | None:
captions = table.captions[variant]
matches = {captions[label] for label in row.labels if label in captions}
return matches.pop() if len(matches) == 1 else None
def _unmapped_prefix(table: ScoreTable, variant: str, row: _Row) -> str | None:
return next((prefix for label, prefix in table.unmapped_items.get(variant, {}).items()
if _folded_label(label) in row.labels), None)
def _coverage(table: ScoreTable, variant: str, rows: list[_Row]) -> float:
matched = set()
foreign = 0
count = 0
for row in rows:
if row.caption in table.total_groups or _unmapped_prefix(table, variant, row):
continue
count += 1
if field := _field_for(table, variant, row):
matched.add(field)
else:
foreign += 1
return len(matched) / len(set(table.variants[variant].values())) - foreign / max(count, 1)
def _read_page(table: ScoreTable, lines: list[SegmentLine]) -> _Page:
anchors = {_folded_label(label) for label in table.anchors}
continuation = {_folded_label(label) for label in table.continuation_anchors}
end = {_folded_label(label) for label in table.end_markers}
headings = [_folded_label(line.text) for line in lines]
start = next((i for i, label in enumerate(headings) if label in anchors - continuation), 0)
cells = []
ended = False
for line, heading in zip(lines[start:], headings[start:]):
words = line.line.words
if len(words) >= 2:
token = fold(words[-1].text)
caption = _folded_label(" ".join(word.text for word in words[:-1]))
if token == table.missing_token or re.fullmatch(table.value_pattern, token) or (
token.isdecimal() and caption in table.total_groups
):
cells.append((line, words[-1].center, caption, token))
if caption in end:
ended = True
break
continue
cells.append((line, None, heading, ""))
if heading in end:
ended = True
break
positions = [x for _, x, _, _ in cells if x is not None]
if not positions:
return _Page(lines, [], bool(anchors.intersection(headings)), bool(continuation.intersection(headings)), ended)
column = max(positions, key=lambda x: (sum(abs(x - other) <= COLUMN_TOLERANCE for other in positions), x))
rows = []
previous = None
for line, x, caption, token in cells:
if x is None or abs(x - column) > COLUMN_TOLERANCE:
previous = line if x is None and caption not in anchors else None
continue
evidence = line.evidence()
labels = table.match(caption) if caption not in table.total_groups else frozenset()
if not labels and caption not in table.total_groups and previous is not None:
joined = f"{_folded_label(previous.text)} {caption}"
if joined_labels := table.match(joined):
caption, labels = joined, joined_labels
first, last = previous.line.bbox, line.line.bbox
bbox = [min(first.x0, last.x0), first.y0, max(first.x1, last.x1), last.y1]
evidence = Evidence(line.document, line.page_number, f"{previous.text} {line.text}",
[round(position, 4) for position in bbox])
rows.append(_Row(caption, token, evidence, labels))
previous = None
return _Page(lines, rows, bool(anchors.intersection(headings)), bool(continuation.intersection(headings)), ended)
+117
View File
@@ -178,6 +178,7 @@ def _caption_from_description(description: str) -> str:
# What a report is about, per target table: a document that names none of
# these is probably a different kind of report (a biopsy read as a cytology).
SUBJECTS: dict[str, tuple[str, ...]] = {
"ados2": ("ADOS", "escala de observación para el diagnóstico del autismo"),
"citologiacervical": ("citología", "citológico", "papanicolaou", "papanicolau", "bethesda", "virus del papiloma", "vph", "hpv"),
"biopsiacervical": ("biopsia", "histopatológico", "histopatología", "histológico", "cono cervical", "conización"),
"mastografia": ("mastografía", "mamografía", "mastográfico", "bi-rads", "birads", "tomosíntesis"),
@@ -404,3 +405,119 @@ FREE_TEXT_FIELDS = FREE_TEXT_FIELDS | {
"eeg_distribucion_anormalidad", "eeg_lentificacion", "eeg_crisis_registradas", "eeg_respuesta_fotoestimulacion",
"eeg_conclusion_categoria", "eeg_calidad_tecnica",
}
SCORE_TABLES = {
"ados2": {
"anchors": (
"Afectación Social (AS)",
"CRR",
"Comportamiento restringido y repetitivo",
"Comportamiento restringido y repetitivo (CRR)",
),
"continuation_anchors": (
"CRR",
"Comportamiento restringido y repetitivo",
"Comportamiento restringido y repetitivo (CRR)",
),
"end_markers": ("Puntuación total global (AS + CRR)", "Puntuación total global", "Total global"),
"totals": {
"Total de afectación social": ("ado_sa_",),
"Puntaje total de comportamiento restringido y repetitivo (CRR)": ("ado_rrb_",),
"Total de comportamiento restringido y repetitivo": ("ado_rrb_",),
"Total CRR": ("ado_rrb_",),
"Puntuación total global (AS + CRR)": ("ado_sa_", "ado_rrb_"),
"Puntuación total global": ("ado_sa_", "ado_rrb_"),
"Total global": ("ado_sa_", "ado_rrb_"),
},
"value_pattern": r"[0-3]",
"missing_token": "S/D",
"metadata": {
"few_words": {"ado_modulo": "MODULO_1", "ado_algoritmo": "Pocas o ninguna palabra"},
"some_words": {"ado_modulo": "MODULO_1", "ado_algoritmo": "Algunas palabras"},
"module_two": {"ado_modulo": "MODULO_2"},
"module_three": {"ado_modulo": "MODULO_3", "ado_algoritmo": "Módulo 3"},
},
"printed_metadata": {"ado_modulo": (r"\bMODULO[ _]+([123])\b", "MODULO_{}")},
"unmapped_items": {
"module_three": {"Gestos descriptivos, convencionales, instrumentales o informativos": "ado_sa_"},
},
"variants": {
"few_words": {
"Frecuencia de la vocalización espontánea dirigida a otros": "ado_sa_a2",
"Gestos": "ado_sa_a8",
"Contacto visual inusual": "ado_sa_b1",
"Expresiones faciales dirigidas a otros": "ado_sa_b3",
"Integración de la mirada y otras conductas durante las iniciaciones sociales": "ado_sa_b4",
"Disfrute compartido durante la interacción": "ado_sa_b5",
"Mostrar": "ado_sa_b9",
"Iniciación espontánea de la atención conjunta": "ado_sa_b10",
"Respuesta a la atención conjunta": "ado_sa_b11",
"Características de las iniciaciones sociales": "ado_sa_b12",
"Entonación de las vocalizaciones o verbalizaciones": "ado_rrb_a3",
"Interés sensorial inusual en los materiales de juego o en las personas": "ado_rrb_d1",
"Manierismos de manos y dedos y otros manierismos complejos": "ado_rrb_d2",
"Intereses inusualmente repetitivos o comportamientos estereotipados": "ado_rrb_d4",
},
"some_words": {
"Frecuencia de la vocalización espontánea dirigida a otros": "ado_sa_a2",
"Señalar": "ado_sa_a7",
"Gestos": "ado_sa_a8",
"Contacto visual inusual": "ado_sa_b1",
"Expresiones faciales dirigidas a otros": "ado_sa_b3",
"Integración de la mirada y otras conductas durante las iniciaciones sociales": "ado_sa_b4",
"Disfrute compartido durante la interacción": "ado_sa_b5",
"Mostrar": "ado_sa_b9",
"Iniciación espontánea de la atención conjunta": "ado_sa_b10",
"Características de las iniciaciones sociales": "ado_sa_b12",
"Uso estereotipado o idiosincrásico de palabras o frases": "ado_rrb_a5",
"Interés sensorial inusual en los materiales de juego o en las personas": "ado_rrb_d1",
"Manierismos de manos y dedos y otros manierismos complejos": "ado_rrb_d2",
"Intereses inusualmente repetitivos o comportamientos estereotipados": "ado_rrb_d4",
},
"module_two": {
"Señalar": "ado_sa_a6",
"Gestos descriptivos, convencionales, instrumentales o informativos": "ado_sa_a7",
"Contacto visual inusual": "ado_sa_b1",
"Expresiones faciales dirigidas a otros": "ado_sa_b2",
"Disfrute compartido durante la interacción": "ado_sa_b3",
"Mostrar": "ado_sa_b5",
"Iniciación espontánea de la atención conjunta": "ado_sa_b6",
"Características de las iniciaciones sociales": "ado_sa_b8",
"Cantidad de comunicación social recíproca": "ado_sa_b11",
"Calidad general de la relación": "ado_sa_b12",
"Uso estereotipado o idiosincrásico de palabras o frases": "ado_rrb_a4",
"Interés sensorial inusual en los materiales de juego o en las personas": "ado_rrb_d1",
"Manierismos de manos y dedos y otros manierismos complejos": "ado_rrb_d2",
"Intereses inusualmente repetitivos o comportamientos estereotipados": "ado_rrb_d4",
},
"module_three": {
"Narración de sucesos": "ado_sa_a7",
"Conversación": "ado_sa_a8",
"Contacto visual inusual": "ado_sa_b1",
"Expresiones faciales dirigidas al examinador": "ado_sa_b2",
"Disfrute compartido durante la interacción": "ado_sa_b4",
"Características de las iniciaciones sociales": "ado_sa_b7",
"Calidad de la respuesta social": "ado_sa_b9",
"Cantidad de comunicación social recíproca": "ado_sa_b10",
"Calidad general de la relación": "ado_sa_b11",
"Uso estereotipado o idiosincrásico de palabras o frases": "ado_rrb_a4",
"Interés sensorial inusual en los materiales de juego o en las personas": "ado_rrb_d1",
"Manierismos de manos y dedos y otros manierismos complejos": "ado_rrb_d2",
"Interés excesivo en temas u objetos inusuales o altamente específicos": "ado_rrb_d4",
},
},
"aliases": {
"Frecuencia de la vocalización espontánea dirigida a otros": ('Vocalización espontánea dirigida a otros',),
"Integración de la mirada y otras conductas durante las iniciaciones sociales": ('Integración de la mirada con otras conductas', 'Integración de la mirada'),
"Disfrute compartido durante la interacción": ('Disfrute compartido en la interacción', 'Disfrute compartido'),
"Características de las iniciaciones sociales": ('Calidad de los acercamientos sociales',),
"Entonación de las vocalizaciones o verbalizaciones": ('Entonación de vocalizaciones o verbalizaciones',),
"Uso estereotipado o idiosincrásico de palabras o frases": ('Uso estereotipado o idiosincrásico de palabras',),
"Interés sensorial inusual en los materiales de juego o en las personas": ('Interés sensorial inusual',),
"Manierismos de manos y dedos y otros manierismos complejos": ('Manierismos de manos y dedos',),
"Intereses inusualmente repetitivos o comportamientos estereotipados": ('Intereses repetitivos o conductas estereotipadas',),
"Gestos descriptivos, convencionales, instrumentales o informativos": ('Gestos',),
},
},
}
+6 -1
View File
@@ -62,6 +62,8 @@ class ExtractedRecord:
# record it merges into turns out to be on topic.
withheld: dict[str, ExtractedValue] = field(default_factory=dict)
flags: set[str] = field(default_factory=set)
def row(self) -> dict[str, Any]:
return {name: extracted.value for name, extracted in self.values.items()}
@@ -104,6 +106,7 @@ class RecordMerger:
target.images.extend(record.images)
target.conflicts.extend(record.conflicts)
target.discovered.extend(record.discovered)
target.flags.update(record.flags)
for name, proposed in record.candidates.items():
target.candidates.setdefault(name, []).extend(proposed)
if record.on_topic is not None and target.on_topic is not True:
@@ -221,7 +224,8 @@ class DocumentExtractor:
"""`template`: normalized texts of margin lines to read nothing from
(`extraction.template`)."""
lines = [line for line in segment.lines() if not (template and in_margin(line.line) and normalized(line.line) in template)]
candidates = self.fields.candidates(lines)
flags: set[str] = set()
candidates = self.fields.candidates(lines, flags=flags)
on_topic = self._on_topic(lines)
if on_topic is not None:
factor = 1.0 if on_topic else OFF_TOPIC_FACTOR
@@ -259,6 +263,7 @@ class DocumentExtractor:
candidates=candidates,
on_topic=on_topic,
withheld=withheld,
flags=flags,
)
+241
View File
@@ -0,0 +1,241 @@
"""Cover ADOS-2 page selection, score extraction, and review flags.
Fixtures: none. PDF helpers draw template captions and scores in memory.
"""
from io import BytesIO
import pytest
from reportlab.pdfgen.canvas import Canvas
from extraction import DocumentExtractor, FieldKind, FieldSpec, read_document
from extraction.nlp.score_tables import ScoreTableExtractor
ITEMS = {
1: (
("sa_a2", "Frecuencia de la vocalización espontánea dirigida a otros"),
("sa_a8", "Gestos"),
("sa_b1", "Contacto visual inusual"),
("sa_b3", "Expresiones faciales dirigidas a otros"),
("sa_b4", "Integración de la mirada y otras conductas durante las iniciaciones sociales"),
("sa_b5", "Disfrute compartido durante la interacción"),
("sa_b9", "Mostrar"),
("sa_b10", "Iniciación espontánea de la atención conjunta"),
("sa_b11", "Respuesta a la atención conjunta"),
("sa_b12", "Características de las iniciaciones sociales"),
("rrb_a3", "Entonación de las vocalizaciones o verbalizaciones"),
("rrb_d1", "Interés sensorial inusual en los materiales de juego o en las personas"),
("rrb_d2", "Manierismos de manos y dedos y otros manierismos complejos"),
("rrb_d4", "Intereses inusualmente repetitivos o comportamientos estereotipados"),
),
2: (
("sa_a2", "Frecuencia de la vocalización espontánea dirigida a otros"),
("sa_a7", "Señalar"),
("sa_a8", "Gestos"),
("sa_b1", "Contacto visual inusual"),
("sa_b3", "Expresiones faciales dirigidas a otros"),
("sa_b4", "Integración de la mirada y otras conductas durante las iniciaciones sociales"),
("sa_b5", "Disfrute compartido durante la interacción"),
("sa_b9", "Mostrar"),
("sa_b10", "Iniciación espontánea de la atención conjunta"),
("sa_b12", "Características de las iniciaciones sociales"),
("rrb_a5", "Uso estereotipado o idiosincrásico de palabras o frases"),
("rrb_d1", "Interés sensorial inusual en los materiales de juego o en las personas"),
("rrb_d2", "Manierismos de manos y dedos y otros manierismos complejos"),
("rrb_d4", "Intereses inusualmente repetitivos o comportamientos estereotipados"),
),
3: (
("sa_a6", "Señalar"),
("sa_a7", "Gestos descriptivos, convencionales, instrumentales o informativos"),
("sa_b1", "Contacto visual inusual"),
("sa_b2", "Expresiones faciales dirigidas a otros"),
("sa_b3", "Disfrute compartido durante la interacción"),
("sa_b5", "Mostrar"),
("sa_b6", "Iniciación espontánea de la atención conjunta"),
("sa_b8", "Características de las iniciaciones sociales"),
("sa_b11", "Cantidad de comunicación social recíproca"),
("sa_b12", "Calidad general de la relación"),
("rrb_a4", "Uso estereotipado o idiosincrásico de palabras o frases"),
("rrb_d1", "Interés sensorial inusual en los materiales de juego o en las personas"),
("rrb_d2", "Manierismos de manos y dedos y otros manierismos complejos"),
("rrb_d4", "Intereses inusualmente repetitivos o comportamientos estereotipados"),
),
4: (
("sa_a7", "Narración de sucesos"),
("sa_a8", "Conversación"),
("sa_a9", "Gestos descriptivos, convencionales, instrumentales o informativos"),
("sa_b1", "Contacto visual inusual"),
("sa_b2", "Expresiones faciales dirigidas al examinador"),
("sa_b4", "Disfrute compartido durante la interacción"),
("sa_b7", "Características de las iniciaciones sociales"),
("sa_b9", "Calidad de la respuesta social"),
("sa_b10", "Cantidad de comunicación social recíproca"),
("sa_b11", "Calidad general de la relación"),
("rrb_a4", "Uso estereotipado o idiosincrásico de palabras o frases"),
("rrb_d1", "Interés sensorial inusual en los materiales de juego o en las personas"),
("rrb_d2", "Manierismos de manos y dedos y otros manierismos complejos"),
("rrb_d4", "Interés excesivo en temas u objetos inusuales o altamente específicos"),
),
}
MODULES = ("MODULO_1", "MODULO_1", "MODULO_2", "MODULO_3")
ALGORITHMS = ("Pocas o ninguna palabra", "Algunas palabras", None, "Módulo 3")
SPECS = [
FieldSpec(f"ado_{key}", FieldKind.INTEGER)
for key in sorted({key for items in ITEMS.values() for key, _ in items} - {"sa_a9"})
] + [FieldSpec("ado_modulo", FieldKind.CHOICE), FieldSpec("ado_algoritmo")]
PROSE = [("Durante el seguimiento se describió afectación social en el informe psicológico.", None)]
def table(variant, *, title=None, missing=None, wrap=None, wrong_total=False):
social = restricted = 0
restricted_started = False
rows = [
(title, None),
("Afectación Social (AS)", None),
("Comunicación", None),
] if title else [("Afectación Social (AS)", None), ("Comunicación", None)]
expected = {}
for position, (key, caption) in enumerate(ITEMS[variant]):
if key.startswith("rrb_") and not restricted_started:
restricted_started = True
rows.extend([
("TOTAL DE AFECTACIÓN SOCIAL", social),
("Comportamiento restringido y repetitivo (CRR)", None),
])
value = position % 4
if key == missing:
value = "S/D"
else:
if key.startswith("sa_"):
social += value
else:
restricted += value
if key != "sa_a9":
expected[f"ado_{key}"] = value
if key == wrap:
first, caption = caption.split(" espontánea", 1)
rows.append((first, None))
caption = "espontánea" + caption
rows.append((caption, value))
rows.extend([
("PUNTAJE TOTAL DE COMPORTAMIENTO RESTRINGIDO Y REPETITIVO (CRR)", restricted),
("PUNTUACIÓN TOTAL GLOBAL (AS + CRR)", social + restricted + wrong_total),
])
return rows, expected
def extract(pages, specs=SPECS, **kwargs):
buffer = BytesIO()
canvas = Canvas(buffer, pagesize=(612, 792))
for rows in pages:
canvas.setFont("Helvetica", 9)
for position, (caption, value) in enumerate(rows):
y = 730 - position * 24
canvas.drawString(72, y, caption)
if value is not None:
canvas.drawCentredString(512, y, str(value))
canvas.showPage()
canvas.save()
document = read_document("evaluation.pdf", buffer.getvalue())
[record] = DocumentExtractor(specs, **kwargs).extract([document])
return record
@pytest.mark.parametrize("variant", range(1, 5))
def test_variants(variant):
"""Pins down: all template captions map to their module-specific columns. Fails if any score or metadata differs."""
rows, expected = table(variant)
expected["ado_modulo"] = MODULES[variant - 1]
if algorithm := ALGORITHMS[variant - 1]:
expected["ado_algoritmo"] = algorithm
record = extract([rows])
assert record.row() == expected
assert all(value.method == "tabla_puntajes" and value.confidence == 0.95 for value in record.values.values())
assert not record.flags
def test_table_inside_long_report():
"""Pins down: positioned rows identify the table page. Fails if prose about social affect selects another page."""
rows, expected = table(3)
record = extract([PROSE, PROSE, PROSE, rows, PROSE, PROSE])
assert record.row() == {**expected, "ado_modulo": "MODULO_2"}
assert {value.evidence.page_number for value in record.values.values()} == {4}
def test_inferred_module_disagrees_with_title():
"""Pins down: a conflicting title only lowers confidence. Fails if the title selects the module."""
rows, expected = table(3, title="ADOS-2, módulo 1")
record = extract([rows])
assert record.row() == {**expected, "ado_modulo": "MODULO_2"}
assert 0 < record.confidence < 0.95
assert "modulo_no_coincide" in record.flags
def test_shared_items_are_ambiguous():
"""Pins down: shared items expose an ambiguity flag. Fails if shared captions alone fill a field."""
record = extract([[
("Afectación Social (AS)", None),
("Contacto visual inusual", 1),
("Interés sensorial inusual", 2),
("Manierismos de manos y dedos", 0),
]])
assert record.row() == {}
assert record.flags == {"modulo_ambiguo"}
def test_missing_score():
"""Pins down: S/D counts for inference and leaves its column empty. Fails if it becomes a value."""
rows, expected = table(1, missing="sa_b11")
record = extract([rows])
assert record.row() == {**expected, "ado_modulo": "MODULO_1", "ado_algoritmo": ALGORITHMS[0]}
assert record.confidence == 0.95
def test_wrapped_caption():
"""Pins down: two caption lines share one score and evidence box. Fails if the item is lost or clipped."""
rows, expected = table(1, wrap="sa_a2")
value = extract([rows]).values["ado_sa_a2"]
assert value.value == expected["ado_sa_a2"]
assert value.evidence.line.startswith("Frecuencia de la vocalización espontánea")
assert value.evidence.bbox[3] - value.evidence.bbox[1] > 24 / 792
def test_totals_disagree():
"""Pins down: a wrong total lowers confidence to 0.6. Fails if a score or its review feature is lost."""
rows, expected = table(3, wrong_total=True)
record = extract([rows])
assert record.row() == {**expected, "ado_modulo": "MODULO_2"}
assert record.confidence == 0.6
assert record.values["ado_sa_a6"].to_dict()["totales_no_cuadran"] is True
def test_report_without_table():
"""Pins down: prose alone has no table or flags. Fails if it fills a score or signals ambiguity."""
record = extract([PROSE])
assert record.row() == {}
assert not record.flags
def test_unrelated_field():
"""Pins down: the table extractor only serves registered specs. Fails if a CaCu field gets a candidate."""
rows, _ = table(3)
spec = FieldSpec("cit_calidad_especimen", labels=("Contacto visual inusual",))
assert extract([rows], [spec], extractors=[ScoreTableExtractor()]).candidates == {}
def test_continuation_page():
"""Pins down: the next page completes the restricted behavior block. Fails if its scores or totals are lost."""
rows, expected = table(3)
split = next(index for index, (label, _) in enumerate(rows) if label.startswith("Comportamiento"))
record = extract([rows[:split], rows[split:]])
assert record.row() == {**expected, "ado_modulo": "MODULO_2"}
assert record.values["ado_rrb_d4"].evidence.page_number == 2
assert record.confidence == 0.95
def test_renamed_headings():
"""Pins down: high coverage is enough without the anchors. Fails if the headings become mandatory."""
rows, expected = table(4)
rows = [(label, value) for label, value in rows
if label not in {"Afectación Social (AS)", "Comportamiento restringido y repetitivo (CRR)"}]
assert extract([rows]).row() == {**expected, "ado_modulo": "MODULO_3", "ado_algoritmo": "Módulo 3"}
+4
View File
@@ -38,6 +38,8 @@ from core.cama.models import (
NotaMedica,
OrdenesEstudio,
Paciente,
TratamientoMama,
SeguimientoMama,
)
from core.indicadores.cohortes import TablasCohorte
@@ -72,6 +74,8 @@ biopsia_mama_repository = Repository(get_cama_session, BiopsiaMama)
nota_medica_repository = Repository(get_cama_session, NotaMedica)
biometria_hematica_repository = Repository(get_cama_session, BiometriaHematica)
episodio_clinico_repository = Repository(get_cama_session, EpisodioClinico)
tratamiento_mama_repository = Repository(get_cama_session, TratamientoMama)
seguimiento_mama_repository = Repository(get_cama_session, SeguimientoMama)
# 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,98 @@
"""structured pathology, staging, treatment and patient attributes
The results the survival model reads, as they arrive: the biopsy report's structured fields (`biopsia_mama`), the mammogram's density and findings (`mastografia`), the
clinical stage and metastasis of a note (`nota_medica`), marital status, race and BRCA results of the patient
(`paciente`) and one row per treatment course (`tratamiento_mama`).
Revision ID: b6d1f4a82c57
Revises: a9c4e2f17d38
Create Date: 2026-11-22 12:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'b6d1f4a82c57'
down_revision = 'a9c4e2f17d38'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column('biopsiamama', sa.Column('bx_tipo_histologico', sa.Text(), nullable=True))
op.add_column('biopsiamama', sa.Column('bx_grado_nottingham', sa.Text(), nullable=True))
op.add_column('biopsiamama', sa.Column('bx_receptor_estrogeno', sa.Text(), nullable=True))
op.add_column('biopsiamama', sa.Column('bx_receptor_estrogeno_pct', sa.Float(), nullable=True))
op.add_column('biopsiamama', sa.Column('bx_receptor_progesterona', sa.Text(), nullable=True))
op.add_column('biopsiamama', sa.Column('bx_receptor_progesterona_pct', sa.Float(), nullable=True))
op.add_column('biopsiamama', sa.Column('bx_her2', sa.Text(), nullable=True))
op.add_column('biopsiamama', sa.Column('bx_her2_fish', sa.Text(), nullable=True))
op.add_column('biopsiamama', sa.Column('bx_ki67_pct', sa.Float(), nullable=True))
op.add_column('biopsiamama', sa.Column('bx_tamano_tumor_mm', sa.Float(), nullable=True))
op.add_column('biopsiamama', sa.Column('bx_ganglios_positivos', sa.Float(), nullable=True))
op.add_column('biopsiamama', sa.Column('bx_invasion_linfovascular', sa.Text(), nullable=True))
op.add_column('biopsiamama', sa.Column('bx_multifocalidad', sa.Text(), nullable=True))
op.add_column('biopsiamama', sa.Column('bx_margenes', sa.Text(), nullable=True))
op.add_column('biopsiamama', sa.Column('bx_pt', sa.Text(), nullable=True))
op.add_column('biopsiamama', sa.Column('bx_pn', sa.Text(), nullable=True))
op.add_column('biopsiamama', sa.Column('bx_lateralidad', sa.Text(), nullable=True))
op.add_column('biopsiamama', sa.Column('bx_localizacion', sa.Text(), nullable=True))
op.add_column('mastografia', sa.Column('mast_densidad', sa.Text(), nullable=True))
op.add_column('mastografia', sa.Column('mast_margen_masa', sa.Text(), nullable=True))
op.add_column('mastografia', sa.Column('mast_tipo_hallazgo', sa.Text(), nullable=True))
op.add_column('notamedica', sa.Column('nm_estadio_clinico', sa.Text(), nullable=True))
op.add_column('notamedica', sa.Column('nm_metastasis', sa.Text(), nullable=True))
op.add_column('paciente', sa.Column('pac_estado_civil', sa.Text(), nullable=True))
op.add_column('paciente', sa.Column('pac_raza', sa.Text(), nullable=True))
op.add_column('paciente', sa.Column('pac_brca1', sa.Text(), nullable=True))
op.add_column('paciente', sa.Column('pac_brca2', sa.Text(), nullable=True))
op.create_table(
'tratamientomama',
sa.Column('trat_id', sa.Integer(), primary_key=True, autoincrement=True),
sa.Column('pac_id', sa.Integer(), nullable=True),
sa.Column('pac_id_hospital', sa.String(length=64), nullable=False),
sa.Column('trat_tipo', sa.Text(), nullable=False),
sa.Column('trat_fecha', sa.Date(), nullable=True),
sa.Column('trat_detalle', sa.Text(), nullable=True),
sa.Column('trat_lateralidad', sa.Text(), nullable=True),
)
op.create_index('ix_tratamientomama_pac_id', 'tratamientomama', ['pac_id'])
op.create_index('ix_tratamientomama_pac_id_hospital', 'tratamientomama', ['pac_id_hospital'])
def downgrade() -> None:
op.drop_index('ix_tratamientomama_pac_id_hospital', table_name='tratamientomama')
op.drop_index('ix_tratamientomama_pac_id', table_name='tratamientomama')
op.drop_table('tratamientomama')
with op.batch_alter_table('mastografia') as batch:
batch.drop_column('mast_tipo_hallazgo')
batch.drop_column('mast_margen_masa')
batch.drop_column('mast_densidad')
with op.batch_alter_table('paciente') as batch:
batch.drop_column('pac_brca2')
batch.drop_column('pac_brca1')
batch.drop_column('pac_raza')
batch.drop_column('pac_estado_civil')
with op.batch_alter_table('notamedica') as batch:
batch.drop_column('nm_metastasis')
batch.drop_column('nm_estadio_clinico')
with op.batch_alter_table('biopsiamama') as batch:
batch.drop_column('bx_localizacion')
batch.drop_column('bx_lateralidad')
batch.drop_column('bx_pn')
batch.drop_column('bx_pt')
batch.drop_column('bx_margenes')
batch.drop_column('bx_multifocalidad')
batch.drop_column('bx_invasion_linfovascular')
batch.drop_column('bx_ganglios_positivos')
batch.drop_column('bx_tamano_tumor_mm')
batch.drop_column('bx_ki67_pct')
batch.drop_column('bx_her2_fish')
batch.drop_column('bx_her2')
batch.drop_column('bx_receptor_progesterona_pct')
batch.drop_column('bx_receptor_progesterona')
batch.drop_column('bx_receptor_estrogeno_pct')
batch.drop_column('bx_receptor_estrogeno')
batch.drop_column('bx_grado_nottingham')
batch.drop_column('bx_tipo_histologico')
@@ -0,0 +1,56 @@
"""recurrence variables and follow-up
The facts the recurrence model reads, as they arrive: the patient's menopausal state, molecular and clinical subtypes,
integrative cluster, cellularity, mutation load, Ki-67 category and the source of her record (`paciente`), and one row per
follow-up fact, a recurrence or the last contact (`seguimientomama`).
Revision ID: c7e2a5f9b413
Revises: b6d1f4a82c57
Create Date: 2026-11-22 18:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'c7e2a5f9b413'
down_revision = 'b6d1f4a82c57'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column('paciente', sa.Column('pac_estado_menopausico', sa.Text(), nullable=True))
op.add_column('paciente', sa.Column('pac_pam50', sa.Text(), nullable=True))
op.add_column('paciente', sa.Column('pac_subtipo_clinico', sa.Text(), nullable=True))
op.add_column('paciente', sa.Column('pac_cluster_integrativo', sa.Text(), nullable=True))
op.add_column('paciente', sa.Column('pac_celularidad', sa.Text(), nullable=True))
op.add_column('paciente', sa.Column('pac_carga_mutacional', sa.Float(), nullable=True))
op.add_column('paciente', sa.Column('pac_ki67_categoria', sa.Text(), nullable=True))
op.add_column('paciente', sa.Column('pac_fuente', sa.Text(), nullable=True))
op.create_table(
'seguimientomama',
sa.Column('seg_id', sa.Integer(), primary_key=True, autoincrement=True),
sa.Column('pac_id', sa.Integer(), nullable=True),
sa.Column('pac_id_hospital', sa.String(length=64), nullable=False),
sa.Column('seg_tipo', sa.Text(), nullable=False),
sa.Column('seg_fecha', sa.Date(), nullable=True),
sa.Column('seg_detalle', sa.Text(), nullable=True),
)
op.create_index('ix_seguimientomama_pac_id', 'seguimientomama', ['pac_id'])
op.create_index('ix_seguimientomama_pac_id_hospital', 'seguimientomama', ['pac_id_hospital'])
def downgrade() -> None:
op.drop_index('ix_seguimientomama_pac_id_hospital', table_name='seguimientomama')
op.drop_index('ix_seguimientomama_pac_id', table_name='seguimientomama')
op.drop_table('seguimientomama')
with op.batch_alter_table('paciente') as batch:
batch.drop_column('pac_fuente')
batch.drop_column('pac_ki67_categoria')
batch.drop_column('pac_carga_mutacional')
batch.drop_column('pac_celularidad')
batch.drop_column('pac_cluster_integrativo')
batch.drop_column('pac_subtipo_clinico')
batch.drop_column('pac_pam50')
batch.drop_column('pac_estado_menopausico')
@@ -0,0 +1,25 @@
"""cama recurrence heads joined
The structured biopsy results, the treatment and follow-up tables and the recurrence variables (`c7e2a5f9b413`) were
added on a separate line from the risk index date (`d4a7c1e93b58`); this joins them so the chain has one head again.
Nothing to change on any engine.
Revision ID: e3b8a6d29f71
Revises: d4a7c1e93b58, c7e2a5f9b413
Create Date: 2026-11-22 09:45:00.000000
"""
# revision identifiers, used by Alembic.
revision = 'e3b8a6d29f71'
down_revision = ('d4a7c1e93b58', 'c7e2a5f9b413')
branch_labels = None
depends_on = None
def upgrade() -> None:
pass
def downgrade() -> None:
pass
+11 -2
View File
@@ -22,6 +22,10 @@ class DbtRelationError(RuntimeError):
"""A relation dbt should have created can't be read."""
# How many patients go in one `IN (...)`: under the bound-variable limit of the engines (SQL Server's is 2,100).
PATIENTS_PER_QUERY = 2_000
def timeline_view(domain: str) -> str:
return f"{domain}_linea_de_tiempo"
@@ -30,7 +34,7 @@ class DbtTimelineRepository(TimelineRepository):
"""The domain's timeline, read from dbt's view `<domain>_linea_de_tiempo`.
`fecha` comes back as a date and `conocida_en` as an aware UTC datetime on every engine. The filters run in the database; `patients` becomes one bound
parameter per patient, so a long list can exceed an engine's limit (SQL Server's is 2,100): read without it and join.
parameter per patient, so it is read in lists of `PATIENTS_PER_QUERY`, in patient order.
"""
def __init__(self, session_factory: Callable, domain: str):
@@ -52,7 +56,12 @@ class DbtTimelineRepository(TimelineRepository):
def read(self, *, patients: Iterable[int] | None = None, until: date | None = None,
known_until: datetime | None = None) -> list[dict]:
try:
return super().read(patients=patients, until=until, known_until=known_until)
if patients is None:
return super().read(patients=None, until=until, known_until=known_until)
ids = sorted(set(patients))
return [row for desde in range(0, len(ids), PATIENTS_PER_QUERY)
for row in super().read(patients=ids[desde:desde + PATIENTS_PER_QUERY], until=until,
known_until=known_until)]
except DBAPIError as error:
raise DbtRelationError(f"can't read {self.view} ({error.orig}): is it created? "
f"Run `dbt run --select {self.view}` in Transformation") from error
+59 -5
View File
@@ -135,10 +135,20 @@ class CohortRepository(Repository):
evaluation's latest version is `final`. One horizon per `horizonte_anios`, at its latest version, ascending;
horizons whose latest version is `entered-in-error` are left out. `None` if no batch of the patient is
confirmed."""
found = self.current_risks(pac_id, limit=1)
return found[0] if found else None
def current_risks(self, pac_id: int, limit: int | None = None) -> "list[PatientRisk]":
"""The patient's current batch of each outcome (`desenlace`), as `current_risk` picks one, newest first: a
CIN2+ model's and a cancer model's risks are both current. `limit` stops after that many outcomes."""
e = self.cohortes.EvaluacionRiesgo
found: dict[str | None, PatientRisk] = {}
with self._session_factory() as sesion:
batches = sesion.exec(select(e.lote_id).where(e.pac_id == pac_id).distinct().order_by(e.lote_id.desc())).all()
for lote_id in batches:
batch = sesion.get(self.cohortes.EvaluacionRiesgoLote, lote_id)
if batch.desenlace in found:
continue
latest = _latest_versions(sesion, e, lote_id)
if not sesion.exec(select(e.evaluacion_id).join(latest, _same_version(e, latest))
.where(e.lote_id == lote_id, e.estado == FINAL).limit(1)).first():
@@ -146,11 +156,55 @@ class CohortRepository(Repository):
rows = sesion.exec(select(e).join(latest, _same_version(e, latest))
.where(e.lote_id == lote_id, e.pac_id == pac_id, e.estado != ERROR)
.order_by(e.horizonte_anios)).all()
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], rows[0].fecha_indice if rows else None, batch.desenlace)
return None
found[batch.desenlace] = 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],
rows[0].fecha_indice if rows else None, batch.desenlace)
if limit is not None and len(found) >= limit:
break
return list(found.values())
def current_risks_by_patient(self) -> "dict[str | None, dict[int, list[RiskHorizon]]]":
"""Every patient's current risks of each outcome at once, as `current_risks` would give them one by one: per
outcome, per `pac_id`, the horizons of the newest confirmed batch of that outcome that scored her. For lists
of many patients (the follow-up list), where a query per patient is too slow."""
e = self.cohortes.EvaluacionRiesgo
lote = self.cohortes.EvaluacionRiesgoLote
found: dict[str | None, dict[int, list[RiskHorizon]]] = {}
with self._session_factory() as sesion:
for batch in sesion.exec(select(lote).order_by(lote.lote_id.desc())).all():
latest = _latest_versions(sesion, e, batch.lote_id)
if not sesion.exec(select(e.evaluacion_id).join(latest, _same_version(e, latest))
.where(e.lote_id == batch.lote_id, e.estado == FINAL).limit(1)).first():
continue
de_este = found.setdefault(batch.desenlace, {})
nuevos: dict[int, list[RiskHorizon]] = {}
for r in sesion.exec(select(e).join(latest, _same_version(e, latest))
.where(e.lote_id == batch.lote_id, e.estado != ERROR)
.order_by(e.pac_id, e.horizonte_anios)).all():
if r.pac_id not in de_este:
nuevos.setdefault(r.pac_id, []).append(
RiskHorizon(r.horizonte_anios, r.probabilidad, r.ic_bajo, r.ic_alto, r.estado))
de_este.update(nuevos)
return found
def current_batches(self) -> "list[PatientRisk]":
"""The domain's current batch of each outcome, whoever it scored: the highest `lote_id` of the outcome with
some evaluation's latest version `final`, newest first, with no horizons. What tells a patient a model of
that outcome exists although it didn't score her."""
found: dict[str | None, PatientRisk] = {}
lote = self.cohortes.EvaluacionRiesgoLote
e = self.cohortes.EvaluacionRiesgo
with self._session_factory() as sesion:
for batch in sesion.exec(select(lote).order_by(lote.lote_id.desc())).all():
if batch.desenlace in found:
continue
latest = _latest_versions(sesion, e, batch.lote_id)
if sesion.exec(select(e.evaluacion_id).join(latest, _same_version(e, latest))
.where(e.lote_id == batch.lote_id, e.estado == FINAL).limit(1)).first():
found[batch.desenlace] = PatientRisk(batch.lote_id, batch.modelo_nombre, batch.modelo_version,
batch.evaluado_en, FINAL, [], None, batch.desenlace)
return list(found.values())
@dataclass(frozen=True)
@@ -30,6 +30,9 @@ log = logging.getLogger(__name__)
KEY = ("fuente_tabla", "fuente_id", "estudio_id", "clase")
# How many ids go in one `IN (...)`: under the limit of bound variables of the engines.
_LOTE = 10_000
def save_silver_in(
sesion: Session, plata, *, procedimiento: type[SQLModel], observacion: type[SQLModel], carga_id: int
) -> dict[str, int]:
@@ -84,8 +87,9 @@ def save_silver_in(
ids = [fila.procedimiento_id for fila in existentes.values()]
actuales = {
(o.procedimiento_id, o.resultado_id): o
for o in sesion.exec(select(observacion).where(observacion.procedimiento_id.in_(ids)))
} if ids else {}
for desde in range(0, len(ids), _LOTE)
for o in sesion.exec(select(observacion).where(observacion.procedimiento_id.in_(ids[desde:desde + _LOTE])))
}
for o in plata.observaciones:
dueno = existentes.get(o["procedimiento"])
if dueno is None:
+2
View File
@@ -36,6 +36,7 @@ from core.tea.models import (
EegMetrica,
EegCriterio,
EegMetricaElectrodo,
EegMetricaZona,
EvaluacionNeuropediatrica,
Mchat,
OrdenesEstudio,
@@ -77,6 +78,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_metrica_zona_repository = Repository(get_tea_session, EegMetricaZona)
eeg_criterio_repository = Repository(get_tea_session, EegCriterio)
relacion_ados2_repository = Repository(get_tea_session, RelacionAdos2)
relacion_ados2_paciente_repository = Repository(get_tea_session, RelacionAdos2Paciente)
@@ -0,0 +1,34 @@
"""tea eeg metric zones
What the EEG analysis writes per scalp zone: one row per metric and zone in `eeg_metrica_zona`, the metric's value
over the zone's electrodes and its z against the zone's baseline, which the ADOS-2 association model reads. Only
additions: nothing existing changes.
Revision ID: 98dadd777ffd
Revises: e8c2a5d47f13
Create Date: 2026-11-21 18:40:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '98dadd777ffd'
down_revision = 'e8c2a5d47f13'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table('eeg_metrica_zona',
sa.Column('mez_id', sa.String(length=36), nullable=False),
sa.Column('mez_met_id', sa.Text(), nullable=True),
sa.Column('mez_zona', sa.String(length=32), nullable=True),
sa.Column('mez_valor', sa.Float(), nullable=True),
sa.Column('mez_z', sa.Float(), nullable=True),
sa.PrimaryKeyConstraint('mez_id')
)
def downgrade() -> None:
op.drop_table('eeg_metrica_zona')
+55 -1
View File
@@ -1,5 +1,5 @@
"""What this module covers: the per-patient reads of `CohortRepository` behind the risk route: `membership` (the
patient in the cohort's latest build, with its variables) and `current_risk` (the current batch and its horizons).
patient in the cohort's latest build, with its variables) and `current_risk` (the current batch and its horizons), `current_risks` (the current batch of each outcome) and `current_batches` (the domain's, whoever they scored).
Fixtures: `repository`, an in-memory SQLite database with the CaCu tables: builds 1 and 2 of the surveillance cohort
(patient 10 in both, patient 20 only in build 1), patient 10's variables in build 2, and batches written and confirmed
@@ -85,6 +85,60 @@ def test_the_current_batch_is_the_newest_confirmed_one_with_its_horizons(reposit
assert risk.horizontes == [RiskHorizon(1.0, 0.1, 0.05, 0.2, "final"), RiskHorizon(3.0, 0.3, None, None, "final")]
def test_each_outcome_has_its_own_current_batch(repository):
"""Pins down: a CIN2+ batch and a newer cancer batch are both current, newest first, and a newer confirmed batch
of an outcome replaces the older one of the same outcome only. Fails if the newest batch hides the other
outcome's risk, or two batches of one outcome are shown."""
def batch(version, outcome, p):
lote = repository.save_batch(2, {**PROVENANCE, "modelo_version": version}, outcome,
[(10, D, 1.0, p, None, None)])[0]
repository.change_state(lote, "final", "revisado")
return lote
old_cin2, cancer, cin2 = batch("1", "cin2", 0.1), batch("1", "cancer", 0.01), batch("2", "cin2", 0.2)
found = repository.current_risks(10)
assert [(r.lote_id, r.desenlace) for r in found] == [(cin2, "cin2"), (cancer, "cancer")] and old_cin2 < cancer
assert repository.current_risk(10).lote_id == cin2
def test_the_domain_knows_each_outcomes_current_batch_whoever_it_scored(repository):
"""Pins down: the current batch of each outcome is found even for a patient it didn't score, so her record can say
the model exists but doesn't estimate her; an unconfirmed batch isn't current. Fails if `current_batches` reads
only one patient's batches or takes a batch nobody confirmed."""
cin2 = repository.save_batch(1, {**PROVENANCE, "modelo_version": "1"}, "cin2", [(20, D, 1.0, 0.1, None, None)])[0]
repository.change_state(cin2, "final", "revisado")
repository.save_batch(1, {**PROVENANCE, "modelo_version": "2"}, "cancer", [(20, D, 1.0, 0.01, None, None)])
found = repository.current_batches()
assert [(r.lote_id, r.desenlace, r.horizontes) for r in found] == [(cin2, "cin2", [])]
assert repository.current_risks(10) == []
def test_every_patients_current_risks_at_once_match_one_by_one(repository):
"""Pins down: `current_risks_by_patient` gives, per outcome, each patient's horizons of the newest confirmed batch
that scored her, the same as `current_risks` patient by patient; an unconfirmed batch is left out. Fails if a
newer batch that didn't score a patient hides her older one, or a pending batch reaches the follow-up list."""
def batch(armado, version, outcome, rows, confirm=True):
lote = repository.save_batch(armado, {**PROVENANCE, "modelo_version": version}, outcome, rows)[0]
if confirm:
repository.change_state(lote, "final", "revisado")
return lote
batch(1, "1", "cin2", [(10, D, 1.0, 0.1, None, None), (20, D, 1.0, 0.2, None, None)])
batch(2, "2", "cin2", [(10, D, 1.0, 0.3, 0.2, 0.4)])
batch(2, "3", "cin2", [(10, D, 1.0, 0.9, None, None)], confirm=False)
batch(1, "1", "cancer", [(20, D, 1.0, 0.01, None, None)])
found = repository.current_risks_by_patient()
assert {o: {p: [h.probabilidad for h in hs] for p, hs in by.items()} for o, by in found.items()} == {
"cin2": {10: [0.3], 20: [0.2]}, "cancer": {20: [0.01]}}
assert found["cin2"][10] == repository.current_risks(10)[0].horizontes
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."""
+19 -5
View File
@@ -1,7 +1,7 @@
"""What this module covers: the TEA Alembic chain in `persistance/tea/alembic`, applied through
`alembic.command` to a throwaway SQLite file: the deployed schema has the ADOS-2 association tables with
their natural keys, downgrading the association revision removes exactly those tables, and the migrated
schema never drifts from `core.tea.models`.
their natural keys, `eeg_metrica_zona` exists, downgrading each of those revisions removes exactly its tables,
and the migrated schema never drifts from `core.tea.models`.
Fixtures: `url_tea` points `settings.tea_database_url` at a temp file and runs `upgrade head`, so a broken
migration fails the suite instead of the tests silently building the schema with `create_all`; it restores
@@ -53,10 +53,24 @@ def test_association_tables_deployed_with_their_natural_keys(url_tea):
assert ("rap_rel_id", "rap_eeg_id") in uniques_paciente
def test_zone_revision_deploys_and_downgrades_only_its_table(url_tea):
"""Pins down: `eeg_metrica_zona` exists at head with its columns, and downgrading to the revision before it (the
join of the association and the risk index heads) removes it and nothing else. Fails if the zone revision is dropped, loses a column, or its downgrade touches
another table."""
inspector = inspect(create_engine(url_tea))
assert {c["name"] for c in inspector.get_columns("eeg_metrica_zona")} == {
"mez_id", "mez_met_id", "mez_zona", "mez_valor", "mez_z"}
command.downgrade(_config(), "e8c2a5d47f13")
names = set(inspect(create_engine(url_tea)).get_table_names())
assert "eeg_metrica_zona" not in names
assert {"relacion_ados2", "relacion_ados2_paciente", "eeg_metrica", "eeg_metrica_electrodo"} <= names
def test_downgrade_of_the_association_revision_drops_only_the_association_tables(url_tea):
"""Pins down: `downgrade -1` removes `relacion_ados2` and `relacion_ados2_paciente` and nothing the
hospital source loaded. Fails if the downgrade stops dropping them, or starts dropping other tables."""
command.downgrade(_config(), "-1")
"""Pins down: downgrading to the revision before the association removes `relacion_ados2` and
`relacion_ados2_paciente` (and the later zone table) and nothing the hospital source loaded. Fails if the
downgrade stops dropping them, or starts dropping other tables."""
command.downgrade(_config(), "c4306f438b3a")
names = set(inspect(create_engine(url_tea)).get_table_names())
assert "relacion_ados2" not in names
assert "relacion_ados2_paciente" not in names
+49 -31
View File
@@ -27,7 +27,21 @@ vars:
# A note with one of these before the cytology leaves it out: the patient is already a case.
cie_antecedente: ["D06", "D060", "D061", "D067", "D069", "C53", "C530", "C531", "C538", "C539"]
horizonte_toma_reporte_dias: 60
horizonte_toma_diagnostico_dias: 180
# The chained steps take longer than each one's own 60 days: from the sample to the diagnosis, 120, and to the first
# treatment (below), 180.
horizonte_toma_diagnostico_dias: 120
# Provisional: how long after the sample, and after its diagnosis, a treatment still counts for the times to
# treatment (models/cacu/gold/eventos/cacu_tomas_citologia.sql).
horizonte_toma_tratamiento_dias: 180
horizonte_diagnostico_tratamiento_dias: 60
# Provisional: the windows of the screening route, in days: from the sample to the first colposcopy and to the
# biopsy report, from the cytology result to the colposcopy, from the colposcopy to the biopsy report and from the
# biopsy report to the diagnosis (models/cacu/gold/eventos/cacu_ruta_tamizaje.sql).
horizonte_toma_colposcopia_dias: 60
horizonte_toma_biopsia_dias: 60
horizonte_resultado_colposcopia_dias: 60
horizonte_colposcopia_biopsia_dias: 60
horizonte_biopsia_diagnostico_dias: 60
# ASCCP follow-up (the kit's cacu.seguimiento.*; provisional): what counts as a colposcopy and a treatment
# (models/cacu/silver/cacu_procedimientos_inferidos.sql).
seguimiento:
@@ -59,14 +73,17 @@ vars:
# 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
# tratamiento a treatment encounter of one of `tratamiento_estudios` (surgery, chemotherapy, radiotherapy) on or
# 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"]
postratamiento_evidencias: ["egreso", "tratamiento"]
tipos_nota_egreso: ["EGRESO"]
tratamiento_especialidades: ["CIRUGIA_ONCOLOGICA", "ONCOLOGIA_MEDICA"]
diagnostico_evidencias: ["cie"]
tratamiento_estudios: ["cirugia", "quimioterapia", "radioterapia"]
diagnostico_evidencias: ["cie", "biopsia"]
cie_tumor_maligno: ["C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509"]
grados_malignos: ["CARCINOMA_INVASOR"]
especialidades_diagnostico: ["CIRUGIA_ONCOLOGICA"]
@@ -102,31 +119,32 @@ 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]
# The ADOS-2 items by what they measure (core.tea.models.ADOS2_ITEM_MEANINGS, a test keeps them equal): per
# item meaning code, its column code in each module that scores it. The association model's item outcomes are
# these codes (models/tea/gold/seguimiento/tea_paciente_relacion_ados2.sql).
ados2_reactivos:
ados2_item_01: {TODDLER: sa_a2, MODULO_1: sa_a2}
ados2_item_02: {TODDLER: sa_a7, MODULO_1: sa_a7, MODULO_2: sa_a6}
ados2_item_03: {TODDLER: sa_a8, MODULO_1: sa_a8, MODULO_2: sa_a7}
ados2_item_04: {TODDLER: sa_b1, MODULO_1: sa_b1, MODULO_2: sa_b1}
ados2_item_05: {TODDLER: sa_b4, MODULO_1: sa_b3, MODULO_2: sa_b2}
ados2_item_06: {TODDLER: sa_b5, MODULO_1: sa_b4}
ados2_item_07: {TODDLER: sa_b6, MODULO_1: sa_b5, MODULO_2: sa_b3}
ados2_item_08: {TODDLER: sa_b7}
ados2_item_09: {TODDLER: sa_b8}
ados2_item_10: {TODDLER: sa_b9}
ados2_item_11: {TODDLER: sa_b12, MODULO_1: sa_b9, MODULO_2: sa_b5}
ados2_item_12: {TODDLER: sa_b13, MODULO_1: sa_b10, MODULO_2: sa_b6}
ados2_item_13: {TODDLER: sa_b14, MODULO_1: sa_b11}
ados2_item_14: {TODDLER: sa_b15, MODULO_1: sa_b12, MODULO_2: sa_b8}
ados2_item_15: {TODDLER: sa_b16b}
ados2_item_16: {MODULO_2: sa_b11}
ados2_item_17: {TODDLER: sa_b18, MODULO_2: sa_b12}
ados2_item_18: {TODDLER: rrb_a3, MODULO_1: rrb_a3}
ados2_item_19: {MODULO_1: rrb_a5, MODULO_2: rrb_a4}
ados2_item_20: {TODDLER: rrb_d1, MODULO_1: rrb_d1, MODULO_2: rrb_d1}
ados2_item_21: {TODDLER: rrb_d2, MODULO_1: rrb_d2, MODULO_2: rrb_d2}
ados2_item_22: {TODDLER: rrb_d5, MODULO_1: rrb_d4, MODULO_2: rrb_d4}
# 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:
@@ -138,7 +156,7 @@ vars:
# 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_start: "2018-01-01"
recruitment_end: "2027-01-01"
cutoff: "2026-12-31"
surveillance_cohort:
@@ -160,11 +178,11 @@ vars:
# CaMa's recruitment window and cut-off, once (YAML merge key), and its total cohort (models/cama/cohorts/total):
# every patient with a clinical event up to the cut-off, with no rules, for the scenarios that index and filter in
# their own pipeline. The window is the one the scenarios take for their index; the cut-off is where follow-up ends
# (provisional: the synthetic hospital's reference date).
# (the end of the year; no member is followed past the day her build is read).
cama_window: &cama_window
recruitment_start: "2018-01-01"
recruitment_end: "2027-01-01"
cutoff: "2026-01-01"
cutoff: "2026-12-31"
cama_total_cohort:
<<: *cama_window
# The post-treatment cohort (models/cacu/cohorts/post_treatment; KPNC's post-treatment tables): the first cytology
@@ -0,0 +1,30 @@
{#
The first event of a kind after each start, for the same patient: the building block of a time between two events.
`inicio`: a relation with one row per start, with columns `id`, `pac_id` and the date `fecha`.
`linea`: the patient's timeline (`pac_id`, `fecha`, `conocida_en`, `tipo`).
`tipo`: the timeline kind that ends the interval.
`horizonte_dias`: the event must fall fewer days after the start.
`estricto`: true leaves out an event on the start's own day, false counts it.
One row per start that has such an event: `inicio_id`, `fecha_fin` (its date) and `fin_conocido_en` (when it became
known: the earliest load among the patient's events of that day). The days between are the difference of
`dim_fecha.dia_num`, plain arithmetic that every engine runs. The caller joins on `inicio_id`; a start without a
row has no event in its horizon.
#}
{% macro primer_evento_posterior(inicio, id, fecha, linea, tipo, horizonte_dias, estricto=true) -%}
select p.inicio_id, p.fecha_fin, min(l.conocida_en) as fin_conocido_en
from (
select i.{{ id }} as inicio_id, min(l.fecha) as fecha_fin
from {{ inicio }} i
join {{ linea }} l
on l.pac_id = i.pac_id and l.tipo = '{{ tipo }}' and l.fecha {{ '>' if estricto else '>=' }} i.{{ fecha }}
join {{ source('silver', 'dim_fecha') }} dl on dl.fecha = l.fecha
join {{ source('silver', 'dim_fecha') }} di on di.fecha = i.{{ fecha }}
where dl.dia_num - di.dia_num < {{ horizonte_dias }}
group by i.{{ id }}
) p
join {{ inicio }} i on i.{{ id }} = p.inicio_id
join {{ linea }} l on l.pac_id = i.pac_id and l.tipo = '{{ tipo }}' and l.fecha = p.fecha_fin
group by p.inicio_id, p.fecha_fin
{%- endmacro %}
+16
View File
@@ -53,3 +53,19 @@
case when ({{ previo }}) is null or ({{ propio }}) is null then null
when ({{ propio }}) > ({{ previo }}) then ({{ propio }}) else ({{ previo }}) end
{%- endmacro %}
{# The rows of `tea.ados2_reactivos` as a query: per item meaning code (`resultado`) and module (`modulo`, the
`ados2.modulo` catalog codes), the item's code in silver (`reactivo`, `ados2.<column code>`). #}
{% macro tea_ados2_reactivos_por_modulo() -%}
{%- set filas = [] -%}
{%- for resultado, modulos in var('tea')['ados2_reactivos'].items() -%}
{%- for modulo, codigo in modulos.items() -%}
{%- do filas.append((resultado, modulo, 'ados2.' ~ codigo)) -%}
{%- endfor -%}
{%- endfor -%}
{%- for resultado, modulo, reactivo in filas %}
{% if not loop.first %}union all {% endif -%}
select {{ as_text("'" ~ resultado ~ "'") }} as resultado, {{ as_text("'" ~ modulo ~ "'") }} as modulo,
{{ as_text("'" ~ reactivo ~ "'") }} as reactivo
{%- endfor %}
{%- endmacro %}
@@ -16,14 +16,15 @@ models:
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.
description: The patient's first clinical event in the timeline up to the cut-off (not her birth or death). 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.
Pins down: patient 1's index is her earliest clinical event, whatever its type, and her birth, which is earlier,
does not set it; patient 2's only clinical event is after the cut-off, so she has no index, whatever her birth.
Fails if the index takes a later event, one type only, a persona event, or ignores the cut-off.
model: cacu_total_index_date
overrides:
vars:
@@ -34,7 +35,9 @@ unit_tests:
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 1, '1970-05-01', 'nacimiento', 'persona', '1'
union all select 2, '2027-03-01', 'citologia', 't', 'c'
union all select 2, '1960-01-01', 'nacimiento', 'persona', '2'
expect:
format: sql
rows: |
@@ -1,6 +1,7 @@
{#
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
Every patient with at least one clinical event in the timeline up to the cut-off, indexed at her first one (the
earliest, ties broken by source). Her birth and death come from `persona` and are not clinical events, so they never
set the index. 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') %}
@@ -8,7 +9,7 @@ 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 }}'
where fecha <= '{{ p.cutoff }}' and fuente_tabla <> 'persona'
)
select pac_id, fecha as fecha_indice, fuente_tabla as indice_fuente_tabla, fuente_id as indice_fuente_id
from eventos
@@ -0,0 +1,108 @@
-- One row per cytology taken, followed along the screening route: the first colposcopy after the sample, the first
-- biopsy report the sample led to, and the three steps between consecutive events. The sample's own day, whether a
-- cervical cancer note came before it and when the sample and its result became known come from
-- `cacu_tomas_citologia`. Every event is the first of its kind after its start, within its horizon, with when it
-- became known; a step is the days between two of those events. Days are differences of `dim_fecha.dia_num`.
-- colposcopia first `colposcopia` after the sample (`horizonte_toma_colposcopia_dias`)
-- biopsia first biopsy report of the sample (`horizonte_toma_biopsia_dias`)
-- colposcopia_resultado first `colposcopia` from the cytology result on (`horizonte_resultado_colposcopia_dias`)
-- diagnostico_biopsia first `diagnostico` after the biopsy report (`horizonte_biopsia_diagnostico_dias`)
-- The step from the colposcopy to the biopsy report counts when the report falls within
-- `horizonte_colposcopia_biopsia_dias` of that colposcopy.
with colposcopia as (
{{ primer_evento_posterior(ref('cacu_citologias'), 'procedimiento_id', 'fecha_toma', ref('cacu_linea_de_tiempo'),
'colposcopia', var('horizonte_toma_colposcopia_dias')) }}
),
desde_resultado as (
select procedimiento_id, pac_id, fecha_reporte as fecha
from {{ ref('cacu_citologias') }}
where fecha_reporte is not null
),
colposcopia_resultado as (
{{ primer_evento_posterior('desde_resultado', 'procedimiento_id', 'fecha', ref('cacu_linea_de_tiempo'),
'colposcopia', var('horizonte_resultado_colposcopia_dias'), estricto=false) }}
),
-- The biopsy is linked to its sample, not to the patient: the first report of each sample.
primera_biopsia as (
select b.toma_id, min(b.fecha_reporte) as fecha
from {{ ref('cacu_biopsias') }} b
join {{ ref('cacu_citologias') }} c on c.procedimiento_id = b.toma_id
join {{ source('silver', 'dim_fecha') }} db on db.fecha = b.fecha_reporte
join {{ source('silver', 'dim_fecha') }} dt on dt.fecha = c.fecha_toma
where b.fecha_reporte > c.fecha_toma
and db.dia_num - dt.dia_num < {{ var('horizonte_toma_biopsia_dias') }}
group by b.toma_id
),
biopsia as (
select p.toma_id as inicio_id, p.fecha as fecha_fin, min(k.inicio) as fin_conocido_en
from primera_biopsia p
join {{ ref('cacu_biopsias') }} b on b.toma_id = p.toma_id and b.fecha_reporte = p.fecha
join {{ source('silver', 'carga') }} k on k.carga_id = b.reporte_carga_id
group by p.toma_id, p.fecha
),
desde_biopsia as (
select c.procedimiento_id, c.pac_id, bx.fecha_fin as fecha
from {{ ref('cacu_citologias') }} c
join biopsia bx on bx.inicio_id = c.procedimiento_id
),
diagnostico_biopsia as (
{{ primer_evento_posterior('desde_biopsia', 'procedimiento_id', 'fecha', ref('cacu_linea_de_tiempo'),
'diagnostico', var('horizonte_biopsia_diagnostico_dias')) }}
)
select
t.procedimiento_id,
t.fuente_id,
t.pac_id,
t.fecha_toma,
t.toma_conocida_en,
t.resultado_conocido_en,
t.toma_dia,
t.con_antecedente,
dia_reporte.dia_num as reporte_dia,
col.fecha_fin as fecha_colposcopia,
col.fin_conocido_en as colposcopia_conocida_en,
dia_colposcopia.dia_num - t.toma_dia as dias_toma_colposcopia,
bx.fecha_fin as fecha_biopsia,
bx.fin_conocido_en as biopsia_conocida_en,
dia_biopsia.dia_num as biopsia_dia,
dia_biopsia.dia_num - t.toma_dia as dias_toma_biopsia,
cr.fecha_fin as fecha_colposcopia_resultado,
cr.fin_conocido_en as colposcopia_resultado_conocida_en,
dia_colposcopia_resultado.dia_num as colposcopia_resultado_dia,
dia_colposcopia_resultado.dia_num - dia_reporte.dia_num as dias_resultado_colposcopia,
case
when dia_biopsia.dia_num - dia_colposcopia_resultado.dia_num >= 0
and dia_biopsia.dia_num - dia_colposcopia_resultado.dia_num < {{ var('horizonte_colposcopia_biopsia_dias') }}
then dia_biopsia.dia_num - dia_colposcopia_resultado.dia_num
end as dias_colposcopia_biopsia,
db.fecha_fin as fecha_diagnostico_biopsia,
db.fin_conocido_en as diagnostico_biopsia_conocido_en,
dia_diagnostico_biopsia.dia_num - dia_biopsia.dia_num as dias_biopsia_diagnostico
from {{ ref('cacu_tomas_citologia') }} t
join {{ ref('cacu_citologias') }} c on c.procedimiento_id = t.procedimiento_id
left join {{ source('silver', 'dim_fecha') }} dia_reporte
on dia_reporte.fecha = c.fecha_reporte
left join colposcopia col
on col.inicio_id = t.procedimiento_id
left join {{ source('silver', 'dim_fecha') }} dia_colposcopia
on dia_colposcopia.fecha = col.fecha_fin
left join biopsia bx
on bx.inicio_id = t.procedimiento_id
left join {{ source('silver', 'dim_fecha') }} dia_biopsia
on dia_biopsia.fecha = bx.fecha_fin
left join colposcopia_resultado cr
on cr.inicio_id = t.procedimiento_id
left join {{ source('silver', 'dim_fecha') }} dia_colposcopia_resultado
on dia_colposcopia_resultado.fecha = cr.fecha_fin
left join diagnostico_biopsia db
on db.inicio_id = t.procedimiento_id
left join {{ source('silver', 'dim_fecha') }} dia_diagnostico_biopsia
on dia_diagnostico_biopsia.fecha = db.fecha_fin
@@ -0,0 +1,233 @@
version: 2
models:
- name: cacu_ruta_tamizaje
description: "Citologías tomadas, una fila por toma, con la primera colposcopía, el primer reporte de biopsia y los tramos entre eventos consecutivos de la ruta."
config:
materialized: view
semantic_models:
- name: cacu_ruta_tamizaje
description: "Cytologies taken, one row each, followed along the screening route: what the times between its consecutive events count over."
model: ref('cacu_ruta_tamizaje')
defaults:
agg_time_dimension: fecha_toma
entities:
- name: toma_ruta
type: primary
expr: procedimiento_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: resultado_conocido_en
type: time
type_params:
time_granularity: day
- name: fecha_colposcopia
type: time
type_params:
time_granularity: day
- name: colposcopia_conocida_en
type: time
type_params:
time_granularity: day
- name: fecha_biopsia
type: time
type_params:
time_granularity: day
- name: biopsia_conocida_en
type: time
type_params:
time_granularity: day
- name: fecha_colposcopia_resultado
type: time
type_params:
time_granularity: day
- name: colposcopia_resultado_conocida_en
type: time
type_params:
time_granularity: day
- name: fecha_diagnostico_biopsia
type: time
type_params:
time_granularity: day
- name: diagnostico_biopsia_conocido_en
type: time
type_params:
time_granularity: day
- name: toma_dia
type: categorical
- name: reporte_dia
type: categorical
- name: con_antecedente
type: categorical
- name: dias_toma_colposcopia
type: categorical
- name: biopsia_dia
type: categorical
- name: dias_toma_biopsia
type: categorical
- name: colposcopia_resultado_dia
type: categorical
- name: dias_resultado_colposcopia
type: categorical
- name: dias_colposcopia_biopsia
type: categorical
- name: dias_biopsia_diagnostico
type: categorical
measures:
- name: citologias_en_ruta
description: "Distinct samples (the source's cytology id): the unit of the times along the route."
agg: count_distinct
expr: fuente_id
metrics:
- name: cacu_dias_toma_colposcopia
label: "Tiempo de toma de muestra a colposcopía"
description: >-
Días naturales de la toma de cada citología del periodo a la primera colposcopía posterior, dentro del horizonte y a la fecha de corte. La colposcopía se infiere de notas, órdenes y biopsias: su fecha es la de la consulta que ocurrió. Se excluyen las citologías de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.
type: simple
type_params:
measure: citologias_en_ruta
filter: "{{ Dimension('toma_ruta__con_antecedente') }} = 0"
config:
meta:
measure_url: cacu/CACU_DIAS_TOMA_COLPOSCOPIA
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: [toma_conocida_en]
observacion:
valor: dias_toma_colposcopia
fechada_en: [fecha_colposcopia]
conocida_en: [colposcopia_conocida_en]
horizonte:
dias: "{{ var('horizonte_toma_colposcopia_dias') }}"
dia_inicio: toma_dia
- name: cacu_dias_toma_biopsia
label: "Tiempo de toma de muestra a resultado de biopsia"
description: >-
Días naturales de la toma de cada citología del periodo al primer reporte de la biopsia que esa citología originó, dentro del horizonte y a la fecha de corte. Se excluyen las citologías de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.
type: simple
type_params:
measure: citologias_en_ruta
filter: "{{ Dimension('toma_ruta__con_antecedente') }} = 0"
config:
meta:
measure_url: cacu/CACU_DIAS_TOMA_BIOPSIA
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: [toma_conocida_en]
observacion:
valor: dias_toma_biopsia
fechada_en: [fecha_biopsia]
conocida_en: [biopsia_conocida_en]
horizonte:
dias: "{{ var('horizonte_toma_biopsia_dias') }}"
dia_inicio: toma_dia
- name: cacu_dias_resultado_colposcopia
label: "Tiempo del resultado de citología a la colposcopía"
description: >-
Días naturales del resultado de cada citología del periodo a la primera colposcopía desde ese día, dentro del horizonte y a la fecha de corte. Solo entran las citologías con resultado. Se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.
type: simple
type_params:
measure: citologias_en_ruta
filter: "{{ Dimension('toma_ruta__con_antecedente') }} = 0 and {{ Dimension('toma_ruta__reporte_dia') }} is not null"
config:
meta:
measure_url: cacu/CACU_DIAS_RESULTADO_COLPOSCOPIA
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: [toma_conocida_en, resultado_conocido_en]
observacion:
valor: dias_resultado_colposcopia
fechada_en: [fecha_colposcopia_resultado]
conocida_en: [colposcopia_resultado_conocida_en]
horizonte:
dias: "{{ var('horizonte_resultado_colposcopia_dias') }}"
dia_inicio: reporte_dia
- name: cacu_dias_colposcopia_biopsia
label: "Tiempo de la colposcopía al resultado de biopsia"
description: >-
Días naturales de la colposcopía posterior al resultado de cada citología del periodo al primer reporte de la biopsia que esa citología originó, dentro del horizonte y a la fecha de corte. Solo entran las citologías con colposcopía. Se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.
type: simple
type_params:
measure: citologias_en_ruta
filter: "{{ Dimension('toma_ruta__con_antecedente') }} = 0 and {{ Dimension('toma_ruta__colposcopia_resultado_dia') }} is not null"
config:
meta:
measure_url: cacu/CACU_DIAS_COLPOSCOPIA_BIOPSIA
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: [toma_conocida_en, resultado_conocido_en, colposcopia_resultado_conocida_en]
observacion:
valor: dias_colposcopia_biopsia
fechada_en: [fecha_biopsia]
conocida_en: [biopsia_conocida_en]
horizonte:
dias: "{{ var('horizonte_colposcopia_biopsia_dias') }}"
dia_inicio: colposcopia_resultado_dia
- name: cacu_dias_biopsia_diagnostico
label: "Tiempo del resultado de biopsia al diagnóstico"
description: >-
Días naturales del primer reporte de biopsia de cada citología del periodo a la primera nota médica de diagnóstico posterior, dentro del horizonte y a la fecha de corte. Solo entran las citologías con biopsia reportada. Se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.
type: simple
type_params:
measure: citologias_en_ruta
filter: "{{ Dimension('toma_ruta__con_antecedente') }} = 0 and {{ Dimension('toma_ruta__biopsia_dia') }} is not null"
config:
meta:
measure_url: cacu/CACU_DIAS_BIOPSIA_DIAGNOSTICO
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: [toma_conocida_en, biopsia_conocida_en]
observacion:
valor: dias_biopsia_diagnostico
fechada_en: [fecha_diagnostico_biopsia]
conocida_en: [diagnostico_biopsia_conocido_en]
horizonte:
dias: "{{ var('horizonte_biopsia_diagnostico_dias') }}"
dia_inicio: biopsia_dia
@@ -3,27 +3,29 @@
-- was known (`toma_conocida_en`) and when its result was (`resultado_conocido_en`, null without a result). The birth
-- date is the patient's, for strata by age. From her timeline: the first note that resolves the sample (a
-- `diagnostico` after it, within `horizonte_toma_diagnostico_dias`), with its days and when it was known, and whether
-- a cervical cancer note (`antecedente`) came before the sample.
-- a cervical cancer note (`antecedente`) came before the sample. The first `tratamiento` after the sample, within
-- `horizonte_toma_tratamiento_dias`, and the first one after that diagnosis, within
-- `horizonte_diagnostico_tratamiento_dias`, each with its days and when it was known.
with resuelve as (
select c.procedimiento_id, min(l.fecha) as fecha_diagnostico
from {{ ref('cacu_citologias') }} c
join {{ ref('cacu_linea_de_tiempo') }} l
on l.pac_id = c.pac_id and l.tipo = 'diagnostico' and l.fecha > c.fecha_toma
join {{ source('silver', 'dim_fecha') }} dl on dl.fecha = l.fecha
join {{ source('silver', 'dim_fecha') }} dt on dt.fecha = c.fecha_toma
where dl.dia_num - dt.dia_num < {{ var('horizonte_toma_diagnostico_dias') }}
group by c.procedimiento_id
with diagnostico as (
{{ primer_evento_posterior(ref('cacu_citologias'), 'procedimiento_id', 'fecha_toma', ref('cacu_linea_de_tiempo'),
'diagnostico', var('horizonte_toma_diagnostico_dias')) }}
),
-- When the first resolving note became known: the earliest load among her notes of that day.
diagnostico as (
select r.procedimiento_id, r.fecha_diagnostico, min(l.conocida_en) as diagnostico_conocido_en
from resuelve r
join {{ ref('cacu_citologias') }} c on c.procedimiento_id = r.procedimiento_id
join {{ ref('cacu_linea_de_tiempo') }} l
on l.pac_id = c.pac_id and l.tipo = 'diagnostico' and l.fecha = r.fecha_diagnostico
group by r.procedimiento_id, r.fecha_diagnostico
tratamiento as (
{{ primer_evento_posterior(ref('cacu_citologias'), 'procedimiento_id', 'fecha_toma', ref('cacu_linea_de_tiempo'),
'tratamiento', var('horizonte_toma_tratamiento_dias')) }}
),
desde_diagnostico as (
select c.procedimiento_id, c.pac_id, dx.fecha_fin as fecha
from {{ ref('cacu_citologias') }} c
join diagnostico dx on dx.inicio_id = c.procedimiento_id
),
tratamiento_del_diagnostico as (
{{ primer_evento_posterior('desde_diagnostico', 'procedimiento_id', 'fecha', ref('cacu_linea_de_tiempo'),
'tratamiento', var('horizonte_diagnostico_tratamiento_dias')) }}
),
primer_antecedente as (
@@ -47,9 +49,16 @@ select
persona.fecha_nacimiento,
dia_toma.dia_num as toma_dia,
dia_reporte.dia_num - dia_toma.dia_num as dias_toma_reporte,
dx.fecha_diagnostico,
dx.diagnostico_conocido_en,
dx.fecha_fin as fecha_diagnostico,
dx.fin_conocido_en as diagnostico_conocido_en,
dia_diagnostico.dia_num - dia_toma.dia_num as dias_toma_diagnostico,
tx.fecha_fin as fecha_tratamiento,
tx.fin_conocido_en as tratamiento_conocido_en,
dia_tratamiento.dia_num - dia_toma.dia_num as dias_toma_tratamiento,
dia_diagnostico.dia_num as diagnostico_dia,
td.fecha_fin as fecha_tratamiento_diagnostico,
td.fin_conocido_en as tratamiento_diagnostico_conocido_en,
dia_tratamiento_dx.dia_num - dia_diagnostico.dia_num as dias_diagnostico_tratamiento,
case when antecedente.fecha < c.fecha_toma then 1 else 0 end as con_antecedente
from {{ ref('cacu_citologias') }} c
join {{ source('silver', 'persona') }} persona
@@ -64,8 +73,16 @@ left join {{ source('silver', 'dim_fecha') }} dia_toma
left join {{ source('silver', 'dim_fecha') }} dia_reporte
on dia_reporte.fecha = c.fecha_reporte
left join diagnostico dx
on dx.procedimiento_id = c.procedimiento_id
on dx.inicio_id = c.procedimiento_id
left join {{ source('silver', 'dim_fecha') }} dia_diagnostico
on dia_diagnostico.fecha = dx.fecha_diagnostico
on dia_diagnostico.fecha = dx.fecha_fin
left join tratamiento tx
on tx.inicio_id = c.procedimiento_id
left join {{ source('silver', 'dim_fecha') }} dia_tratamiento
on dia_tratamiento.fecha = tx.fecha_fin
left join tratamiento_del_diagnostico td
on td.inicio_id = c.procedimiento_id
left join {{ source('silver', 'dim_fecha') }} dia_tratamiento_dx
on dia_tratamiento_dx.fecha = td.fecha_fin
left join primer_antecedente antecedente
on antecedente.pac_id = c.pac_id
@@ -60,6 +60,28 @@ semantic_models:
time_granularity: day
- name: dias_toma_diagnostico
type: categorical
- name: fecha_tratamiento
type: time
type_params:
time_granularity: day
- name: tratamiento_conocido_en
type: time
type_params:
time_granularity: day
- name: dias_toma_tratamiento
type: categorical
- name: diagnostico_dia
type: categorical
- name: fecha_tratamiento_diagnostico
type: time
type_params:
time_granularity: day
- name: tratamiento_diagnostico_conocido_en
type: time
type_params:
time_granularity: day
- name: dias_diagnostico_tratamiento
type: categorical
- name: con_antecedente
type: categorical
measures:
@@ -258,3 +280,69 @@ metrics:
horizonte:
dias: "{{ var('horizonte_toma_diagnostico_dias') }}"
dia_inicio: toma_dia
- name: cacu_dias_toma_tratamiento
label: "Tiempo de tamizaje a tratamiento"
description: >-
Días naturales de la toma de cada citología del periodo al primer tratamiento posterior: una nota médica con un
CIE-10 de tratamiento después de la primera colposcopia de la paciente, dentro del horizonte y a la fecha de
corte. Entran todas las citologías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de
cáncer cervicouterino anterior a la toma. El tratamiento se infiere de la nota: no distingue el indicado del
realizado.
type: simple
type_params:
measure: citologias
filter: "{{ Dimension('toma__con_antecedente') }} = 0"
config:
meta:
measure_url: cacu/CACU_DIAS_TOMA_TRATAMIENTO
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: [toma_conocida_en]
# The first treatment's days, if it was written by the event cut-off; a sample without one whose horizon
# hasn't passed by then isn't measured yet. The horizon is the one the model used to find the treatment.
observacion:
valor: dias_toma_tratamiento
fechada_en: [fecha_tratamiento]
conocida_en: [tratamiento_conocido_en]
horizonte:
dias: "{{ var('horizonte_toma_tratamiento_dias') }}"
dia_inicio: toma_dia
- name: cacu_dias_diagnostico_tratamiento
label: "Tiempo de diagnóstico a tratamiento"
description: >-
Días naturales del diagnóstico que resuelve cada citología del periodo al primer tratamiento posterior: una nota
médica con un CIE-10 de tratamiento después de la primera colposcopia de la paciente, dentro del horizonte y a la
fecha de corte. Solo entran las citologías que un diagnóstico resolvió; se excluyen las de pacientes con un
diagnóstico de cáncer cervicouterino anterior a la toma. Dos citologías que resuelve el mismo diagnóstico cuentan
cada una. El tratamiento se infiere de la nota: no distingue el indicado del realizado.
type: simple
type_params:
measure: citologias
filter: "{{ Dimension('toma__con_antecedente') }} = 0 and {{ Dimension('toma__diagnostico_dia') }} is not null"
config:
meta:
measure_url: cacu/CACU_DIAS_DIAGNOSTICO_TRATAMIENTO
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: [toma_conocida_en, diagnostico_conocido_en]
observacion:
valor: dias_diagnostico_tratamiento
fechada_en: [fecha_tratamiento_diagnostico]
conocida_en: [tratamiento_diagnostico_conocido_en]
horizonte:
dias: "{{ var('horizonte_diagnostico_tratamiento_dias') }}"
dia_inicio: diagnostico_dia
@@ -1,8 +1,27 @@
{# A view, not ephemeral like the other silver models: cohorts query it. Its sources: cacu_linea_de_tiempo.yml;
the procedures silver doesn't hold but its facts imply (colposcopy, treatment): cacu_procedimientos_inferidos. #}
the procedures silver doesn't hold but its facts imply (colposcopy, treatment): cacu_procedimientos_inferidos; her
birth and death, from `persona` (as CaMa's timeline): the survival scenario's age and outcome. They are not
clinical events, so a cohort indexed at the first event leaves them out (`cacu_total_index_date`). #}
{{ 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('cacu_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 %}
@@ -47,10 +47,24 @@ models:
- {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"}
- {estudio_id: "sociodemografico", clase: "parte", resultado_id: "sociodemografico.raza", clase_de_linea: "medicion", tipo: "raza"}
# 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: "hormonoterapia", clase: "encuentro", resultado_id: "hormonoterapia.intencion", clase_de_linea: "procedimiento", tipo: "hormonoterapia"}
- {estudio_id: "anti_her2", clase: "encuentro", resultado_id: "anti_her2.intencion", clase_de_linea: "procedimiento", tipo: "anti_her2"}
- {estudio_id: "recurrencia", clase: "encuentro", resultado_id: "recurrencia.sitio", clase_de_linea: "medicion", tipo: "recurrencia"}
- {estudio_id: "ultimo_contacto", clase: "encuentro", resultado_id: "ultimo_contacto.estado", clase_de_linea: "medicion", tipo: "ultimo_contacto"}
- {estudio_id: "sociodemografico", clase: "parte", resultado_id: "sociodemografico.estado_menopausico", clase_de_linea: "medicion", tipo: "estado_menopausico"}
- {estudio_id: "sociodemografico", clase: "parte", resultado_id: "sociodemografico.fuente", clase_de_linea: "medicion", tipo: "fuente"}
- {estudio_id: "perfil_molecular", clase: "parte", resultado_id: "perfil_molecular.pam50", clase_de_linea: "medicion", tipo: "pam50"}
- {estudio_id: "perfil_molecular", clase: "parte", resultado_id: "perfil_molecular.subtipo_clinico", clase_de_linea: "medicion", tipo: "subtipo_clinico"}
- {estudio_id: "perfil_molecular", clase: "parte", resultado_id: "perfil_molecular.cluster_integrativo", clase_de_linea: "medicion", tipo: "cluster_integrativo"}
- {estudio_id: "perfil_molecular", clase: "parte", resultado_id: "perfil_molecular.celularidad", clase_de_linea: "medicion", tipo: "celularidad"}
- {estudio_id: "perfil_molecular", clase: "parte", resultado_id: "perfil_molecular.carga_mutacional", clase_de_linea: "medicion", tipo: "carga_mutacional"}
- {estudio_id: "perfil_molecular", clase: "parte", resultado_id: "perfil_molecular.ki67_categoria", clase_de_linea: "medicion", tipo: "ki67_categoria"}
- {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"}
- {estudio_id: "nota_medica", clase: "encuentro", resultado_id: null, clase_de_linea: "procedimiento", tipo: "consulta"}
@@ -60,6 +60,14 @@ evidencia_postratamiento as (
where n.tipo_nota in {{ sql_list(e['tipos_nota_egreso']) }}
and (n.cie_codigo in {{ sql_list(e['cie_tumor_maligno']) }} or n.fecha >= d.primera)
{% endif %}
{% if 'tratamiento' in e['postratamiento_evidencias'] %}
union all
select t.pac_id, t.fecha, c.inicio, t.fuente_tabla, t.fuente_id, 'tratamiento'
from {{ source('silver', 'procedimiento') }} t
join {{ source('silver', 'carga') }} c on c.carga_id = t.carga_id
join diagnostico_maligno d on d.pac_id = t.pac_id and t.fecha >= d.primera
where t.estudio_id in {{ sql_list(e['tratamiento_estudios']) }} and t.clase = 'encuentro'
{% endif %}
{% if 'nota' in e['postratamiento_evidencias'] %}
union all
select n.pac_id, n.fecha, n.conocida_en, n.fuente_tabla, n.fuente_id, 'nota'
@@ -1,10 +1,11 @@
-- One row per child of the cohort, the study's EEG and association row of the latest model version that scored
-- that EEG: the model's metadata (version, expert validation, level, cohort size), the association (EEG metric,
-- scalp zone, outcome level, ADOS-2 item or domain, event) with the cohort's odds ratio, confidence interval and
-- q, and the child's z and probabilities. `observado` is read here, never stored: the outcome's score in the
-- child's first ADOS-2 by date (the one the patient summary shows), the item's score for an item, the domain's
-- algorithm total for a domain. `rel_evento` is the outcome event as a threshold on that score, machine-readable
-- (`>=2`).
-- scalp zone, outcome level, ADOS-2 outcome, event) with the cohort's odds ratio, confidence interval and q, and
-- the child's z and probabilities. `observado` is read here, never stored, from the child's first ADOS-2 by date
-- (the one the patient summary shows): for an item meaning code, the algorithm score of that item's column code in
-- that ADOS-2's module (`vars.tea.ados2_reactivos`), null when the module has no such item or it wasn't scored; for
-- `CSS`, that ADOS-2's calibrated severity score. `rel_evento` is the outcome event as a threshold on that score,
-- machine-readable (`>=1`).
--
-- Latest model version is the greatest version label among the versions that scored the child's study EEG.
-- The patient rows reference the EEG by its staging id, the recording's `fuente_id` in silver.
@@ -32,21 +33,21 @@ primer_ados2 as (
group by a.pac_id
),
observados as (
select a.pac_id, r.reactivo, r.dominio, r.puntaje, r.puntaje_algoritmo
ados2_inicial as (
select a.pac_id, a.procedimiento_id, a.modulo, a.css
from primer_ados2 p
join {{ ref('tea_ados2') }} a on a.pac_id = p.pac_id and a.fecha_ados2 = p.fecha
join {{ ref('tea_ados2_reactivos') }} r on r.procedimiento_id = a.procedimiento_id
),
reactivos_por_modulo as (
{{ tea_ados2_reactivos_por_modulo() }}
),
item_obs as (
select pac_id, reactivo, puntaje from observados
),
dominio_obs as (
select pac_id, dominio, sum(puntaje_algoritmo) as total
from observados
group by pac_id, dominio
select a.pac_id, m.resultado, r.puntaje_algoritmo
from ados2_inicial a
join reactivos_por_modulo m on m.modulo = a.modulo
join {{ ref('tea_ados2_reactivos') }} r on r.procedimiento_id = a.procedimiento_id and r.reactivo = m.reactivo
)
select
@@ -69,8 +70,8 @@ select
rap.rap_probabilidad as probabilidad,
rap.rap_probabilidad_referencia as probabilidad_referencia,
case
when r.rel_tipo = 'item' then io.puntaje
when r.rel_tipo = 'dominio' then dom.total
when r.rel_tipo = 'item' then io.puntaje_algoritmo
when r.rel_tipo = 'dominio' and r.rel_resultado = 'CSS' then ai.css
end as observado
from estudio e
join ultima_version u
@@ -83,8 +84,7 @@ join {{ source('staging', 'relacion_ados2') }} r
left join item_obs io
on io.pac_id = e.pac_id
and r.rel_tipo = 'item'
and io.reactivo = {{ concatena(as_text("'ados2.'"), 'r.rel_resultado') }}
left join dominio_obs dom
on dom.pac_id = e.pac_id
and io.resultado = r.rel_resultado
left join ados2_inicial ai
on ai.pac_id = e.pac_id
and r.rel_tipo = 'dominio'
and dom.dominio = r.rel_resultado
@@ -1,5 +1,6 @@
/* One row per ADOS-2 and scored item: its domain (`SA` social affect, `RRB` restricted and repetitive behaviour,
from the item's prefix), its label in the catalog, its score and its algorithm score (a 3 counts as 2). */
from the item's prefix), its label in the catalog, its score and its algorithm score (a 3 counts as 2; 7, 8 and 9
count as 0). */
select
o.procedimiento_id,
@@ -9,7 +10,9 @@ select
o.resultado_id as reactivo,
r.etiqueta,
o.valor_numerico as puntaje,
case when o.valor_numerico = 3 then 2 else o.valor_numerico end as puntaje_algoritmo
case when o.valor_numerico = 3 then 2
when o.valor_numerico in (7, 8, 9) then 0
else o.valor_numerico end as puntaje_algoritmo
from {{ source('silver', 'observacion_clinica') }} o
join {{ source('silver', 'cat_resultado') }} r
on r.resultado_id = o.resultado_id
+1 -1
Submodule WebApi updated: 4cc2ce83ac...5831fcd9d9
+1 -1
Submodule WebApp updated: 72e5f9bf93...6ade415f63
+1 -1
Submodule models updated: 1b9afb22ea...f9d97f4d12