Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| dc9a3422e0 | |||
| 97480ab832 | |||
| 0f9433949f | |||
| a0407e41d6 |
@@ -43,6 +43,7 @@ packages = ["webapi"]
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"fhir-resources>=8",
|
||||
"pytest>=8.0.0",
|
||||
"reportlab>=4.0",
|
||||
]
|
||||
|
||||
+1
-1
@@ -67,7 +67,7 @@ def base_de(proyecto: str, carpeta, datos=None) -> Base:
|
||||
return Base(proyecto, ctx, import_module(f"persistance.{proyecto}"), motor)
|
||||
|
||||
|
||||
@pytest.fixture(params=["cacu", "cama"])
|
||||
@pytest.fixture(params=["cacu", "cama", "tea"])
|
||||
def proyecto(request):
|
||||
return request.param
|
||||
|
||||
|
||||
+43
-1
@@ -20,12 +20,18 @@ reporte y grado, y una solicitada que todavía no lo tiene.
|
||||
Seis notas médicas con su CIE-10, para el tiempo de la toma al diagnóstico
|
||||
(`NOTAS`; sus casos están en `familias/dias_toma_diagnostico/casos.toml`).
|
||||
|
||||
Texts the silver load reads results from (`TEXTOS`, `INFORME_DE_PATOLOGIA`, `DIAGNOSTICO_DE_NOTA`):
|
||||
H-003's B4A carries density C and a 14 mm lesion, its biopsy a PDF with an invasive ductal carcinoma, grade 2,
|
||||
ER+ 90 %, PR- 0 %, HER2 3+ and Ki-67 25 %, and its oncology note stage IIA. H-101's first mammography says
|
||||
density "tipo E", which the catalog doesn't know: it stays as source text, out of catalog.
|
||||
|
||||
H-001 y H-003 también están en el fixture de CaCu, con otro `pac_id`:
|
||||
lo único común entre los dos sistemas es `pac_id_hospital`.
|
||||
|
||||
Apoyo de pruebas: escribe en la sesión que se le da, nunca en la base del dominio.
|
||||
"""
|
||||
|
||||
import io
|
||||
from datetime import date, timedelta
|
||||
|
||||
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente
|
||||
@@ -69,6 +75,39 @@ NOTAS = (
|
||||
("H-104", None, "C50", ONCOLOGIA), # sin fecha: no cuenta
|
||||
)
|
||||
|
||||
# Index in MASTOGRAFIAS -> the radiologist's interpretation.
|
||||
TEXTOS = {
|
||||
0: "Densidad mamaria: tipo E\nSin hallazgos.",
|
||||
4: "Densidad mamaria: heterogéneamente densas (C).\nNódulo irregular en CSE.\nTamaño de la lesión: 14 mm.",
|
||||
}
|
||||
# Index in BIOPSIAS -> the lines of its pathology report, as a PDF with a text layer.
|
||||
INFORME_DE_PATOLOGIA = {
|
||||
1: (
|
||||
"DIAGNÓSTICO: Carcinoma ductal infiltrante",
|
||||
"Grado histológico: 2 (moderadamente diferenciado)",
|
||||
"Receptores de estrógeno: Positivo (90%)",
|
||||
"Receptores de progesterona: Negativo (0%)",
|
||||
"HER2: 3+",
|
||||
"Ki-67: 25%",
|
||||
),
|
||||
}
|
||||
# Patient -> the diagnosis text of their note.
|
||||
DIAGNOSTICO_DE_NOTA = {"H-003": "Carcinoma de mama izquierda, estadio clínico IIA (T2N0M0)"}
|
||||
|
||||
|
||||
def pdf_de(lineas) -> bytes:
|
||||
"""A one-page PDF with these lines as its text layer."""
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.pdfgen import canvas
|
||||
|
||||
buffer = io.BytesIO()
|
||||
hoja = canvas.Canvas(buffer, pagesize=letter)
|
||||
for i, linea in enumerate(lineas):
|
||||
hoja.drawString(72, 720 - 18 * i, linea)
|
||||
hoja.save()
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
# Órdenes de estudio: (número, paciente, fecha de la orden, especialidad como la escribe el hospital).
|
||||
# La segunda no es de tamizaje; la tercera está pedida y todavía no tiene mastografía.
|
||||
ORDENES = (
|
||||
@@ -141,11 +180,12 @@ def insertar(sesion: Session) -> None:
|
||||
mast_calidad_imagen=calidad,
|
||||
mast_birads=birads,
|
||||
mast_fecha_reporte=None if sin_reporte else toma + timedelta(days=7),
|
||||
mast_interpretacion=TEXTOS.get(indice),
|
||||
)
|
||||
)
|
||||
sesion.add_all(mastografias)
|
||||
sesion.flush()
|
||||
for indice, solicitud, reporte, grado in BIOPSIAS:
|
||||
for numero, (indice, solicitud, reporte, grado) in enumerate(BIOPSIAS):
|
||||
mastografia = mastografias[indice]
|
||||
sesion.add(
|
||||
BiopsiaMama(
|
||||
@@ -155,6 +195,7 @@ def insertar(sesion: Session) -> None:
|
||||
bx_fecha_solicitud=solicitud,
|
||||
bx_fecha_reporte=reporte,
|
||||
bx_grado_histologico=grado,
|
||||
bx_pdf_blob=pdf_de(INFORME_DE_PATOLOGIA[numero]) if numero in INFORME_DE_PATOLOGIA else None,
|
||||
)
|
||||
)
|
||||
sesion.add_all(
|
||||
@@ -165,6 +206,7 @@ def insertar(sesion: Session) -> None:
|
||||
nm_fecha=fecha,
|
||||
nm_cie_codigo=cie,
|
||||
nm_especialidad=especialidad,
|
||||
nm_diagnostico_texto=DIAGNOSTICO_DE_NOTA.get(hospital) if especialidad == ONCOLOGIA else None,
|
||||
)
|
||||
for numero, (hospital, fecha, cie, especialidad) in enumerate(NOTAS, start=1)
|
||||
)
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
"""TEA's synthetic staging, written by hand. Never real data.
|
||||
|
||||
Seven children screened in 2025, each one exercising a rule of the screening's chain (M-CHAT, psychology note
|
||||
with the ADOS-2, neuropediatrics note, good-quality EEG). Ages are at the first M-CHAT, in completed months:
|
||||
|
||||
- 1, H-T01, 19 months (16 to 23): the whole chain. M-CHAT 10 Jan, ADOS-2 5 Feb, F84.0 note 12 Mar, a bad EEG
|
||||
2 Apr, a good EEG 20 May with a slow posterior rhythm, then a second good EEG 1 Sep that changes nothing. Leaves
|
||||
after May. Its EEG has an order.
|
||||
- 2, H-T02, 26 months (24 to 29): M-CHAT 20 Jan, ADOS-2 1 Mar, a note with F84 without subcode 10 Apr (not a
|
||||
confirmation), no EEG: stays at neuropediatrics.
|
||||
- 3, H-T03, 35 months (30 to 36): M-CHAT 14 Feb (a second one 10 Jun doesn't count), ADOS-2 28 Feb, nothing else:
|
||||
stays at psychology.
|
||||
- 4, H-T04, 39 months: out of the cohort, never counted.
|
||||
- 5, H-T05, 21 months: M-CHAT 15 Jun, a F84.0 note 1 Jul and a good EEG 20 Jul without the ADOS-2: steps go in
|
||||
order, so it stays at M-CHAT and in process.
|
||||
- 6, H-T06, 26 months: M-CHAT 5 Apr, ADOS-2 20 Apr, a good EEG 1 Jun before its F84.0 note of 2 Jun: the EEG
|
||||
step is dated by the note, so it reaches EEG on 2 Jun and leaves after June.
|
||||
- 7, H-T07, without birth date: in the cohort with age group `sin_dato`. M-CHAT 1 May, nothing else.
|
||||
|
||||
Every EEG's quality criteria are written as its analysis would; a bad EEG has one criterion out of its threshold.
|
||||
|
||||
Test support: writes in the session it's given, never in the domain's database.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from core.tea.models import (
|
||||
Ados2,
|
||||
Eeg,
|
||||
EegMetrica,
|
||||
EegMetricaElectrodo,
|
||||
EvaluacionNeuropediatrica,
|
||||
Mchat,
|
||||
OrdenesEstudio,
|
||||
Pacientes,
|
||||
)
|
||||
from sqlmodel import Session
|
||||
|
||||
# (pac_id, pac_id_hospital, birth date)
|
||||
PACIENTES = (
|
||||
(1, "H-T01", date(2023, 6, 1)),
|
||||
(2, "H-T02", date(2022, 11, 15)),
|
||||
(3, "H-T03", date(2022, 3, 1)),
|
||||
(4, "H-T04", date(2021, 12, 1)),
|
||||
(5, "H-T05", date(2023, 9, 1)),
|
||||
(6, "H-T06", date(2023, 1, 10)),
|
||||
(7, "H-T07", None),
|
||||
)
|
||||
|
||||
# (pac_id, date, score)
|
||||
MCHATS = (
|
||||
(1, date(2025, 1, 10), 12),
|
||||
(2, date(2025, 1, 20), 9),
|
||||
(3, date(2025, 2, 14), 15),
|
||||
(3, date(2025, 6, 10), 4),
|
||||
(4, date(2025, 3, 3), 11),
|
||||
(5, date(2025, 6, 15), 8),
|
||||
(6, date(2025, 4, 5), 14),
|
||||
(7, date(2025, 5, 1), 7),
|
||||
)
|
||||
|
||||
# (pac_id, date, module, CSS, classification)
|
||||
ADOS2 = (
|
||||
(1, date(2025, 2, 5), "MODULO_1", 7, "AUTISMO"),
|
||||
(2, date(2025, 3, 1), "Toddler", 4, "espectro autista"),
|
||||
(3, date(2025, 2, 28), "MODULO_2", 2, "NO_TEA"),
|
||||
(6, date(2025, 4, 20), "MODULO_1", 8, "AUTISMO"),
|
||||
)
|
||||
|
||||
# (pac_id, date, ICD-10 as the hospital writes it)
|
||||
NOTAS = (
|
||||
(1, date(2025, 3, 12), "F84.0"),
|
||||
(2, date(2025, 4, 10), "F84"),
|
||||
(5, date(2025, 7, 1), "f84.0"),
|
||||
(6, date(2025, 6, 2), "F84.0"),
|
||||
)
|
||||
|
||||
GOOD = {"amplitud": 0, "alta_frecuencia": 1, "correlacion": 0, "sin_senal": 0, "linea": 3.5}
|
||||
BAD = {**GOOD, "sin_senal": 5}
|
||||
|
||||
# (eeg id, pac_id, date, laboratory id, criteria, with sleep)
|
||||
EEGS = (
|
||||
("eeg-1a", 1, date(2025, 4, 2), "LAB-1A", BAD, 0),
|
||||
("eeg-1b", 1, date(2025, 5, 20), "LAB-1B", GOOD, 1),
|
||||
("eeg-1c", 1, date(2025, 9, 1), "LAB-1C", GOOD, 1),
|
||||
("eeg-5", 5, date(2025, 7, 20), "LAB-5", GOOD, 0),
|
||||
("eeg-6", 6, date(2025, 6, 1), "LAB-6", GOOD, 1),
|
||||
)
|
||||
|
||||
# (metric id, eeg id, code, value): a null value can't be evaluated.
|
||||
METRICAS = (
|
||||
("met-1b-rp", "eeg-1b", "RITMO_POSTERIOR", 3.2),
|
||||
("met-1b-n2", "eeg-1b", "HUSOS_SUENO_N2", 4.0),
|
||||
("met-1b-pp", "eeg-1b", "PICOS_PAROXISTICOS", 0.4),
|
||||
("met-1a-rp", "eeg-1a", "RITMO_POSTERIOR", 2.0),
|
||||
("met-6-rp", "eeg-6", "RITMO_POSTERIOR", 6.5),
|
||||
("met-6-n2", "eeg-6", "HUSOS_SUENO_N2", None),
|
||||
("met-6-gr", "eeg-6", "GRADIENTE_ANTEROPOSTERIOR", 2.6),
|
||||
)
|
||||
|
||||
# (electrode value id, metric id, electrode, z-score)
|
||||
ELECTRODOS = (
|
||||
("mel-1", "met-1b-rp", "O1", -2.8),
|
||||
("mel-2", "met-1b-rp", "O2", -2.4),
|
||||
("mel-3", "met-1b-rp", "Pz", -1.1),
|
||||
)
|
||||
|
||||
# The EEG of child 1 that completes the chain hangs from an order.
|
||||
ORDENES = (("ord-1b", 1, "ORD-T01-EEG", "ELECTROENCEFALOGRAMA", date(2025, 5, 2)),)
|
||||
ORDEN_DE = {"eeg-1b": "ord-1b"}
|
||||
|
||||
# What the load gives (`test_orquestacion_plata`).
|
||||
PROCEDIMIENTOS = len(ORDENES) + len(MCHATS) + len(ADOS2) + len(NOTAS) + len(EEGS) + len(ELECTRODOS)
|
||||
|
||||
|
||||
def insertar(sesion: Session) -> None:
|
||||
"""Writes the children, their orders and their studies."""
|
||||
sesion.add_all(Pacientes(pac_id=p, pac_id_hospital=h, pac_fecha_nacimiento=n) for p, h, n in PACIENTES)
|
||||
sesion.add_all(OrdenesEstudio(ord_id=i, ord_pac_id=p, ord_id_hospital=h, ord_tipo_estudio=t, ord_fecha=f)
|
||||
for i, p, h, t, f in ORDENES)
|
||||
sesion.add_all(Mchat(mch_id=f"mch-{k}", mch_pac_id=p, mch_fecha=f, mch_puntaje=s)
|
||||
for k, (p, f, s) in enumerate(MCHATS, 1))
|
||||
for k, (p, f, modulo, css, clasificacion) in enumerate(ADOS2, 1):
|
||||
items = {f"ado_sa_b{n}": n % 3 for n in range(1, 6)} | {"ado_rrb_d1": 2, "ado_rrb_d2": 1}
|
||||
sesion.add(Ados2(ado_id=f"ado-{k}", ado_pac_id=p, ado_fecha=f, ado_modulo=modulo, ado_css=css,
|
||||
ado_clasificacion=clasificacion, ado_algoritmo="Pocas o ninguna palabra", **items))
|
||||
sesion.add_all(EvaluacionNeuropediatrica(neu_id=f"neu-{k}", neu_pac_id=p, neu_fecha=f, neu_cie_codigo=c)
|
||||
for k, (p, f, c) in enumerate(NOTAS, 1))
|
||||
for i, p, f, lab, criterios, sueno in EEGS:
|
||||
sesion.add(Eeg(
|
||||
eeg_id=i, eeg_pac_id=p, eeg_fecha_estudio=f, eeg_id_registro_laboratorio=lab, eeg_ord_id=ORDEN_DE.get(i),
|
||||
eeg_con_sueno=sueno, eeg_canales=19, eeg_duracion_min=25.0,
|
||||
eeg_canales_amplitud=criterios["amplitud"], eeg_canales_alta_frecuencia=criterios["alta_frecuencia"],
|
||||
eeg_canales_correlacion=criterios["correlacion"], eeg_canales_sin_senal=criterios["sin_senal"],
|
||||
eeg_ruido_linea_db=criterios["linea"],
|
||||
))
|
||||
sesion.add_all(EegMetrica(met_id=i, met_eeg_id=e, met_codigo=c, met_valor=v) for i, e, c, v in METRICAS)
|
||||
sesion.add_all(EegMetricaElectrodo(mel_id=i, mel_met_id=m, mel_electrodo=e, mel_valor=v)
|
||||
for i, m, e, v in ELECTRODOS)
|
||||
@@ -0,0 +1,116 @@
|
||||
"""What this module covers: CaMa's tumour stratifiers, from the results read from reports to a measure's strata.
|
||||
dbt's `cama_estratificadores` (stage group, early or advanced stage, surrogate molecular subtype, T by size) as
|
||||
timeline facts; `CAMA_BIRADS_CANCER_INVASOR` broken down by them with the `linea_de_tiempo_al_corte` stratum; and the
|
||||
labels a timeline stratum's values carry into FHIR.
|
||||
|
||||
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database
|
||||
(`staging/cama.py`) through the cycle up to `event_models`. Only H-003 has an invasive cancer: biopsy reported on
|
||||
2025-07-28 from her BI-RADS 4A mammogram (14 mm), HER2 3+, and a note of 2025-08-04 with stage IIA.
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import replace
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from conftest import base_de
|
||||
from sqlalchemy import text
|
||||
from webapi.compositions import answer_composition, composition_definitions
|
||||
from webapi.fhir.measures import _label
|
||||
from webapi.metrics import Question
|
||||
|
||||
URL = "cama/CAMA_BIRADS_CANCER_INVASOR"
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manifest():
|
||||
path = os.environ.get("DBT_MANIFEST")
|
||||
if not path:
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
return Path(path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def base(tmp_path, sin_supresion, manifest):
|
||||
base = base_de("cama", tmp_path)
|
||||
base.run(*UNTIL_MODELS, parameters=sin_supresion, allow_undecided=True)
|
||||
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def answered(base, manifest, period: str, event_cutoff: date | None = None):
|
||||
d = base.dominio
|
||||
definition = composition_definitions(manifest)[URL]
|
||||
return answer_composition("cama", definition, Question(URL, period, event_cutoff=event_cutoff),
|
||||
parameters=d.def_parametro_repository, periods=d.dim_periodo_repository,
|
||||
history=d.history_repository, queries=d.dbt_query_repository, allow_undecided=True)
|
||||
|
||||
|
||||
def stratifiers(base) -> set[str]:
|
||||
with base.motor.connect() as con:
|
||||
return set(con.execute(text("select tipo from cama_estratificadores")).scalars())
|
||||
|
||||
|
||||
def test_the_stratifiers_come_from_h003_s_reports(base):
|
||||
"""Pins down: the view derives the stage's group and early stage from the note, the subtype from the pathology
|
||||
report and T1 from the 14 mm lesion, and nothing for patients without those results. Fails if a rule in
|
||||
`vars.cama.estratos` or a timeline `tipo` it reads changes."""
|
||||
assert stratifiers(base) == {"estadio_ii", "etapa_temprana", "subtipo_her2", "tamano_t1"}
|
||||
|
||||
|
||||
def test_the_measure_breaks_down_the_invasive_cancers_by_tumour(base, manifest):
|
||||
"""Pins down: H-003 counts in S2, the period of her biopsy report, under the BI-RADS of the mammogram that led to
|
||||
it, and in each stratum by what her reports said. S1 has no invasive cancer. Fails if the event model, the
|
||||
category or a stratum's values drift."""
|
||||
assert answered(base, manifest, "2025-S1").categories == {}
|
||||
result = answered(base, manifest, "2025-S2")
|
||||
assert result.categories == {"B4A": 1}
|
||||
assert result.strata == {"grupo_edad": {"50-59": {"B4A": 1}}, "estadio": {"II": {"B4A": 1}},
|
||||
"etapa": {"TEMPRANA": {"B4A": 1}}, "clasificacion": {"HER2": {"B4A": 1}},
|
||||
"tamano": {"T1": {"B4A": 1}}}
|
||||
|
||||
|
||||
def test_a_stratum_by_the_cut_off_sees_only_what_was_dated_by_then(base, manifest):
|
||||
"""Pins down: `linea_de_tiempo_al_corte` reads the timeline up to the event cut-off: on 2025-08-01 the subtype
|
||||
(report of 07-28) is known and the stage (note of 08-04) isn't yet. Fails if the stratum reads before the period's
|
||||
start (H-003 would have nothing) or ignores the cut-off (she'd have her stage)."""
|
||||
strata = answered(base, manifest, "2025-S2", event_cutoff=date(2025, 8, 1)).strata
|
||||
assert strata["clasificacion"] == {"HER2": {"B4A": 1}}
|
||||
assert strata["estadio"] == {"SIN_DATO": {"B4A": 1}}
|
||||
|
||||
|
||||
SUBTIPOS = [
|
||||
({"her2": "H3"}, "subtipo_her2"),
|
||||
({"her2": "H1", "receptor_estrogeno": "NEGATIVO", "receptor_progesterona": "NEGATIVO"}, "subtipo_triple_negativo"),
|
||||
({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 10.0}, "subtipo_luminal_a"),
|
||||
({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 30.0}, "subtipo_luminal_b"),
|
||||
({"her2": "H0", "receptor_progesterona_pct": 10.0, "ki67_pct": 10.0}, "subtipo_luminal_b"),
|
||||
({"her2": "H0", "ki67_pct": None}, None),
|
||||
({"her2": "H2"}, None),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cambios, subtipo", SUBTIPOS)
|
||||
def test_the_surrogate_subtype_follows_its_rules(base, cambios, subtipo):
|
||||
"""Pins down the surrogate subtype from one pathology report: HER2 3+ is HER2-positive; HER2 0 or 1+ with both
|
||||
receptors negative, triple negative; with a positive receptor, luminal A only with Ki-67 under 20 % and
|
||||
progesterone of at least 20 %, else luminal B; without Ki-67, or with an equivocal HER2, none. The fixture's
|
||||
report starts as ER+ 90 %, PR- 0 %, HER2 3+, Ki-67 25 %, with PR made positive here unless a case says otherwise.
|
||||
Fails if a branch of the rule or a threshold in `vars.cama.estratos` changes."""
|
||||
valores = {"receptor_progesterona": "POSITIVO", **cambios}
|
||||
with base.motor.begin() as con:
|
||||
for nombre, valor in valores.items():
|
||||
columna = "valor_numerico" if nombre.endswith("_pct") else "valor_id"
|
||||
con.execute(text(f"update observacion_clinica set {columna} = :v where resultado_id = :r"),
|
||||
{"v": valor, "r": f"biopsia.{nombre}"})
|
||||
assert {t for t in stratifiers(base) if t.startswith("subtipo_")} == ({subtipo} if subtipo else set())
|
||||
|
||||
|
||||
def test_a_timeline_stratum_s_values_carry_their_labels():
|
||||
"""Pins down: FHIR labels a timeline stratum's value from its entry in `valores`, and its `resto` from
|
||||
`resto_etiqueta`. Fails if `_label` reads labels only from a map."""
|
||||
spec = {"valores": [{"valor": "II", "etiqueta": "Estadio II", "si": []}], "resto": "SIN_DATO",
|
||||
"resto_etiqueta": "Sin dato"}
|
||||
assert (_label(spec, "II"), _label(spec, "SIN_DATO"), _label(spec, "IV")) == ("Estadio II", "Sin dato", None)
|
||||
@@ -0,0 +1,178 @@
|
||||
"""What this module covers: catalog results read from a staging row's text (`silver.extracted`). The catalog's
|
||||
`etiquetas_fuente` and `alias` checked when it's read; a report's text, a PDF's text layer and a note turned into
|
||||
codes, numbers and their sources; a spelling the catalog doesn't know kept as text and turned into a code by a
|
||||
catalog change alone; and CaMa's load putting them in silver and dbt's timeline.
|
||||
|
||||
Fixtures: `catalogo_en`, a copy of CaMa's catalog in `tmp_path` that the catalog functions read instead of Core's;
|
||||
`cargada`, the CaMa fixture database (`staging/cama.py`: H-003's texts and pathology PDF, H-101's unknown density)
|
||||
loaded, with dbt's views when `DBT_MANIFEST` is set.
|
||||
"""
|
||||
|
||||
import os
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
from staging.cama import INFORME_DE_PATOLOGIA, pdf_de
|
||||
from webapi.orchestration.reference import catalogs
|
||||
from webapi.orchestration.reference.catalogs import CatalogoInvalido, catalogo_desde_toml, ruta_de_catalogo
|
||||
from webapi.orchestration.silver import cama
|
||||
from webapi.orchestration.silver.extracted import DesdeTexto
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
|
||||
DENSIDAD = """
|
||||
[mastografia]
|
||||
etiqueta = "Mastografía"
|
||||
|
||||
[mastografia.resultados.densidad]
|
||||
etiqueta = "Densidad"
|
||||
tipo_valor = "codigo"
|
||||
etiquetas_fuente = ["Densidad mamaria"]
|
||||
valores = [
|
||||
{ valor = "C", etiqueta = "Heterogéneamente densa", alias = ["Tipo C"] },
|
||||
{ valor = "D", etiqueta = "Extremadamente densa", alias = ["Tipo D"] },
|
||||
]
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalogo_en(tmp_path, monkeypatch):
|
||||
"""Writes a catalog for `cama` in `tmp_path` and points the catalog functions at it. Returns a writer."""
|
||||
ruta = tmp_path / "cama.toml"
|
||||
monkeypatch.setattr(catalogs, "ruta_de_catalogo", lambda proyecto: ruta)
|
||||
|
||||
def escribir(contenido: str):
|
||||
ruta.write_text(contenido, encoding="utf-8")
|
||||
return ruta
|
||||
|
||||
return escribir
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def proyecto():
|
||||
return "cama"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cargada(base):
|
||||
pasos = ("catalogs", "load", "event_models") if os.environ.get("DBT_MANIFEST") else ("catalogs", "load")
|
||||
base.run(*pasos)
|
||||
return base
|
||||
|
||||
|
||||
def observaciones(base, resultado_prefijo: str) -> dict[str, tuple]:
|
||||
"""`resultado_id` -> (valor_id, valor_numerico, valor_fuente) of the observations whose result starts so."""
|
||||
with base.motor.connect() as con:
|
||||
filas = con.execute(text(
|
||||
"SELECT resultado_id, valor_id, valor_numerico, valor_fuente FROM observacion_clinica "
|
||||
"WHERE resultado_id LIKE :p AND (valor_id IS NOT NULL OR valor_numerico IS NOT NULL OR valor_fuente IS NOT NULL)"
|
||||
), {"p": resultado_prefijo + "%"}).all()
|
||||
return {f.resultado_id: (f.valor_id, f.valor_numerico, f.valor_fuente) for f in filas}
|
||||
|
||||
|
||||
# --- the catalog ---
|
||||
|
||||
def test_the_catalog_lists_cama_s_extractable_results_as_provisional():
|
||||
"""Pins down: every CaMa result with captions is extractable and marked provisional, and the catalog still
|
||||
loads with them. Fails if `resultados_extraibles` drops a result or the new keys break `catalogo_desde_toml`."""
|
||||
extraibles = catalogs.resultados_extraibles("cama")
|
||||
assert set(extraibles) >= {"mastografia.densidad", "biopsia.her2", "nota_medica.estadio_clinico"}
|
||||
assert all(e.provisional for e in extraibles.values())
|
||||
catalogo = catalogo_desde_toml(ruta_de_catalogo("cama"), tablas=tablas_de("cama"))
|
||||
assert {r.resultado_id for r in catalogo.resultados} >= set(extraibles)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cambio, error", [
|
||||
(('alias = ["Tipo D"]', 'alias = ["Tipo C"]'), "se escribe igual"),
|
||||
(('etiquetas_fuente = ["Densidad mamaria"]', 'etiquetas_fuente = []'), "lista de textos"),
|
||||
(('etiquetas_fuente = ["Densidad mamaria"]\n', ''), "solo sirven con etiquetas_fuente"),
|
||||
])
|
||||
def test_an_ambiguous_or_incomplete_mapping_is_rejected(catalogo_en, cambio, error):
|
||||
"""Pins down: one spelling on two values, empty captions, or aliases without captions stop the catalog from
|
||||
loading. Fails if a check is dropped and an alias could turn into either of two codes."""
|
||||
ruta = catalogo_en(DENSIDAD.replace(*cambio))
|
||||
with pytest.raises(CatalogoInvalido, match=error):
|
||||
catalogo_desde_toml(ruta, tablas=tablas_de("cama"))
|
||||
|
||||
|
||||
# --- reading text ---
|
||||
|
||||
def test_a_report_s_text_gives_codes_with_their_spelling_and_numbers():
|
||||
"""Pins down: a caption followed by a known spelling gives its code and that spelling as source; a number
|
||||
after its caption gives the number. Fails if the catalog's aliases stop reaching Extraction's field specs."""
|
||||
leido = cama.DE_LA_INTERPRETACION.leer(SimpleNamespace(
|
||||
mast_interpretacion="Densidad mamaria: heterogéneamente densas (C).\nTamaño de la lesión: 14 mm."))
|
||||
assert leido == {"mastografia.densidad": ("C", "heterogéneamente densas"), "mastografia.tamano_lesion_mm": (14.0, None)}
|
||||
|
||||
|
||||
def test_an_unknown_spelling_is_kept_as_its_source_without_a_code():
|
||||
"""Pins down: what follows a caption that matches no alias is kept as source text, with no code. Fails if it's
|
||||
dropped (it couldn't be found and mapped later) or forced into a code."""
|
||||
leido = cama.DE_LA_INTERPRETACION.leer(SimpleNamespace(mast_interpretacion="Densidad mamaria: tipo E"))
|
||||
assert leido["mastografia.densidad"] == (None, "tipo E")
|
||||
|
||||
|
||||
def test_a_stage_is_found_in_a_note_without_a_caption():
|
||||
"""Pins down: a result marked `buscar_en_texto` is found as a mention in narrative text. Fails if the flag
|
||||
stops reaching `scan_free_text`."""
|
||||
leido = cama.DE_LA_NOTA.leer(SimpleNamespace(
|
||||
nm_diagnostico_texto="Carcinoma de mama izquierda, estadio clínico IIA (T2N0M0)", nm_pronostico=None))
|
||||
assert leido["nota_medica.estadio_clinico"] == ("EIIA", "estadio clínico IIA")
|
||||
|
||||
|
||||
def test_a_pathology_pdf_s_text_layer_gives_its_results():
|
||||
"""Pins down: a PDF's text layer is read without OCR and every result on it comes out. Fails if bytes stop
|
||||
going through the PDF reader, or a receptor's percentage stops sharing its captions with the receptor."""
|
||||
leido = cama.DEL_REPORTE_DE_PATOLOGIA.leer(SimpleNamespace(bx_pdf_blob=pdf_de(INFORME_DE_PATOLOGIA[1])))
|
||||
assert {r: v for r, (v, _) in leido.items()} == {
|
||||
"biopsia.tipo_histologico": "DUCTAL_INFILTRANTE", "biopsia.grado_nottingham": "G2",
|
||||
"biopsia.receptor_estrogeno": "POSITIVO", "biopsia.receptor_estrogeno_pct": 90.0,
|
||||
"biopsia.receptor_progesterona": "NEGATIVO", "biopsia.receptor_progesterona_pct": 0.0,
|
||||
"biopsia.her2": "H3", "biopsia.ki67_pct": 25.0,
|
||||
}
|
||||
|
||||
|
||||
def test_no_text_gives_no_values():
|
||||
"""Pins down: a row without text (or a PDF that can't be read) gives every result empty. Fails if an empty
|
||||
text or broken bytes raise during a load."""
|
||||
assert set(cama.DE_LA_NOTA.leer(SimpleNamespace(nm_diagnostico_texto=None, nm_pronostico=None)).values()) == {(None, None)}
|
||||
assert set(cama.DEL_REPORTE_DE_PATOLOGIA.leer(SimpleNamespace(bx_pdf_blob=b"not a pdf")).values()) == {(None, None)}
|
||||
|
||||
|
||||
def test_adding_an_alias_maps_the_same_text_on_the_next_read(catalogo_en):
|
||||
"""Pins down: an unknown spelling becomes a code by adding it to the catalog, with nothing else changed. Fails
|
||||
if the mapping is cached across catalog reads or lives anywhere but the catalog."""
|
||||
fila = SimpleNamespace(mast_interpretacion="Densidad mamaria: tipo E")
|
||||
catalogo_en(DENSIDAD)
|
||||
antes = DesdeTexto("cama", ("mastografia.densidad",), texto=lambda f: f.mast_interpretacion).leer(fila)
|
||||
catalogo_en(DENSIDAD.replace('alias = ["Tipo D"]', 'alias = ["Tipo D", "Tipo E"]'))
|
||||
despues = DesdeTexto("cama", ("mastografia.densidad",), texto=lambda f: f.mast_interpretacion).leer(fila)
|
||||
assert antes["mastografia.densidad"] == (None, "tipo E")
|
||||
assert despues["mastografia.densidad"] == ("D", "tipo E")
|
||||
|
||||
|
||||
# --- the load ---
|
||||
|
||||
def test_the_load_puts_the_extracted_results_in_silver(cargada):
|
||||
"""Pins down: CaMa's load writes the results read from the interpretation, the pathology PDF and the note, and
|
||||
an unknown spelling as an out-of-catalog source. Fails if `cama.DESDE_STAGING` stops wiring a `DesdeTexto`."""
|
||||
with cargada.motor.connect() as con:
|
||||
densidades = sorted(con.execute(text(
|
||||
"SELECT coalesce(valor_id, '?') || ':' || valor_fuente FROM observacion_clinica "
|
||||
"WHERE resultado_id = 'mastografia.densidad' AND valor_fuente IS NOT NULL")).scalars())
|
||||
assert densidades == ["?:tipo E", "C:heterogéneamente densas"]
|
||||
assert observaciones(cargada, "biopsia.her2") == {"biopsia.her2": ("H3", None, "3+")}
|
||||
assert observaciones(cargada, "biopsia.ki67_pct") == {"biopsia.ki67_pct": (None, 25.0, None)}
|
||||
assert observaciones(cargada, "nota_medica.estadio_clinico") == {
|
||||
"nota_medica.estadio_clinico": ("EIIA", None, "estadio clínico IIA")}
|
||||
|
||||
|
||||
def test_the_timeline_carries_the_extracted_results(cargada):
|
||||
"""Pins down: the timeline declares the new results, so H-003's stage, receptors and density are rows of it.
|
||||
Fails if a source line is missing from `cama_linea_de_tiempo.yml`."""
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
filas = cargada.ctx.repos.silver.timeline.read()
|
||||
valores = {(f["tipo"], f["valor_codigo"] or f["valor_numerico"]) for f in filas}
|
||||
assert {("estadio_clinico", "EIIA"), ("her2", "H3"), ("receptor_estrogeno_pct", 90.0),
|
||||
("densidad_mamaria", "C"), ("densidad_mamaria", "tipo E")} <= valores
|
||||
@@ -0,0 +1,60 @@
|
||||
"""What this module covers: the FHIR R4 measure routes of `webapi.fhir` for CaCu and CaMa: every `Measure` of the
|
||||
domain and one `MeasureReport` of each, checked against FHIR's models (`fhir.resources`, R4B), and the patient routes
|
||||
absent outside TEA.
|
||||
|
||||
Fixtures: `domain_client`, a Flask app with only the domain's FHIR blueprint over its fixture database loaded through
|
||||
the cycle up to `event_models` (`conftest.base_de`); needs `DBT_MANIFEST`.
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fhir.resources.R4B import get_fhir_model_class
|
||||
from flask import Flask
|
||||
|
||||
from conftest import base_de
|
||||
from webapi.fhir import fhir_blueprint
|
||||
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", params=["cacu", "cama"])
|
||||
def domain_client(request, tmp_path_factory):
|
||||
manifest = os.environ.get("DBT_MANIFEST")
|
||||
if not manifest:
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
base = base_de(request.param, tmp_path_factory.mktemp(request.param))
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
app = Flask(__name__)
|
||||
app.register_blueprint(fhir_blueprint(request.param, base.dominio, Path(manifest), with_patients=True),
|
||||
url_prefix=f"/{request.param}/fhir")
|
||||
yield request.param, app.test_client()
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def valid(resource: dict) -> dict:
|
||||
get_fhir_model_class(resource["resourceType"]).model_validate(resource)
|
||||
for item in resource.get("entry", ()):
|
||||
get_fhir_model_class(item["resource"]["resourceType"]).model_validate(item["resource"])
|
||||
return resource
|
||||
|
||||
|
||||
def test_every_measure_and_one_report_of_each_are_valid_fhir(domain_client):
|
||||
"""Pins down: each Measure of the domain, and its report for 2025-S1, validate as FHIR R4 resources, compositions
|
||||
with strata included. Fails if the serialization of a scoring, a stratifier or a population breaks FHIR's shape."""
|
||||
domain, client = domain_client
|
||||
measures = valid(client.get(f"/{domain}/fhir/Measure").get_json())
|
||||
assert measures["total"] == {"cacu": 7, "cama": 8}[domain]
|
||||
for item in measures["entry"]:
|
||||
response = client.get(f"/{domain}/fhir/Measure/{item['resource']['id']}/$evaluate-measure?periodo=2025-S1")
|
||||
assert response.status_code in (200, 409), response.get_json()
|
||||
valid(response.get_json())
|
||||
|
||||
|
||||
def test_the_patient_routes_are_tea_s_only(domain_client):
|
||||
"""Pins down: `EpisodeOfCare` exists only on TEA's endpoint; elsewhere it's an OperationOutcome 404. Fails if
|
||||
the patient routes register for another domain."""
|
||||
domain, client = domain_client
|
||||
response = client.get(f"/{domain}/fhir/EpisodeOfCare")
|
||||
assert response.status_code == 404 and valid(response.get_json())["resourceType"] == "OperationOutcome"
|
||||
@@ -0,0 +1,233 @@
|
||||
"""What this module covers: TEA's FHIR R4 endpoint (`/tea/fhir/`): the capability statement, the measures as
|
||||
`Measure` and their answers as `MeasureReport` (one period and several), the follow-up list as `EpisodeOfCare` with
|
||||
its filters, paging and includes, the EEG summary and the patient summary; and that the alterations stay hidden until
|
||||
validated. Every resource is checked against FHIR's models (`fhir.resources`, R4B, which keeps R4's shape for these
|
||||
resources).
|
||||
|
||||
Fixtures: `client`, a Flask app in DEV (`DEV_REVISION`, so the patient routes exist) over TEA's fixture database
|
||||
(`staging.tea`) loaded through the cycle up to `event_models`; needs `DBT_MANIFEST`. `validated`, the switch that
|
||||
shows the alterations (`TEA_ALTERACIONES_VALIDADAS`).
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
from fhir.resources.R4B import get_fhir_model_class
|
||||
|
||||
from conftest import base_de
|
||||
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
mp = pytest.MonkeyPatch()
|
||||
mp.setenv("DEV_REVISION", "pruebas")
|
||||
mp.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False)
|
||||
base = base_de("tea", tmp_path_factory.mktemp("tea_fhir"))
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
base.motor.dispose()
|
||||
mp.undo()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def validated(monkeypatch):
|
||||
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
|
||||
|
||||
|
||||
def valid(resource: dict) -> dict:
|
||||
"""The resource, after checking it and every resource in it against FHIR's model of its type."""
|
||||
get_fhir_model_class(resource["resourceType"]).model_validate(resource)
|
||||
for item in resource.get("entry", ()):
|
||||
get_fhir_model_class(item["resource"]["resourceType"]).model_validate(item["resource"])
|
||||
return resource
|
||||
|
||||
|
||||
def get(client, url: str, status: int = 200) -> dict:
|
||||
response = client.get(url)
|
||||
assert response.status_code == status, response.get_json()
|
||||
assert response.mimetype == "application/fhir+json"
|
||||
return valid(response.get_json())
|
||||
|
||||
|
||||
def resources(bundle: dict, kind: str | None = None, mode: str | None = None) -> list[dict]:
|
||||
return [e["resource"] for e in bundle["entry"] if (kind is None or e["resource"]["resourceType"] == kind)
|
||||
and (mode is None or e.get("search", {}).get("mode") == mode)]
|
||||
|
||||
|
||||
def test_the_capability_statement_lists_the_measures_and_the_patient_routes(client):
|
||||
"""Pins down: `metadata` is a valid CapabilityStatement naming Measure with `evaluate-measure` and, in DEV,
|
||||
EpisodeOfCare with its search parameters. Fails if a route drops out of it."""
|
||||
body = get(client, "/tea/fhir/metadata")
|
||||
kinds = {r["type"]: r for r in body["rest"][0]["resource"]}
|
||||
assert {"Measure", "MeasureReport", "EpisodeOfCare", "Patient"} <= set(kinds)
|
||||
assert {p["name"] for p in kinds["EpisodeOfCare"]["searchParam"]} >= {"date", "etapa", "fecha-etapa", "alteracion"}
|
||||
|
||||
|
||||
def test_the_measures_hide_m30_until_the_alterations_are_validated(client, monkeypatch):
|
||||
"""Pins down: the Measure list has the nine measures without alterations; M30 shows only with the switch on.
|
||||
Fails if M30 leaks before the domain expert validates the references, or the switch stops showing it."""
|
||||
ids = {m["id"] for m in resources(get(client, "/tea/fhir/Measure"))}
|
||||
assert len(ids) == 9 and "M30-resultado-eeg" not in ids
|
||||
assert get(client, "/tea/fhir/Measure/M30_resultado_eeg", 404)["resourceType"] == "OperationOutcome"
|
||||
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
|
||||
assert "M30-resultado-eeg" in {m["id"] for m in resources(get(client, "/tea/fhir/Measure"))}
|
||||
|
||||
|
||||
def test_the_routes_outside_fhir_hide_m30_too(client, monkeypatch):
|
||||
"""Pins down: `/tea/indicadores` neither lists nor answers M30 until the alterations are validated, and does both
|
||||
with the switch on. Fails if the measures answered outside `/tea/fhir/` stop waiting for the validation."""
|
||||
assert "M30_resultado_eeg" not in {m["id"] for m in client.get("/tea/indicadores").get_json()}
|
||||
assert client.get("/tea/indicadores/M30_resultado_eeg?periodos=2025-S1").status_code == 404
|
||||
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
|
||||
assert "M30_resultado_eeg" in {m["id"] for m in client.get("/tea/indicadores").get_json()}
|
||||
assert client.get("/tea/indicadores/M30_resultado_eeg?periodos=2025-S1").status_code == 200
|
||||
|
||||
|
||||
def test_a_measure_carries_what_the_page_needs(client):
|
||||
"""Pins down: a Measure has its absolute canonical, title, scoring (a C2 is a cohort), its strata and its category
|
||||
labels. Fails if the page's catalog fields stop reaching the Measure."""
|
||||
m28 = get(client, "/tea/fhir/Measure/M28_casos_por_estado")
|
||||
assert m28["url"] == "https://isssteleon.org/fhir/Measure/M28-casos-por-estado"
|
||||
assert m28["title"] == "Casos por estatus" and m28["scoring"]["coding"][0]["code"] == "cohort"
|
||||
assert {e["extension"][0]["valueCode"] for e in m28["extension"] if e["url"].endswith("/categoria")} == {
|
||||
"SOLO_MCHAT", "PSICOLOGIA", "NEUROPEDIATRIA", "EEG"}
|
||||
m24 = get(client, "/tea/fhir/Measure/M24_confirmacion_diagnostico")
|
||||
assert m24["group"][0]["stratifier"][0]["code"]["coding"][0]["code"] == "grupo_edad"
|
||||
assert "denominator-exclusion" in {p["code"]["coding"][0]["code"] for p in m24["group"][0]["population"]}
|
||||
|
||||
|
||||
def test_evaluate_measure_answers_one_period_as_a_measure_report(client):
|
||||
"""Pins down: `$evaluate-measure` with periodStart and periodEnd answers that period of `dim_periodo`: M28's first
|
||||
semester of 2025 counts six children by stage, as a cohort whose stages are a stratifier. Fails if the period
|
||||
lookup, the canonical or the C2 shape changes."""
|
||||
report = get(client, "/tea/fhir/Measure/M28_casos_por_estado/$evaluate-measure"
|
||||
"?periodStart=2025-01-01&periodEnd=2025-06-30")
|
||||
assert report["measure"].startswith("https://isssteleon.org/fhir/Measure/M28-casos-por-estado|")
|
||||
(group,) = report["group"]
|
||||
assert group["population"][0]["count"] == 6
|
||||
stages = {s["value"]["coding"][0]["code"]: s["population"][0]["count"] for s in group["stratifier"][0]["stratum"]}
|
||||
assert stages == {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1, "EEG": 2}
|
||||
|
||||
|
||||
def test_a_proportion_reports_its_exclusion_and_its_strata_with_codings(client):
|
||||
"""Pins down: M24's report has the exclusion count (child 2's note without F84.0) and each age group as a coded
|
||||
stratum. Fails if `denominator-exclusion` or the stratum codings drop out."""
|
||||
report = get(client, "/tea/fhir/Measure/M24_confirmacion_diagnostico/$evaluate-measure?periodo=2025-04")
|
||||
counts = {p["code"]["coding"][0]["code"]: p["count"] for p in report["group"][0]["population"]}
|
||||
assert counts == {"denominator": 3, "numerator": 1, "denominator-exclusion": 1}
|
||||
values = {s["value"]["coding"][0]["code"] for s in report["group"][0]["stratifier"][0]["stratum"]}
|
||||
assert {"16_23", "30_36"} <= values
|
||||
|
||||
|
||||
def test_the_measure_report_search_answers_several_periods_with_paging(client):
|
||||
"""Pins down: `MeasureReport?measure=…&tipo-periodo=mes&period=ge…&period=le…` gives one report per month, and
|
||||
`_count` pages them with a `next` link. Fails if the search stops selecting `dim_periodo` by type and dates."""
|
||||
url = ("/tea/fhir/MeasureReport?measure=https://isssteleon.org/fhir/Measure/M26-dias-mchat-ados2"
|
||||
"&tipo-periodo=mes&period=ge2025-01-01&period=le2025-03-31")
|
||||
body = get(client, url)
|
||||
assert body["total"] == 3 and [r["period"]["start"] for r in resources(body)] == [
|
||||
"2025-01-01", "2025-02-01", "2025-03-01"]
|
||||
paged = get(client, url + "&_count=2")
|
||||
assert len(paged["entry"]) == 2 and any(link["relation"] == "next" for link in paged["link"])
|
||||
|
||||
|
||||
def test_the_follow_up_list_is_each_child_s_episode_at_the_cut_off(client):
|
||||
"""Pins down: `EpisodeOfCare?date=le…` gives each child who entered by the cut-off, at its stage then: at 31 May,
|
||||
children 1, 2, 3, 6 and 7 (child 5 enters in June), child 1 finished on its good EEG. A window from 1 June leaves
|
||||
child 1 out. Fails if the episode's status, stage or window drift from the measures' rules."""
|
||||
may = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-05-31"))
|
||||
assert len(may) == 5
|
||||
assert sorted(e["status"] for e in may) == ["active"] * 4 + ["finished"]
|
||||
assert all(e["meta"]["tag"][0]["code"] == "simulado" for e in may)
|
||||
june = resources(get(client, "/tea/fhir/EpisodeOfCare?date=ge2025-06-01&date=le2025-06-30"))
|
||||
assert len(june) == 5 and "finished" in {e["status"] for e in june}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("query", "n"), [
|
||||
("etapa=PSICOLOGIA", 1), ("grupo-edad=24_29", 2), ("mchat=ge12", 3), ("css=ge4", 3),
|
||||
("fecha-etapa=ge2025-06-01&fecha-etapa=le2025-06-30", 2), ("status=finished", 2), ("resultado-eeg=sin-eeg-valido", 3),
|
||||
])
|
||||
def test_the_follow_up_filters(client, query, n):
|
||||
"""Pins down each search parameter at the year's end, over the six children who entered by then: child 3 at
|
||||
psychology; children 2 and 6 in 24 to 29 months (finished episodes still list); M-CHAT of 12 or more for children
|
||||
1, 3 and 6; CSS of 4 or more for 1, 2 and 6; a stage dated in June for child 5 (its M-CHAT; its EEG doesn't count)
|
||||
and child 6 (EEG on 2 June); children 1 and 6 finished; children 2, 3 and 7 without a valid EEG. Fails if a filter
|
||||
stops reading its column."""
|
||||
assert get(client, f"/tea/fhir/EpisodeOfCare?date=le2025-12-31&{query}")["total"] == n
|
||||
|
||||
|
||||
def test_includes_bring_the_patient_its_steps_and_its_study_eeg(client):
|
||||
"""Pins down: `_include` adds each child's Patient (birth date to the month), CarePlan with its steps, M-CHAT,
|
||||
confirmed diagnosis and study EEG as a DiagnosticReport with its quality observations; no metric observation while
|
||||
the alterations are hidden. Fails if an included resource drops out or the alterations leak."""
|
||||
body = get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&status=finished&_include=*")
|
||||
included = resources(body, mode="include")
|
||||
kinds = {r["resourceType"] for r in included}
|
||||
assert {"Patient", "CarePlan", "Observation", "Condition", "DiagnosticReport", "Procedure"} <= kinds
|
||||
assert all(len(p["birthDate"]) == 7 for p in included if p["resourceType"] == "Patient")
|
||||
reports = [r for r in included if r["resourceType"] == "DiagnosticReport"]
|
||||
assert {r["conclusionCode"][0]["coding"][0]["code"] for r in reports} == {"BUENO"}
|
||||
assert all(len(r["result"]) == 5 for r in reports)
|
||||
|
||||
|
||||
def test_the_alteration_filter_waits_for_the_validation(client, monkeypatch):
|
||||
"""Pins down: filtering by an alteration is refused while they're hidden, and works with the switch on (child 1's
|
||||
slow posterior rhythm). Fails if the filter leaks alterations before validation."""
|
||||
assert get(client, "/tea/fhir/EpisodeOfCare?alteracion=ritmo_posterior", 403)["resourceType"] == "OperationOutcome"
|
||||
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
|
||||
assert get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&alteracion=ritmo_posterior")["total"] == 1
|
||||
|
||||
|
||||
def test_the_eeg_summary_counts_valid_eegs_and_alterations_only_when_validated(client, monkeypatch):
|
||||
"""Pins down `$resumen-eeg`: children 1, 5 and 6 with a valid EEG, 2, 3 and 7 without; with the alterations
|
||||
validated, child 1 abnormal (posterior rhythm), 5 and 6 normal. Fails if the summary counts bad EEGs as valid or
|
||||
shows the split before validation."""
|
||||
def counts(body):
|
||||
return {p["name"]: p.get("valueInteger") for p in body["parameter"] if "valueInteger" in p}
|
||||
|
||||
hidden = get(client, "/tea/fhir/EpisodeOfCare/$resumen-eeg?date=le2025-12-31")
|
||||
assert counts(hidden) == {"con_eeg_valido": 3, "sin_eeg_valido": 3}
|
||||
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
|
||||
shown = get(client, "/tea/fhir/EpisodeOfCare/$resumen-eeg?date=le2025-12-31")
|
||||
assert counts(shown) == {"con_eeg_valido": 3, "sin_eeg_valido": 3, "normales": 2, "anormales": 1}
|
||||
|
||||
|
||||
def test_the_patient_summary_shows_the_first_ados2_and_the_study_eeg(client, monkeypatch):
|
||||
"""Pins down `$resumen-tea` for child 1: its Patient, its ADOS-2 (module, CSS, domain totals and items), its first
|
||||
good EEG (20 May, not the bad one of April nor the later one) with its quality; with the alterations validated,
|
||||
the metrics against their reference and the electrode values. Fails if the summary takes another EEG or shows the
|
||||
alterations before validation."""
|
||||
episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&grupo-edad=16_23&status=finished"))
|
||||
(child_1,) = episodes
|
||||
path = f"/tea/fhir/Patient/{child_1['id']}/$resumen-tea"
|
||||
bundle = get(client, path)
|
||||
assert bundle["type"] == "collection"
|
||||
(report,) = resources(bundle, "DiagnosticReport")
|
||||
assert report["effectiveDateTime"] == "2025-05-20" and report["conclusionCode"][0]["coding"][0]["code"] == "BUENO"
|
||||
ados2 = next(o for o in resources(bundle, "Observation") if o["id"].startswith("ados2-"))
|
||||
codes = {c["code"]["coding"][0]["code"] for c in ados2["component"]}
|
||||
assert {"ados2.modulo", "ados2.css", "SA", "RRB", "ados2.sa_b1"} <= codes
|
||||
assert not any("tea-eeg-metrica" in o["code"]["coding"][0]["system"] for o in resources(bundle, "Observation"))
|
||||
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
|
||||
shown = get(client, path)
|
||||
metrics = [o for o in resources(shown, "Observation") if o["code"]["coding"][0]["system"].endswith("tea-eeg-metrica")]
|
||||
rhythm = next(o for o in metrics if o["id"].startswith("ritmo-posterior-"))
|
||||
assert rhythm["interpretation"][0]["coding"][0]["code"] == "L" and rhythm["referenceRange"][0]["low"]["value"] == 4.5
|
||||
electrodes = next(o for o in metrics if o["id"].startswith("electrodos-ritmo-posterior-"))
|
||||
assert [c["code"]["coding"][0]["code"] for c in electrodes["component"]] == ["O1", "O2", "Pz"]
|
||||
|
||||
|
||||
def test_an_unknown_patient_or_parameter_is_an_operation_outcome(client):
|
||||
"""Pins down: errors are OperationOutcomes with the HTTP status: an unknown pseudonym (404), an unknown search
|
||||
parameter (400). Fails if an error goes back to `{"error": …}`."""
|
||||
assert get(client, "/tea/fhir/Patient/P-NADIE/$resumen-tea", 404)["issue"][0]["code"] == "not-found"
|
||||
assert get(client, "/tea/fhir/EpisodeOfCare?color=azul", 400)["issue"][0]["code"] == "invalid"
|
||||
@@ -124,7 +124,8 @@ def test_commit_multi_source_batch_mixes_file_and_sql_within_one_domain(client,
|
||||
|
||||
def test_commit_rejects_a_batch_mixing_domains(client):
|
||||
cacu_source = _csv_source(b"pac_id_hospital,pac_sexo\nH-MIX-1,F\n", target="cacu.Paciente")
|
||||
tea_source = _json_source([{"pac_id_hospital": "T-MIX-1", "pac_sexo": "F"}], target="tea.Pacientes")
|
||||
tea_source = _json_source([{"pac_id_hospital": "T-MIX-1"}], target="tea.Pacientes",
|
||||
column_mapping={"pac_id_hospital": "pac_id_hospital"})
|
||||
|
||||
response = client.post("/imports/commit", json={"sources": [cacu_source, tea_source], "on_conflict": "reject"})
|
||||
assert response.status_code == 400
|
||||
@@ -159,20 +160,21 @@ def test_commit_on_conflict_reject_then_upsert(client):
|
||||
|
||||
def test_commit_upsert_rejected_for_target_without_natural_key(client):
|
||||
source = _json_source(
|
||||
[{"psi_pac_id": 1}], target="tea.EvaluacionPsicologica", column_mapping={"psi_pac_id": "psi_pac_id"}
|
||||
[{"pac_id_hospital": "H-NO-KEY"}], target="cacu.BiometriaHematica",
|
||||
column_mapping={"pac_id_hospital": "pac_id_hospital"},
|
||||
)
|
||||
response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "upsert"})
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_tea_patient_keeps_the_source_id_and_reimport_updates_it(client):
|
||||
mapping = {"pac_id": "pac_id", "pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"}
|
||||
first = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_sexo": "F"}],
|
||||
mapping = {"pac_id": "pac_id", "pac_id_hospital": "pac_id_hospital", "pac_fecha_nacimiento": "pac_fecha_nacimiento"}
|
||||
first = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_fecha_nacimiento": "2023-05-01"}],
|
||||
target="tea.Pacientes", column_mapping=mapping)
|
||||
body = client.post("/imports/commit", json={"sources": [first], "on_conflict": "upsert"}).get_json()
|
||||
assert body["results"][0]["created"] == 1
|
||||
|
||||
again = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_sexo": "M"}],
|
||||
again = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_fecha_nacimiento": "2023-06-01"}],
|
||||
target="tea.Pacientes", column_mapping=mapping)
|
||||
body = client.post("/imports/commit", json={"sources": [again], "on_conflict": "upsert"}).get_json()
|
||||
assert body["results"][0]["created"] == 0
|
||||
@@ -180,20 +182,22 @@ def test_tea_patient_keeps_the_source_id_and_reimport_updates_it(client):
|
||||
|
||||
[paciente] = client.get("/data/tea.Pacientes").get_json()["rows"]
|
||||
assert paciente["pac_id"] == 9001 and paciente["pac_id_hospital"] == "T-SRC-1"
|
||||
assert paciente["pac_sexo"] == "M"
|
||||
assert paciente["pac_fecha_nacimiento"] == "2023-06-01"
|
||||
|
||||
|
||||
def test_an_import_into_a_domain_without_measures_queues_no_recomputation(client):
|
||||
"""The cycle computes no TEA measures, so a TEA import saves its rows and asks for no recomputation.
|
||||
def test_an_import_into_tea_queues_its_recomputation(client):
|
||||
"""Pins down: TEA's measures come from the cycle like CaCu's and CaMa's, so a TEA import saves its rows and
|
||||
asks for a recomputation of TEA.
|
||||
|
||||
Fails if the import queues every domain it writes to: the queue refuses TEA and the import answers 500.
|
||||
Fails if TEA leaves the queue's domains (`DOMAINS` in `webapi.recomputation`).
|
||||
"""
|
||||
source = _json_source([{"pac_id_hospital": "T-NO-RECALC", "pac_sexo": "F"}], target="tea.Pacientes")
|
||||
source = _json_source([{"pac_id_hospital": "T-RECALC"}], target="tea.Pacientes",
|
||||
column_mapping={"pac_id_hospital": "pac_id_hospital"})
|
||||
response = client.post("/imports/commit", json={"sources": [source]})
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["results"][0]["created"] == 1
|
||||
assert body["indicadores_en_recalculo"] is False
|
||||
assert body["indicadores_en_recalculo"] is True
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
- detect -> table/preview -> validate -> commit, for the ruled-table
|
||||
path, writing into `cacu.Paciente`.
|
||||
- detect -> page-image -> regions/extract -> validate -> commit, for the
|
||||
OCR/region path, writing into `tea.Pacientes`.
|
||||
OCR/region path, writing into `cacu.Paciente` as well.
|
||||
"""
|
||||
|
||||
import base64
|
||||
@@ -201,7 +201,7 @@ def test_pdf_page_image_missing_file_returns_400(client):
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# OCR/region path: detect -> page-image -> regions/extract -> validate ->
|
||||
# commit (tea.Pacientes)
|
||||
# commit (cacu.Paciente)
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -241,7 +241,7 @@ def test_pdf_region_round_trip_detect_image_extract_validate_commit(client):
|
||||
|
||||
source = {
|
||||
"source_type": "pdf",
|
||||
"target": "tea.Pacientes",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"},
|
||||
"payload": {
|
||||
"file_base64": base64.b64encode(pdf_bytes).decode(),
|
||||
@@ -261,7 +261,7 @@ def test_pdf_region_round_trip_detect_image_extract_validate_commit(client):
|
||||
commit_body = commit_response.get_json()
|
||||
assert commit_body["ok"] is True
|
||||
result = commit_body["results"][0]
|
||||
assert result["target"] == "tea.Pacientes"
|
||||
assert result["target"] == "cacu.Paciente"
|
||||
assert result["created"] == 1
|
||||
|
||||
|
||||
|
||||
+37
-58
@@ -78,31 +78,35 @@ def test_unknown_engine_and_missing_host_are_rejected(client):
|
||||
# -- EEG -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_edf_preview_maps_onto_eeg_estudio(client):
|
||||
data = {"file": (io.BytesIO(eeg()), "estudio_007.edf"), "target": "tea.EegEstudio"}
|
||||
def test_edf_preview_maps_onto_eeg(client):
|
||||
"""Pins down: an EDF previews as one row with the study id, patient, date, channels and duration read from the
|
||||
file, and its columns suggest the `eeg` fields. Fails if the connector stops reading the header or the column
|
||||
matcher stops pairing them."""
|
||||
data = {"file": (io.BytesIO(eeg()), "estudio_007.edf"), "target": "tea.Eeg"}
|
||||
body = client.post("/imports/sources/file/preview", data=data, content_type="multipart/form-data").get_json()
|
||||
[row] = body["sample_rows"]
|
||||
assert row["id_registro_laboratorio"] == "LAB-778"
|
||||
assert row["paciente"] == "EXP-0042"
|
||||
assert row["fecha_estudio"] == "2024-01-15"
|
||||
assert row["edad_meses"] == 56.0
|
||||
assert row["ritmo_base_frecuencia"] == pytest.approx(10, abs=0.3)
|
||||
assert "3 canales a 128 Hz" in row["descripcion_senal"]
|
||||
assert row["canales"] == 3
|
||||
assert row["duracion_min"] == pytest.approx(8 / 60, abs=0.05)
|
||||
suggested = {m["source_column"]: m["target_field"] for m in body["suggested_mapping"]}
|
||||
assert suggested["estudio"] == "eeg_estudio"
|
||||
assert suggested["fecha_estudio"] == "eeg_fecha_estudio"
|
||||
assert suggested["ritmo_base_frecuencia"] == "eeg_ritmo_base_frecuencia"
|
||||
assert suggested["canales"] == "eeg_canales"
|
||||
|
||||
|
||||
def test_several_edf_files_load_into_eeg_estudio_with_the_file(client):
|
||||
def test_several_edf_files_load_into_eeg_with_the_file(client):
|
||||
"""Pins down: several EDF files commit as one `eeg` row each, keyed by the lab's study id (or the file name),
|
||||
with the file stored. Fails if the commit drops the file or the key."""
|
||||
source = {
|
||||
"source_type": "edf",
|
||||
"target": "tea.EegEstudio",
|
||||
"target": "tea.Eeg",
|
||||
"column_mapping": {
|
||||
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
|
||||
"fecha_estudio": "eeg_fecha_estudio",
|
||||
"duracion_min": "eeg_duracion_min",
|
||||
"ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia",
|
||||
"canales": "eeg_canales",
|
||||
"estudio": "eeg_estudio",
|
||||
},
|
||||
"payload": {"files": [{"name": "a.edf", "file_base64": b64(eeg())}, {"name": "b.edf", "file_base64": b64(eeg(recording="sin datos"))}]},
|
||||
@@ -110,19 +114,21 @@ def test_several_edf_files_load_into_eeg_estudio_with_the_file(client):
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 2, result
|
||||
|
||||
from persistance.tea import eeg_estudio_repository
|
||||
from persistance.tea import eeg_repository
|
||||
|
||||
stored = {row.eeg_id_registro_laboratorio: row for row in eeg_estudio_repository.list()}
|
||||
stored = {row.eeg_id_registro_laboratorio: row for row in eeg_repository.list()}
|
||||
assert set(stored) == {"LAB-778", "b"}
|
||||
assert stored["LAB-778"].eeg_canales == 3
|
||||
assert stored["LAB-778"].eeg_estudio[:8].strip() == b"0"
|
||||
assert stored["LAB-778"].eeg_fecha_estudio == date(2024, 1, 15)
|
||||
|
||||
|
||||
def test_eeg_estudio_rejects_a_file_mne_cannot_read():
|
||||
def test_eeg_rejects_a_file_mne_cannot_read():
|
||||
"""Pins down: `eeg_estudio` only takes a file MNE can open. Fails if the schema stops validating the EDF."""
|
||||
from webapi.imports.schemas.service import validate_rows
|
||||
from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema
|
||||
from webapi.imports.schemas.tea.eeg import EegImportSchema
|
||||
|
||||
result = validate_rows(EegEstudioImportSchema, [{"eeg_estudio": b"definitely not an EDF file" * 20}])
|
||||
result = validate_rows(EegImportSchema, [{"eeg_estudio": b"definitely not an EDF file" * 20}])
|
||||
[row] = result.rejected
|
||||
assert row.errors[0].field == "eeg_estudio"
|
||||
|
||||
@@ -228,73 +234,48 @@ def test_patient_scattered_across_csv_and_scanned_forms_is_merged(client):
|
||||
|
||||
|
||||
EEG_REPORT = text_pdf(
|
||||
[
|
||||
["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-778", "Fecha de estudio: 15/01/2024",
|
||||
"Simetría: SIMETRICO", "Médico interpreta: Dra. Ruiz"],
|
||||
["Conclusión: trazado con actividad de base simétrica,", "sin eventos epileptiformes durante el registro."],
|
||||
],
|
||||
image_on_page=2,
|
||||
[["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-778", "Fecha de estudio: 15/01/2024"]],
|
||||
)
|
||||
|
||||
# A second study id, distinct from LAB-778 (already used by an earlier test
|
||||
# against this module-scoped client/database), for the merge test below.
|
||||
EEG_REPORT_2 = text_pdf(
|
||||
[
|
||||
["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-900", "Fecha de estudio: 20/02/2024",
|
||||
"Simetría: SIMETRICO", "Médico interpreta: Dra. Ruiz"],
|
||||
["Conclusión: trazado con actividad de base simétrica,", "sin eventos epileptiformes durante el registro."],
|
||||
],
|
||||
[["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-900", "Fecha de estudio: 20/02/2024"]],
|
||||
)
|
||||
|
||||
|
||||
def test_eeg_report_scattered_across_pages_merges_into_one_record(client):
|
||||
"""The report's demographics are on page 1, its conclusion on page 2 —
|
||||
non-contiguous fields the same way a multi-file upload would be, just
|
||||
without the file boundary. Proves the extractor merges by the lab's own
|
||||
study id, not by page adjacency."""
|
||||
def test_an_eeg_report_gives_its_study_id_and_date(client):
|
||||
"""Pins down: a report read with NLP lands on `eeg` by the lab's own study id, with the study date. Fails if
|
||||
the extractor stops keying EEG records by `eeg_id_registro_laboratorio` or stops reading the date."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"files": [{"name": "reporte.pdf", "file_base64": b64(EEG_REPORT)}], "target": "tea.EegEstudio"},
|
||||
json={"files": [{"name": "reporte.pdf", "file_base64": b64(EEG_REPORT)}], "target": "tea.Eeg"},
|
||||
).get_json()
|
||||
assert body["key_field"] == "eeg_id_registro_laboratorio"
|
||||
[record] = body["records"]
|
||||
assert record["key"] == "LAB-778"
|
||||
assert record["sources"] == [{"document": "reporte.pdf", "page_numbers": [1, 2]}]
|
||||
assert record["fields"]["eeg_simetria"]["value"] == "SIMETRICO"
|
||||
assert record["fields"]["eeg_fecha_estudio"]["value"] == "2024-01-15"
|
||||
assert "sin eventos epileptiformes" in record["fields"]["eeg_conclusion_texto"]["value"]
|
||||
assert [image["page_number"] for image in record["images"]] == [2]
|
||||
|
||||
|
||||
def test_eeg_file_and_its_scanned_report_merge_into_one_eeg_estudio_row(client):
|
||||
"""The EDF connector computes signal fields from the file itself; the
|
||||
report PDF (read with NLP, across two pages) carries the clinician's
|
||||
interpretation. Different sources, same study — `eeg_id_registro_
|
||||
laboratorio` (the lab's own code, read from the EDF header by one side
|
||||
and from the report text by the other) is what lets them land on one
|
||||
`eeg_estudio` row instead of two half-populated ones."""
|
||||
def test_eeg_file_and_its_scanned_report_merge_into_one_eeg_row(client):
|
||||
"""Pins down: the EDF and its report, two sources of the same study, land on one `eeg` row through the lab's
|
||||
study id (read from the EDF header by one and from the report text by the other). Fails if
|
||||
`merge_duplicates` stops matching them on `eeg_id_registro_laboratorio`."""
|
||||
edf_source = {
|
||||
"source_type": "edf",
|
||||
"target": "tea.EegEstudio",
|
||||
"target": "tea.Eeg",
|
||||
"label": "estudio.edf",
|
||||
"column_mapping": {
|
||||
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
|
||||
"fecha_estudio": "eeg_fecha_estudio",
|
||||
"duracion_min": "eeg_duracion_min",
|
||||
"ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia",
|
||||
"estudio": "eeg_estudio",
|
||||
},
|
||||
"payload": {"files": [{"name": "estudio.edf", "file_base64": b64(eeg(recording="Startdate 20-FEB-2024 LAB-900 Tec_Ruiz Nihon_Kohden"))}]},
|
||||
}
|
||||
document_source = _document_source(
|
||||
[("reporte.pdf", EEG_REPORT_2)],
|
||||
"tea.EegEstudio",
|
||||
{
|
||||
"eeg_id_registro_laboratorio": "eeg_id_registro_laboratorio",
|
||||
"eeg_simetria": "eeg_simetria",
|
||||
"eeg_conclusion_texto": "eeg_conclusion_texto",
|
||||
"eeg_medico_interpreta": "eeg_medico_interpreta",
|
||||
},
|
||||
"tea.Eeg",
|
||||
{"eeg_id_registro_laboratorio": "eeg_id_registro_laboratorio", "eeg_fecha_estudio": "eeg_fecha_estudio"},
|
||||
)
|
||||
body = client.post(
|
||||
"/imports/commit", json={"sources": [edf_source, document_source], "merge_duplicates": True}
|
||||
@@ -303,16 +284,14 @@ def test_eeg_file_and_its_scanned_report_merge_into_one_eeg_estudio_row(client):
|
||||
assert edf_result["created"] == 1, body
|
||||
assert doc_result["merged"] == 1, body # absorbed into the EDF source's row, not inserted again
|
||||
|
||||
from persistance.tea import eeg_estudio_repository
|
||||
from persistance.tea import eeg_repository
|
||||
|
||||
[row] = eeg_estudio_repository.list(eeg_id_registro_laboratorio="LAB-900")
|
||||
[row] = eeg_repository.list(eeg_id_registro_laboratorio="LAB-900")
|
||||
# From the EDF file itself:
|
||||
assert row.eeg_duracion_min is not None
|
||||
assert row.eeg_estudio[:8].strip() == b"0"
|
||||
# From the scanned report, on the very same row:
|
||||
assert row.eeg_simetria == "SIMETRICO"
|
||||
assert "sin eventos epileptiformes" in row.eeg_conclusion_texto
|
||||
assert row.eeg_medico_interpreta == "Dra. Ruiz"
|
||||
# From the report, on the very same row:
|
||||
assert row.eeg_fecha_estudio == date(2024, 2, 20)
|
||||
|
||||
|
||||
def test_citologia_table_and_scanned_report_merge_on_the_order_number(client):
|
||||
|
||||
@@ -27,7 +27,7 @@ CONSULTA = text("""
|
||||
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", params=["cacu", "cama"])
|
||||
@pytest.fixture(scope="module", params=["cacu", "cama", "tea"])
|
||||
def bases(request, tmp_path_factory):
|
||||
proyecto = request.param
|
||||
carpeta = tmp_path_factory.mktemp(proyecto)
|
||||
|
||||
@@ -84,10 +84,11 @@ def test_las_definiciones_son_las_del_manifiesto_de_dbt(base):
|
||||
measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows."""
|
||||
resumen = base.run("definitions")["definitions"]
|
||||
|
||||
# CaCu: three strata and its seven measures; CaMa: its seven measures, without strata.
|
||||
assert resumen["definitions"] == {"cacu": 10, "cama": 7}[base.proyecto]
|
||||
# CaCu: three strata and its seven measures; CaMa: the five strata of its invasive cancers and its eight measures;
|
||||
# TEA: the age group and its ten measures.
|
||||
assert resumen["definitions"] == {"cacu": 10, "cama": 13, "tea": 11}[base.proyecto]
|
||||
# Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado.
|
||||
assert base.dominio.cat_measure_repository.count() == 7 # seven measures in each domain
|
||||
assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 8, "tea": 10}[base.proyecto]
|
||||
assert base.run("definitions")["definitions"]["borradas"] == 0
|
||||
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ def antes(deps: dict[str, set[str]], paso: str) -> set[str]:
|
||||
return previos
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu", "cama"])
|
||||
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
|
||||
def test_cada_paso_corre_despues_de_lo_que_necesita(proyecto):
|
||||
deps = dependencias(proyecto)
|
||||
assert deps["migrate"] == set()
|
||||
|
||||
@@ -26,6 +26,7 @@ from sqlmodel import select
|
||||
CAMBIO = {
|
||||
"cacu": ("citologiacervical", "cit_calidad_especimen", "INSATISFACTORIO"),
|
||||
"cama": ("mastografia", "mast_calidad_imagen", "OTRA CALIDAD"),
|
||||
"tea": ("mchat", "mch_puntaje", 19),
|
||||
}
|
||||
CORTE = date(2025, 12, 31)
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ def test_ningun_modulo_fuera_de_repositorios_abre_sesiones(modulo):
|
||||
assert not PROHIBIDO.findall(texto), f"{modulo} abre su propia sesión: debe usar ctx.repos"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True)])
|
||||
@pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True), ("tea", True)])
|
||||
def test_cada_proyecto_tiene_sus_repositorios(proyecto, con_cohortes):
|
||||
repos = repositories_of(proyecto)
|
||||
assert (repos.gold.cohorts is not None) == con_cohortes
|
||||
|
||||
+10
-9
@@ -48,14 +48,15 @@ def test_tea_pacientes_schema_is_fully_optional():
|
||||
assert schema.pac_id_hospital is None
|
||||
|
||||
|
||||
def test_tea_pacientes_schema_coerces_sexo_from_bare_enum_no_alias_dict():
|
||||
schema = PacientesImportSchema(pac_sexo="f")
|
||||
assert schema.pac_sexo == "F"
|
||||
def test_tea_neuropediatrics_note_takes_icd10_with_or_without_the_dot():
|
||||
"""Pins down: the note's ICD-10 is upper-cased and accepted with or without its dot; anything else is
|
||||
rejected. Fails if the pattern of `neu_cie_codigo` changes."""
|
||||
from webapi.imports.schemas.tea.evaluacion_neuropediatrica import EvaluacionNeuropediatricaImportSchema as Nota
|
||||
|
||||
|
||||
def test_tea_pacientes_schema_coerces_parentesco():
|
||||
schema = PacientesImportSchema(pac_parentesco="hijo")
|
||||
assert schema.pac_parentesco == "HIJO"
|
||||
assert Nota(neu_cie_codigo=" f84.0 ").neu_cie_codigo == "F84.0"
|
||||
assert Nota(neu_cie_codigo="F840").neu_cie_codigo == "F840"
|
||||
with pytest.raises(ValidationError):
|
||||
Nota(neu_cie_codigo="autismo")
|
||||
|
||||
|
||||
def test_classify_error_missing():
|
||||
@@ -243,5 +244,5 @@ def test_catalog_aliases_for_values_the_indicator_kit_uses():
|
||||
cito = CitologiaCervicalImportSchema(pac_id_hospital="H", cit_celulas_escamosas="NEGATIVO")
|
||||
assert cito.cit_celulas_escamosas == "NORMAL"
|
||||
assert CamaOrdenes(pac_id_hospital="H", ord_numero_hospital=1, ord_tipo_estudio="MASTOGRAFIA").ord_tipo_estudio == "MASTOGRAFIA"
|
||||
assert TeaOrdenes(ord_tipo_estudio="POTENCIALES_EVOCADOS").ord_tipo_estudio == "POTENCIALES_EVOCADOS_AUDITIVOS"
|
||||
assert TeaOrdenes(ord_tipo_estudio=" evaluacion_psicologica_tea ").ord_tipo_estudio == "EVALUACION_PSICOLOGICA_TEA"
|
||||
assert TeaOrdenes(ord_tipo_estudio="electroencefalograma").ord_tipo_estudio == "EEG"
|
||||
assert TeaOrdenes(ord_tipo_estudio=" evaluacion_psicologica_tea ").ord_tipo_estudio == "ADOS2"
|
||||
|
||||
@@ -5,7 +5,8 @@ from pydantic import ValidationError
|
||||
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
from webapi.imports.schemas.cama.ordenes_estudio import OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema
|
||||
from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema
|
||||
from webapi.imports.schemas.tea.ados2 import Ados2ImportSchema
|
||||
from webapi.imports.schemas.tea.mchat import MchatImportSchema
|
||||
from webapi.imports.schemas.cacu.biopsia_cervical import BiopsiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cacu.episodio_clinico import EpisodioClinicoImportSchema
|
||||
|
||||
@@ -48,11 +49,21 @@ def test_cama_ordenes_estudio_requires_numero_hospital_and_coerces_tipo_estudio(
|
||||
assert schema.ord_tipo_estudio == "BIOPSIA_CHICA"
|
||||
|
||||
|
||||
# TEA entity with a bare Enum field (no *_ALIAS dict), so the schema builds
|
||||
# a Catalog from the Enum alone, as in tea/pacientes.py.
|
||||
def test_tea_eeg_estudio_coerces_simetria_from_bare_enum_no_alias_dict():
|
||||
schema = EegEstudioImportSchema(eeg_simetria="simetrico")
|
||||
assert schema.eeg_simetria == "SIMETRICO"
|
||||
def test_tea_ados2_coerces_module_and_classification_aliases():
|
||||
"""Pins down: the ADOS-2's module comes from the bare enum and its classification takes the old spelling
|
||||
`NO_TEA`. Fails if either catalog stops normalizing case or aliases."""
|
||||
schema = Ados2ImportSchema(ado_modulo="modulo_1", ado_clasificacion="no_tea")
|
||||
assert (schema.ado_modulo, schema.ado_clasificacion) == ("MODULO_1", "NO_ESPECTRO")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("schema", "field", "value"), [
|
||||
(MchatImportSchema, "mch_puntaje", 21), (Ados2ImportSchema, "ado_css", 0), (Ados2ImportSchema, "ado_sa_b1", 4),
|
||||
])
|
||||
def test_tea_scores_out_of_their_range_are_rejected(schema, field, value):
|
||||
"""Pins down: an M-CHAT score above 20, a CSS below 1 and an ADOS-2 item above 3 are validation errors. Fails if
|
||||
a bound of `Bounded` is dropped from the schemas."""
|
||||
with pytest.raises(ValidationError):
|
||||
schema(**{field: value})
|
||||
|
||||
|
||||
# CaCu entity with a real *_ALIAS-backed field (GRADO_CIN_ALIAS).
|
||||
|
||||
+14
-14
@@ -76,31 +76,31 @@ def test_tea_children_keep_pointing_at_their_parents_source_ids(tea_client):
|
||||
sources = [
|
||||
_json([{"pac_id": 1, "pac_id_hospital": "T-1"}], "tea.Pacientes"),
|
||||
_json([{"ord_id": "ord-1", "ord_pac_id": 1, "ord_id_hospital": "O-1"}], "tea.OrdenesEstudio"),
|
||||
_json([{"psi_id": "psi-1", "psi_ord_id": "ord-1", "psi_pac_id": 1}], "tea.EvaluacionPsicologica"),
|
||||
_json([{"ins_psi_id": "psi-1", "ins_instrumento": "ADOS-2"}], "tea.InstrumentoAplicado"),
|
||||
_json([{"eeg_id": "eeg-1", "eeg_ord_id": "ord-1", "eeg_id_registro_laboratorio": "L-1"}], "tea.EegEstudio"),
|
||||
_json([{"seg_eeg_id": "eeg-1", "seg_duracion_s": 30}], "tea.EegSegmento"),
|
||||
_json([{"ado_id": "ado-1", "ado_ord_id": "ord-1", "ado_pac_id": 1}], "tea.Ados2"),
|
||||
_json([{"eeg_id": "eeg-1", "eeg_ord_id": "ord-1", "eeg_id_registro_laboratorio": "L-1"}], "tea.Eeg"),
|
||||
_json([{"met_id": "met-1", "met_eeg_id": "eeg-1", "met_codigo": "RITMO_POSTERIOR", "met_valor": 5.5}], "tea.EegMetrica"),
|
||||
_json([{"mel_met_id": "met-1", "mel_electrodo": "O1", "mel_valor": -1.2}], "tea.EegMetricaElectrodo"),
|
||||
]
|
||||
body = tea_client.post("/imports/commit", json={"sources": sources}).get_json()
|
||||
assert all(r["rejected"] == 0 for r in body["results"]), body
|
||||
|
||||
from persistance.tea import (
|
||||
eeg_estudio_repository,
|
||||
eeg_segmento_repository,
|
||||
evaluacion_psicologica_repository,
|
||||
instrumento_aplicado_repository,
|
||||
ados2_repository,
|
||||
eeg_metrica_electrodo_repository,
|
||||
eeg_metrica_repository,
|
||||
eeg_repository,
|
||||
)
|
||||
|
||||
assert eeg_estudio_repository.get(eeg_segmento_repository.list()[0].seg_eeg_id).eeg_id_registro_laboratorio == "L-1"
|
||||
evaluacion = evaluacion_psicologica_repository.get(instrumento_aplicado_repository.list()[0].ins_psi_id)
|
||||
assert evaluacion.psi_ord_id == "ord-1"
|
||||
metrica = eeg_metrica_repository.get(eeg_metrica_electrodo_repository.list()[0].mel_met_id)
|
||||
assert eeg_repository.get(metrica.met_eeg_id).eeg_id_registro_laboratorio == "L-1"
|
||||
assert ados2_repository.get("ado-1").ado_ord_id == "ord-1"
|
||||
|
||||
|
||||
def test_tea_rows_without_a_source_id_get_one(tea_client):
|
||||
eeg = _json([{"eeg_id_registro_laboratorio": "L-SIN-ID"}], "tea.EegEstudio")
|
||||
eeg = _json([{"eeg_id_registro_laboratorio": "L-SIN-ID"}], "tea.Eeg")
|
||||
assert tea_client.post("/imports/commit", json={"sources": [eeg]}).get_json()["results"][0]["created"] == 1
|
||||
|
||||
from persistance.tea import eeg_estudio_repository
|
||||
from persistance.tea import eeg_repository
|
||||
|
||||
[fila] = [e for e in eeg_estudio_repository.list() if e.eeg_id_registro_laboratorio == "L-SIN-ID"]
|
||||
[fila] = [e for e in eeg_repository.list() if e.eeg_id_registro_laboratorio == "L-SIN-ID"]
|
||||
assert len(fila.eeg_id) == 36
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
"""What this module covers: TEA's ten measures answered on request from dbt's semantic layer, on hand-written
|
||||
expectations for the synthetic children of `staging.tea`, period by period: who each period counts (the children in
|
||||
the screening during it, at their stage at its end, leaving after the period of their good EEG), the day counts, the
|
||||
EEGs by quality and the alterations of each child's first good EEG.
|
||||
|
||||
Fixtures: `base`, TEA's fixture database through the cycle up to `event_models` (dbt's views); `manifest`, dbt's
|
||||
`manifest.json` (`DBT_MANIFEST`; skipped without it). The expectations are worked out by hand from the children's
|
||||
dates in `staging/tea.py`; each test says which child makes each number.
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import replace
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
from sqlmodel import select
|
||||
|
||||
import staging.tea as fixture
|
||||
from conftest import base_de
|
||||
from core.tea.models import Ados2, Eeg, EegMetrica, Mchat
|
||||
from webapi.compositions import answer_composition, composition_definitions
|
||||
from webapi.durations import answer_duration, duration_definitions
|
||||
from webapi.metrics import Question, answer, measure_definitions
|
||||
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def manifest():
|
||||
path = os.environ.get("DBT_MANIFEST")
|
||||
if not path:
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
return Path(path)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def base(tmp_path_factory, manifest):
|
||||
"""The seven children of `staging.tea`, loaded once, with dbt's TEA views created."""
|
||||
base = base_de("tea", tmp_path_factory.mktemp("tea"))
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
yield replace(base, ctx=replace(base.ctx, allow_undecided=True))
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def repositories(base) -> dict:
|
||||
d = base.dominio
|
||||
return {"parameters": d.def_parametro_repository, "periods": d.dim_periodo_repository,
|
||||
"history": d.history_repository, "queries": d.dbt_query_repository, "allow_undecided": True}
|
||||
|
||||
|
||||
def composition(base, manifest, measure_id, period, **question):
|
||||
url = f"tea/{measure_id}"
|
||||
result = answer_composition("tea", composition_definitions(manifest)[url], Question(url, period, **question),
|
||||
**repositories(base))
|
||||
return {k: v for k, v in result.categories.items() if v}
|
||||
|
||||
|
||||
def proportion(base, manifest, measure_id, period, **question):
|
||||
url = f"tea/{measure_id}"
|
||||
return answer("tea", measure_definitions(manifest)[url], Question(url, period, **question), **repositories(base))
|
||||
|
||||
|
||||
def duration(base, manifest, measure_id, period):
|
||||
url = f"tea/{measure_id}"
|
||||
return answer_duration("tea", duration_definitions(manifest)[url], Question(url, period), **repositories(base))
|
||||
|
||||
|
||||
STAGES = {
|
||||
"2025-01": {"SOLO_MCHAT": 2},
|
||||
"2025-02": {"SOLO_MCHAT": 1, "PSICOLOGIA": 2},
|
||||
"2025-03": {"PSICOLOGIA": 2, "NEUROPEDIATRIA": 1},
|
||||
"2025-04": {"PSICOLOGIA": 2, "NEUROPEDIATRIA": 2},
|
||||
"2025-05": {"SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 1, "EEG": 1},
|
||||
"2025-06": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1, "EEG": 1},
|
||||
"2025-07": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1},
|
||||
"2025-12": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1},
|
||||
"2025-S1": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1, "EEG": 2},
|
||||
"2025-S2": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("period", sorted(STAGES))
|
||||
def test_m28_counts_every_child_in_the_screening_at_its_stage_at_the_period_s_end(base, manifest, period):
|
||||
"""Pins down M28: a period counts every cohort child who entered by its end and hadn't finished before its start,
|
||||
at the furthest step reached by its end, whether or not anything of theirs happened in it. Child 1 is at
|
||||
psychology in February and March's stage moves with its note; it reaches EEG in May and is gone from June. Child 2
|
||||
stays at neuropediatrics all year; child 5 stays at M-CHAT (no ADOS-2); child 6 reaches EEG on its note's day,
|
||||
2 June; child 4 (39 months) never counts; child 7 (no birth date) counts from May.
|
||||
|
||||
Fails if the population goes back to the children with a fact in the period, if a child stops leaving after the
|
||||
period of its good EEG, or if a step stops needing the previous one."""
|
||||
assert composition(base, manifest, "M28_casos_por_estado", period) == STAGES[period]
|
||||
|
||||
|
||||
def test_m28_an_event_cut_off_leaves_out_what_came_after_it(base, manifest):
|
||||
"""Pins down: facts dated after the event cut-off don't count. With a cut-off of 10 May, child 1's good EEG of
|
||||
20 May isn't there, so May counts it at neuropediatrics. Fails if the status rows stop applying the cut-off."""
|
||||
assert composition(base, manifest, "M28_casos_por_estado", "2025-05", event_cutoff=date(2025, 5, 10)) == {
|
||||
"SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 2}
|
||||
|
||||
|
||||
RESULTS = {
|
||||
"2025-01": {"EN_PROCESO": 2},
|
||||
"2025-03": {"CONFIRMADO": 1, "EN_PROCESO": 2},
|
||||
"2025-04": {"CONFIRMADO": 1, "EN_PROCESO": 2},
|
||||
"2025-06": {"CONFIRMADO": 1, "EN_PROCESO": 3},
|
||||
"2025-07": {"EN_PROCESO": 3},
|
||||
"2025-S1": {"CONFIRMADO": 2, "EN_PROCESO": 3},
|
||||
"2025-S2": {"EN_PROCESO": 3},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("period", sorted(RESULTS))
|
||||
def test_m23_counts_the_confirmed_and_in_process_but_not_a_note_without_f84_0(base, manifest, period):
|
||||
"""Pins down M23: the confirmed (a F84.0 note by the period's end) and those in process (no note yet). Child 2's
|
||||
note says F84 without the subcode: from April it's out of M23, though still in the screening. Child 5's F84.0 note
|
||||
of July doesn't confirm it without the ADOS-2: it stays in process. Fails if F84 counts as a confirmation, if a
|
||||
note without F84.0 counts as in process, or if a note counts before the psychology step."""
|
||||
assert composition(base, manifest, "M23_pacientes_evaluados", period) == RESULTS[period]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("period", "numerator", "denominator", "excluded"), [
|
||||
("2025-03", 1, 3, 0), ("2025-04", 1, 3, 1), ("2025-06", 1, 4, 1), ("2025-07", 0, 3, 1), ("2025-S1", 2, 5, 1),
|
||||
])
|
||||
def test_m24_is_the_confirmed_out_of_the_confirmed_and_in_process(base, manifest, period, numerator, denominator,
|
||||
excluded):
|
||||
"""Pins down M24: confirmed over confirmed plus in process, with child 2 (a note without F84.0) as its exclusion
|
||||
from April. In July child 5's F84.0 note, without the ADOS-2, leaves it in process. Fails if the denominator takes
|
||||
the children without TEA, the exclusion stops being counted, or a note confirms without the psychology step."""
|
||||
result = proportion(base, manifest, "M24_confirmacion_diagnostico", period)
|
||||
assert (result.numerator, result.denominator, result.excluded) == (numerator, denominator, excluded)
|
||||
|
||||
|
||||
def test_m24_is_stratified_by_the_age_group_at_the_first_m_chat(base, manifest):
|
||||
"""Pins down: the age group is the child's at its first M-CHAT, one per child, the page's windows. In March, child
|
||||
1 (19 months) is confirmed, child 2 (26) and child 3 (35) are in process. Fails if the stratum goes back to the age
|
||||
at the period's start or loses a window."""
|
||||
result = proportion(base, manifest, "M24_confirmacion_diagnostico", "2025-03")
|
||||
strata = {v: (c.numerator, c.denominator) for v, c in result.strata["grupo_edad"].items()}
|
||||
assert strata == {"16_23": (1, 1), "24_29": (0, 1), "30_36": (0, 1)}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("period", "with_eeg", "without_eeg", "confirmed"), [
|
||||
("2025-03", 0, 1, 1), ("2025-05", 1, 0, 1), ("2025-06", 1, 0, 1), ("2025-07", 0, 0, 0),
|
||||
("2025-S1", 2, 0, 2), ("2025-S2", 0, 0, 0),
|
||||
])
|
||||
def test_m21_and_m22_split_the_confirmed_by_a_good_eeg_by_the_period_s_end(base, manifest, period, with_eeg,
|
||||
without_eeg, confirmed):
|
||||
"""Pins down M21 and its complement M22: of the confirmed at the period's end, those whose chain reached a good EEG
|
||||
by then. Child 1 is confirmed in March without its EEG (20 May), and with it in May; child 5 has a F84.0 note and
|
||||
a good EEG in July but no ADOS-2, so it isn't confirmed and July has nobody. Fails if the EEG is read beyond the
|
||||
period's end, or the note or the EEG count outside the chain."""
|
||||
m21 = proportion(base, manifest, "M21_diagnosticados_con_eeg", period)
|
||||
m22 = proportion(base, manifest, "M22_diagnosticados_sin_eeg", period)
|
||||
assert (m21.numerator, m21.denominator) == (with_eeg, confirmed)
|
||||
assert (m22.numerator, m22.denominator) == (without_eeg, confirmed)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("measure_id", "period", "initial", "n", "median"), [
|
||||
("M26_dias_mchat_ados2", "2025-01", 2, 0, None),
|
||||
("M26_dias_mchat_ados2", "2025-02", 3, 2, 20.0),
|
||||
("M26_dias_mchat_ados2", "2025-03", 3, 3, 26.0),
|
||||
("M26_dias_mchat_ados2", "2025-S1", 6, 4, 20.5),
|
||||
("M27_dias_ados2_diagnostico", "2025-S1", 6, 3, 40.0),
|
||||
("M25_dias_mchat_diagnostico", "2025-S1", 6, 2, 59.5),
|
||||
("M25_dias_mchat_diagnostico", "2025-S2", 4, 0, None),
|
||||
])
|
||||
def test_the_day_counts_take_the_period_s_children_whose_interval_ended_by_its_end(base, manifest, measure_id, period,
|
||||
initial, n, median):
|
||||
"""Pins down M26, M27 and M25: every child the period counts is in the initial population; those whose interval
|
||||
ended by the period's end have days (repeated in each period that counts them), the rest count as without event.
|
||||
In February, child 1 (26 days) and child 3 (14) have their ADOS-2 and child 2 doesn't yet. Child 5's F84.0 note of
|
||||
1 July gives no days without the ADOS-2. Fails if the value is read beyond the period's end or the
|
||||
population goes back to the facts in the period."""
|
||||
result = duration(base, manifest, measure_id, period)
|
||||
assert (result.initial, result.n, result.median) == (initial, n, median)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("period", "expected"), [
|
||||
("2025-04", {"MALO": 1}), ("2025-05", {"BUENO": 1}), ("2025-09", {"BUENO": 1}),
|
||||
("2025-S1", {"BUENO": 2, "MALO": 1}), ("2025-S2", {"BUENO": 2}),
|
||||
])
|
||||
def test_m29_counts_the_period_s_eegs_good_or_bad(base, manifest, period, expected):
|
||||
"""Pins down M29: the EEGs of the cohort's children dated in the period, by exam, good or bad. Child 1's bad EEG of
|
||||
April and its second good one of September count; so does child 5's, though its chain never reaches it. Fails if
|
||||
M29 stops counting exams, or a bad EEG stops showing."""
|
||||
assert composition(base, manifest, "M29_calidad_eeg", period) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("period", "total", "ritmo_posterior"), [
|
||||
("2025-05", (1, 1), (1, 1)), ("2025-06", (0, 1), (0, 1)), ("2025-S1", (1, 2), (1, 2)), ("2025-S2", (0, 1), (0, 1)),
|
||||
])
|
||||
def test_m30_reads_the_alterations_of_each_child_s_first_good_eeg(base, manifest, period, total, ritmo_posterior):
|
||||
"""Pins down M30: of the children whose first good EEG falls in the period, those with an alteration in it, in
|
||||
total and in one group per alteration. Child 1's EEG of 20 May has a slow posterior rhythm (3.2 Hz at 23 months,
|
||||
against 4.5 to 7.0); its second good EEG of September doesn't count. Fails if a later EEG counts, or the groups
|
||||
stop being answered one by one."""
|
||||
result = proportion(base, manifest, "M30_resultado_eeg", period)
|
||||
assert (result.numerator, result.denominator) == total
|
||||
assert (result.groups["ritmo_posterior"].numerator, result.groups["ritmo_posterior"].denominator) == ritmo_posterior
|
||||
assert result.groups["husos_sueno_n2"].numerator == 0
|
||||
|
||||
|
||||
def test_m30_read_back_from_the_history_keeps_its_groups(base, manifest):
|
||||
"""Pins down: asking again reads the stored answer, groups included. Fails if a stored answer loses its groups or
|
||||
counts every group's units in the total."""
|
||||
first = proportion(base, manifest, "M30_resultado_eeg", "2025-S1")
|
||||
again = proportion(base, manifest, "M30_resultado_eeg", "2025-S1")
|
||||
assert again.stored_before and (again.numerator, again.denominator) == (first.numerator, first.denominator)
|
||||
assert again.groups == first.groups
|
||||
|
||||
|
||||
def test_a_knowledge_cut_off_leaves_out_a_step_loaded_later(tmp_path, manifest):
|
||||
"""Pins down: a step known after the knowledge cut-off doesn't move the child. Child 1's good EEG and its metrics
|
||||
arrive in a second load; asked as of the first load, May still counts child 1 at neuropediatrics and it hasn't
|
||||
left in June. Fails if the status rows stop applying the knowledge cut-off to the steps or to the exit."""
|
||||
def without_the_good_eeg(session):
|
||||
fixture.insertar(session)
|
||||
session.flush()
|
||||
for model, key in ((EegMetrica, "met_eeg_id"), (Eeg, "eeg_id")):
|
||||
for row in session.exec(select(model).where(getattr(model, key) == "eeg-1b")):
|
||||
session.delete(row)
|
||||
|
||||
base = base_de("tea", tmp_path, without_the_good_eeg)
|
||||
try:
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
with base.motor.begin() as connection:
|
||||
(first_load,) = connection.execute(text("select max(fin) from carga")).one()
|
||||
known = datetime.fromisoformat(str(first_load)).replace(tzinfo=timezone.utc)
|
||||
with base.staging() as session:
|
||||
session.add(Eeg(eeg_id="eeg-1b", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 5, 20), eeg_con_sueno=1,
|
||||
eeg_canales=19, eeg_duracion_min=25.0, eeg_canales_amplitud=0,
|
||||
eeg_canales_alta_frecuencia=1, eeg_canales_correlacion=0, eeg_canales_sin_senal=0,
|
||||
eeg_ruido_linea_db=3.5))
|
||||
session.commit()
|
||||
base.run("load", allow_undecided=True)
|
||||
later = replace(base, ctx=replace(base.ctx, allow_undecided=True))
|
||||
assert composition(later, manifest, "M28_casos_por_estado", "2025-05", knowledge_cutoff=known) == {
|
||||
"SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 2}
|
||||
assert composition(later, manifest, "M28_casos_por_estado", "2025-06", knowledge_cutoff=known)[
|
||||
"NEUROPEDIATRIA"] == 2
|
||||
assert composition(later, manifest, "M28_casos_por_estado", "2025-05")["EEG"] == 1
|
||||
finally:
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def test_a_knowledge_cut_off_keeps_what_was_known_when_an_earlier_fact_arrives_later(tmp_path, manifest):
|
||||
"""Pins down: an answer as of a load doesn't change when a later load brings an earlier-dated fact. A second load
|
||||
adds an ADOS-2 of 20 Feb for child 3 (its known one is of 28 Feb) and an M-CHAT of 1 Apr for child 7 (its known
|
||||
one is of 1 May). Asked as of the first load, March still counts child 3 at psychology and May still counts
|
||||
child 7; asked as of now, child 7 is in the screening from April. Fails if a child's first fact is chosen among
|
||||
every load's facts and then dropped for being known after the cut-off."""
|
||||
base = base_de("tea", tmp_path)
|
||||
try:
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
with base.motor.begin() as connection:
|
||||
(first_load,) = connection.execute(text("select max(fin) from carga")).one()
|
||||
known = datetime.fromisoformat(str(first_load)).replace(tzinfo=timezone.utc)
|
||||
with base.staging() as session:
|
||||
session.add(Ados2(ado_id="ado-3-earlier", ado_pac_id=3, ado_fecha=date(2025, 2, 20), ado_modulo="MODULO_2",
|
||||
ado_css=2))
|
||||
session.add(Mchat(mch_id="mch-7-earlier", mch_pac_id=7, mch_fecha=date(2025, 4, 1), mch_puntaje=7))
|
||||
session.commit()
|
||||
base.run("load", allow_undecided=True)
|
||||
later = replace(base, ctx=replace(base.ctx, allow_undecided=True))
|
||||
for period in ("2025-03", "2025-05"):
|
||||
assert composition(later, manifest, "M28_casos_por_estado", period, knowledge_cutoff=known) == STAGES[period]
|
||||
assert composition(later, manifest, "M28_casos_por_estado", "2025-04") == {
|
||||
"SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 2}
|
||||
finally:
|
||||
base.motor.dispose()
|
||||
@@ -1,15 +1,15 @@
|
||||
version = 1
|
||||
revision = 3
|
||||
revision = 5
|
||||
requires-python = ">=3.12"
|
||||
resolution-markers = [
|
||||
"python_full_version >= '3.14' and sys_platform == 'win32'",
|
||||
"python_full_version >= '3.14' and sys_platform == 'emscripten'",
|
||||
"python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'",
|
||||
"python_full_version == '3.13.*' and sys_platform == 'win32'",
|
||||
"python_full_version < '3.13' and sys_platform == 'win32'",
|
||||
"python_full_version == '3.13.*' and sys_platform == 'emscripten'",
|
||||
"python_full_version < '3.13' and sys_platform == 'emscripten'",
|
||||
"python_full_version == '3.13.*' and sys_platform != 'emscripten' and sys_platform != 'win32'",
|
||||
"python_full_version < '3.13' and sys_platform == 'win32'",
|
||||
"python_full_version < '3.13' and sys_platform == 'emscripten'",
|
||||
"python_full_version < '3.13' and sys_platform != 'emscripten' and sys_platform != 'win32'",
|
||||
]
|
||||
|
||||
@@ -768,6 +768,30 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/45/2a/101012d82931d9de3855384e1667e49c0e07a0048e3868f9fec1697293a9/fastapi-0.161.1-py3-none-any.whl", hash = "sha256:a1363080cf9aeedecd99f4e1a23669d7e77542227f6536f4d7bbd59f07ecaa94", size = 149049, upload-time = "2026-10-22T22:22:06.139Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fhir-core"
|
||||
version = "1.1.12"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "pydantic" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/f7/1b/0072a6ec7716df558bbcc134611df02d8ba22e286cbf64070fe6190f9d75/fhir_core-1.1.12.tar.gz", hash = "sha256:8f1674104ff575ff00dd2b4ff7ed6caf043d6d5a306990536e1b6ee2ccd06732", size = 40415, upload-time = "2026-10-18T20:20:47.011Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/67/22/4a118da089892195692b5e3519992708dc67fb84d49fddee5d9a1f3f43b4/fhir_core-1.1.12-py2.py3-none-any.whl", hash = "sha256:2ae218ed43b32705ce1c37150253942bd88350248a77f66e8ca2b6c3ed8263b2", size = 34264, upload-time = "2026-10-18T20:20:45.735Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fhir-resources"
|
||||
version = "8.3.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "fhir-core" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/98/06/331d78ad6db6903be6b912701c44b32af295279907b3a2e6ad6c2e2f97b1/fhir_resources-8.3.0.tar.gz", hash = "sha256:bdfd1c7bd1b89bfa269c1f435727771f6c632cd857e2848221713b3f8b9f46e8", size = 1617996, upload-time = "2026-07-03T15:23:54.01Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/d1/86/32914542064b8aee77ac48142f8a1955df78da4eb905dd41697d26941d21/fhir_resources-8.3.0-py2.py3-none-any.whl", hash = "sha256:151e6c9b4336e36383cc2aaf2067a6f112a420fce1c7bd289182e55dd950871b", size = 2288069, upload-time = "2026-07-03T15:23:51.97Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flask"
|
||||
version = "3.1.3"
|
||||
@@ -3284,6 +3308,7 @@ sql-drivers = [
|
||||
|
||||
[package.dev-dependencies]
|
||||
dev = [
|
||||
{ name = "fhir-resources" },
|
||||
{ name = "pytest" },
|
||||
{ name = "reportlab" },
|
||||
]
|
||||
@@ -3314,6 +3339,7 @@ provides-extras = ["sql-drivers"]
|
||||
|
||||
[package.metadata.requires-dev]
|
||||
dev = [
|
||||
{ name = "fhir-resources", specifier = ">=8" },
|
||||
{ name = "pytest", specifier = ">=8.0.0" },
|
||||
{ name = "reportlab", specifier = ">=4.0" },
|
||||
]
|
||||
|
||||
+7
-3
@@ -78,11 +78,15 @@ def create_app() -> Flask:
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
|
||||
from webapi.fhir import fhir_blueprint
|
||||
from webapi.kpis import kpis_blueprint
|
||||
|
||||
for domain in ("cacu", "cama"):
|
||||
app.register_blueprint(kpis_blueprint(domain, import_module(f"persistance.{domain}"),
|
||||
Path(os.environ["DBT_MANIFEST"])), url_prefix=f"/{domain}")
|
||||
for domain in ("cacu", "cama", "tea"):
|
||||
repositories, manifest = import_module(f"persistance.{domain}"), Path(os.environ["DBT_MANIFEST"])
|
||||
app.register_blueprint(kpis_blueprint(domain, repositories, manifest), url_prefix=f"/{domain}")
|
||||
# The same measures in FHIR R4, and TEA's patients only in DEV (simulated data).
|
||||
app.register_blueprint(fhir_blueprint(domain, repositories, manifest, with_patients=in_dev()),
|
||||
url_prefix=f"/{domain}/fhir")
|
||||
# Patient-level follow-up list and individual risk: only in DEV, with simulated data.
|
||||
if in_dev():
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
@@ -29,6 +29,7 @@ from webapi.metrics import (
|
||||
MeasureQueries,
|
||||
Population,
|
||||
Question,
|
||||
StatusAtEnd,
|
||||
Stratum,
|
||||
_population,
|
||||
_semantic_model_of,
|
||||
@@ -80,6 +81,8 @@ class CompositionDefinition:
|
||||
basis: str
|
||||
rules: dict[str, str]
|
||||
strata: tuple[Stratum, ...]
|
||||
population: StatusAtEnd | None = None
|
||||
meta: dict = dataclasses.field(default_factory=dict, compare=False, hash=False)
|
||||
|
||||
@property
|
||||
def measure_id(self) -> str:
|
||||
@@ -121,6 +124,7 @@ def composition_definitions(manifest: Path) -> dict[str, CompositionDefinition]:
|
||||
tuple((b["valor"], b.get("menor_que")) for b in rule.get("bandas", ()))),
|
||||
group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})),
|
||||
strata=tuple(Stratum.of(name, s) for name, s in meta.get("estratos", {}).items()),
|
||||
population=StatusAtEnd.of(meta.get("poblacion")), meta=meta,
|
||||
)
|
||||
return definitions
|
||||
|
||||
|
||||
+10
-2
@@ -6,7 +6,8 @@ cut-offs apply to, and the horizon: a unit without a value whose horizon hasn't
|
||||
measured yet, so it's left out of the initial population. Days are differences of `dim_fecha.dia_num`, computed in
|
||||
dbt's event model; the cut-off's day is looked up the same way. Quartiles are ANSI (`inclusive_quartiles`).
|
||||
|
||||
The event cut-off defaults to the day of the last load, as the horizon needs a day to count to.
|
||||
The event cut-off defaults to the day of the last load, as the horizon needs a day to count to. With a population at
|
||||
the period's end (`webapi.metrics.StatusAtEnd`), a unit's interval has a value only if it ended by the period's end.
|
||||
"""
|
||||
|
||||
import dataclasses
|
||||
@@ -28,6 +29,7 @@ from webapi.metrics import (
|
||||
MeasureQueries,
|
||||
Population,
|
||||
Question,
|
||||
StatusAtEnd,
|
||||
_population,
|
||||
_semantic_model_of,
|
||||
key_of,
|
||||
@@ -90,6 +92,8 @@ class DurationDefinition:
|
||||
rules: dict[str, str]
|
||||
improvement_notation: str | None = None
|
||||
strata: tuple = ()
|
||||
population: StatusAtEnd | None = None
|
||||
meta: dict = dataclasses.field(default_factory=dict, compare=False, hash=False)
|
||||
|
||||
@property
|
||||
def measure_id(self) -> str:
|
||||
@@ -127,7 +131,8 @@ def duration_definitions(manifest: Path) -> dict[str, DurationDefinition]:
|
||||
rule["horizonte"].get("regla"), rule["horizonte"]["dia_inicio"],
|
||||
int(rule["horizonte"]["dias"]) if "dias" in rule["horizonte"] else None),
|
||||
group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})),
|
||||
improvement_notation=meta.get("improvement_notation"),
|
||||
improvement_notation=meta.get("improvement_notation"), population=StatusAtEnd.of(meta.get("poblacion")),
|
||||
meta=meta,
|
||||
)
|
||||
return definitions
|
||||
|
||||
@@ -145,6 +150,9 @@ class DurationQueries(MeasureQueries):
|
||||
o, q = self.d.observation, self.q
|
||||
conditions = [self._column(o.value).is_not(None)]
|
||||
conditions += [self._column(n) <= q.event_cutoff.isoformat() for n in o.dated_at]
|
||||
if self.status is not None:
|
||||
# Counted at the period's end: the interval has to have ended by then.
|
||||
conditions += [self._column(n) < self.events.c.periodo_fin for n in o.dated_at]
|
||||
if q.knowledge_cutoff is not None:
|
||||
conditions += [self._column(n) <= q.knowledge_cutoff for n in o.known_at]
|
||||
return and_(*conditions)
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
"""A domain's FHIR R4 endpoint, `/<domain>/fhir/`: its measures and, for TEA, its patients' screening.
|
||||
|
||||
GET metadata CapabilityStatement
|
||||
GET Measure, Measure/<id> the measures (dbt's definitions)
|
||||
GET Measure/<id>/$evaluate-measure one period: periodStart and periodEnd, or `periodo`
|
||||
GET MeasureReport?measure=&periodo=|period= several periods (one report each), with `tipo-periodo`
|
||||
POST Measure/$recalcular queues the domain's recomputation
|
||||
GET CodeSystem, CodeSystem/<id>, ValueSet/<id> the project's code systems
|
||||
GET EpisodeOfCare, EpisodeOfCare/$resumen-eeg TEA's follow-up list and its EEG summary (DEV only)
|
||||
GET Patient/<pseudonym>/$resumen-tea TEA's patient summary (DEV only)
|
||||
|
||||
Every question of a measure takes `corte_evento` and `corte_conocimiento` as in `webapi.kpis`. Errors are
|
||||
`OperationOutcome`s. Patient data are served only in DEV, on simulated data, each resource tagged `simulado`.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from flask import Blueprint, request
|
||||
from werkzeug.exceptions import HTTPException
|
||||
|
||||
from webapi.fhir.common import FHIR_VERSION, canonical, entry, fhir, outcome, page, searchset, simulated_data
|
||||
from webapi.fhir.measures import fhir_id, labels, measure_report, measure_resource, measure_url
|
||||
from webapi.fhir.terminology import code_systems, metric_value_set
|
||||
from webapi.kpis import ANSWERS, _date, _datetime, _last_load, definitions_of, scoring_of
|
||||
from webapi.metrics import Question, UndecidedRule
|
||||
|
||||
TEA_SEARCH = ("status", "date", "etapa", "fecha-etapa", "grupo-edad", "mchat", "css", "resultado-eeg", "alteracion")
|
||||
|
||||
|
||||
def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients: bool = False,
|
||||
now: Callable[[], datetime] = lambda: datetime.now(timezone.utc)) -> Blueprint:
|
||||
"""The blueprint of a domain, to register with `url_prefix="/<domain>/fhir"`. `repositories` is the domain's
|
||||
`persistance.<domain>` module; `with_patients` adds TEA's patient routes (only in DEV)."""
|
||||
blueprint = Blueprint(f"{project}_fhir", __name__)
|
||||
titles = labels(manifest)
|
||||
patients = with_patients and project == "tea"
|
||||
|
||||
def definitions() -> dict:
|
||||
"""The domain's measures by their FHIR id; `definition()` also takes the dbt id."""
|
||||
return {fhir_id(d): d for d in definitions_of(project, manifest).values()}
|
||||
|
||||
def definition_of(measure_id: str):
|
||||
return definitions().get(measure_id.replace("_", "-"))
|
||||
|
||||
def measure(definition) -> dict:
|
||||
title, description = titles.get(definition.metric, (definition.measure_id, ""))
|
||||
return measure_resource(definition, title, description)
|
||||
|
||||
@blueprint.app_errorhandler(HTTPException)
|
||||
def http_error(error: HTTPException):
|
||||
"""Under `/<domain>/fhir/`, an error is an `OperationOutcome`, also for a route that doesn't exist there;
|
||||
elsewhere, Flask's own answer."""
|
||||
if "/fhir/" not in request.path and not request.path.endswith("/fhir"):
|
||||
return error
|
||||
code = {404: "not-found", 405: "not-supported"}.get(error.code, "exception")
|
||||
return outcome(error.code, code, error.description or error.name)
|
||||
|
||||
@blueprint.get("/metadata")
|
||||
def capability_statement():
|
||||
resources = [
|
||||
{"type": "Measure", "interaction": [{"code": "read"}, {"code": "search-type"}],
|
||||
"operation": [{"name": "evaluate-measure", "definition": "http://hl7.org/fhir/OperationDefinition/Measure-evaluate-measure"},
|
||||
{"name": "recalcular", "definition": canonical("OperationDefinition/recalcular")}]},
|
||||
{"type": "MeasureReport", "interaction": [{"code": "search-type"}],
|
||||
"searchParam": [{"name": n, "type": t} for n, t in (("measure", "reference"), ("period", "date"),
|
||||
("periodo", "token"), ("tipo-periodo", "token"))]},
|
||||
{"type": "CodeSystem", "interaction": [{"code": "read"}, {"code": "search-type"}]},
|
||||
]
|
||||
if patients:
|
||||
resources += [
|
||||
{"type": "EpisodeOfCare", "interaction": [{"code": "search-type"}],
|
||||
"searchParam": [{"name": n, "definition": canonical(f"SearchParameter/episode-{n}"),
|
||||
"type": "date" if n in ("date", "fecha-etapa") else
|
||||
"number" if n in ("mchat", "css") else "token"} for n in TEA_SEARCH],
|
||||
"searchInclude": ["*"],
|
||||
"operation": [{"name": "resumen-eeg", "definition": canonical("OperationDefinition/resumen-eeg")}]},
|
||||
{"type": "Patient", "operation": [{"name": "resumen-tea",
|
||||
"definition": canonical("OperationDefinition/resumen-tea")}]},
|
||||
{"type": "ValueSet", "interaction": [{"code": "read"}]},
|
||||
]
|
||||
return fhir({"resourceType": "CapabilityStatement", "status": "active", "date": now().date().isoformat(),
|
||||
"kind": "instance", "fhirVersion": FHIR_VERSION, "format": ["application/fhir+json"],
|
||||
"implementation": {"description": f"ISSSTELEON, {project.upper()}", "url": request.url_root},
|
||||
"rest": [{"mode": "server", "resource": resources}]})
|
||||
|
||||
@blueprint.get("/Measure")
|
||||
def measures():
|
||||
found = [measure(d) for _, d in sorted(definitions().items())]
|
||||
if url := request.args.get("url"):
|
||||
found = [m for m in found if m["url"] == url]
|
||||
count, offset = page()
|
||||
return fhir(searchset([entry(m) for m in found[offset:offset + count]], len(found), count, offset))
|
||||
|
||||
@blueprint.get("/Measure/<measure_id>")
|
||||
def read_measure(measure_id: str):
|
||||
definition = definition_of(measure_id)
|
||||
if definition is None:
|
||||
return outcome(404, "not-found", f"no hay un indicador {measure_id!r}")
|
||||
return fhir(measure(definition))
|
||||
|
||||
def ask(definition, period, event_cutoff, knowledge_cutoff):
|
||||
question = Question(definition.url, period.periodo_id, event_cutoff, knowledge_cutoff)
|
||||
answer_of, _ = ANSWERS[scoring_of(definition)]
|
||||
result = answer_of(project, definition, question, parameters=repositories.def_parametro_repository,
|
||||
periods=repositories.dim_periodo_repository, history=repositories.history_repository,
|
||||
queries=repositories.dbt_query_repository)
|
||||
return measure_report(definition, question, result, period, now())
|
||||
|
||||
def cutoffs():
|
||||
return (_date(request.args.get("corte_evento")),
|
||||
_datetime(request.args.get("corte_conocimiento")) or _last_load(repositories))
|
||||
|
||||
@blueprint.get("/Measure/<measure_id>/$evaluate-measure")
|
||||
def evaluate_measure(measure_id: str):
|
||||
definition = definition_of(measure_id)
|
||||
if definition is None:
|
||||
return outcome(404, "not-found", f"no hay un indicador {measure_id!r}")
|
||||
try:
|
||||
event_cutoff, knowledge_cutoff = cutoffs()
|
||||
period = _period_asked(repositories)
|
||||
except ValueError as error:
|
||||
return outcome(400, "invalid", str(error))
|
||||
except LookupError as error:
|
||||
return outcome(404, "not-found", str(error))
|
||||
try:
|
||||
return fhir(ask(definition, period, event_cutoff, knowledge_cutoff))
|
||||
except UndecidedRule as error:
|
||||
return outcome(409, "business-rule", str(error))
|
||||
|
||||
@blueprint.get("/MeasureReport")
|
||||
def measure_reports():
|
||||
asked = request.args.get("measure", "")
|
||||
by_url = {measure_url(d): d for d in definitions().values()}
|
||||
definition = by_url.get(asked.split("|")[0]) or definition_of(asked)
|
||||
if definition is None:
|
||||
return outcome(400, "required", "falta `measure` (el canónico o el id de un indicador)")
|
||||
try:
|
||||
event_cutoff, knowledge_cutoff = cutoffs()
|
||||
periods = _periods_searched(repositories)
|
||||
count, offset = page()
|
||||
except ValueError as error:
|
||||
return outcome(400, "invalid", str(error))
|
||||
except LookupError as error:
|
||||
return outcome(404, "not-found", str(error))
|
||||
try:
|
||||
reports = [ask(definition, p, event_cutoff, knowledge_cutoff) for p in periods[offset:offset + count]]
|
||||
except UndecidedRule as error:
|
||||
return outcome(409, "business-rule", str(error))
|
||||
return fhir(searchset([entry(r) for r in reports], len(periods), count, offset))
|
||||
|
||||
@blueprint.post("/Measure/$recalcular")
|
||||
def recompute():
|
||||
from webapi.recomputation import RecomputationQueue
|
||||
|
||||
RecomputationQueue().request_run(project)
|
||||
return outcome(202, "informational", f"se pidió recalcular los indicadores de {project}", severity="information")
|
||||
|
||||
@blueprint.get("/CodeSystem")
|
||||
def code_system_search():
|
||||
systems = list(code_systems(project).values())
|
||||
return fhir(searchset([entry(s) for s in systems], len(systems), len(systems) or 1, 0))
|
||||
|
||||
@blueprint.get("/CodeSystem/<system_id>")
|
||||
def read_code_system(system_id: str):
|
||||
system = code_systems(project).get(system_id)
|
||||
return fhir(system) if system else outcome(404, "not-found", f"no hay un sistema de códigos {system_id!r}")
|
||||
|
||||
if patients:
|
||||
_patient_routes(blueprint, repositories, now)
|
||||
return blueprint
|
||||
|
||||
|
||||
def _period_asked(repositories):
|
||||
"""The `dim_periodo` row the question names: `periodo`, or `periodStart` and `periodEnd` (inclusive)."""
|
||||
if periodo := request.args.get("periodo"):
|
||||
period = repositories.dim_periodo_repository.get(periodo)
|
||||
if period is None:
|
||||
raise LookupError(f"no hay un periodo {periodo!r}")
|
||||
return period
|
||||
start, end = request.args.get("periodStart"), request.args.get("periodEnd")
|
||||
if not (start and end):
|
||||
raise ValueError("falta el periodo: `periodStart` y `periodEnd`, o `periodo`")
|
||||
start, end = date.fromisoformat(start), date.fromisoformat(end)
|
||||
for period in repositories.dim_periodo_repository.list(limit=10000, inicio=start):
|
||||
if period.fin - timedelta(days=1) == end:
|
||||
return period
|
||||
raise LookupError(f"no hay un periodo de {start} a {end}")
|
||||
|
||||
|
||||
def _periods_searched(repositories) -> list:
|
||||
"""The periods of a `MeasureReport` search: `periodo` (comma-separated ids), or the periods of `tipo-periodo`
|
||||
within `period=ge…` and `period=le…`."""
|
||||
if ids := [p for p in request.args.get("periodo", "").split(",") if p]:
|
||||
periods = [repositories.dim_periodo_repository.get(i) for i in ids]
|
||||
if missing := [i for i, p in zip(ids, periods) if p is None]:
|
||||
raise LookupError(f"no hay un periodo {missing[0]!r}")
|
||||
return periods
|
||||
kind = request.args.get("tipo-periodo")
|
||||
if not kind:
|
||||
raise ValueError("falta `periodo` o `tipo-periodo` con `period`")
|
||||
low, high = date.min, date.max
|
||||
for value in request.args.getlist("period"):
|
||||
if value.startswith("ge"):
|
||||
low = date.fromisoformat(value[2:])
|
||||
elif value.startswith("le"):
|
||||
high = date.fromisoformat(value[2:])
|
||||
else:
|
||||
raise ValueError(f"`period` admite ge y le: {value!r}")
|
||||
found = repositories.dim_periodo_repository.list(limit=10000, tipo=kind)
|
||||
return sorted((p for p in found if p.inicio >= low and p.fin - timedelta(days=1) <= high), key=lambda p: p.inicio)
|
||||
|
||||
|
||||
def _bound(name: str) -> tuple[float | None, float | None]:
|
||||
"""A number search parameter's bounds: `mchat=ge8&mchat=le20`, or one exact value."""
|
||||
low = high = None
|
||||
for value in request.args.getlist(name):
|
||||
if value.startswith("ge"):
|
||||
low = float(value[2:])
|
||||
elif value.startswith("le"):
|
||||
high = float(value[2:])
|
||||
else:
|
||||
low = high = float(value)
|
||||
return low, high
|
||||
|
||||
|
||||
def _dates(name: str) -> tuple[date | None, date | None]:
|
||||
low = high = None
|
||||
for value in request.args.getlist(name):
|
||||
if value.startswith("ge"):
|
||||
low = date.fromisoformat(value[2:])
|
||||
elif value.startswith("le"):
|
||||
high = date.fromisoformat(value[2:])
|
||||
else:
|
||||
low = high = date.fromisoformat(value)
|
||||
return low, high
|
||||
|
||||
|
||||
def _patient_routes(blueprint: Blueprint, repositories, now) -> None:
|
||||
from webapi.fhir import tea
|
||||
|
||||
queries = repositories.dbt_query_repository
|
||||
|
||||
def matching():
|
||||
"""The episodes the search's parameters select, at its cut-off (`date=le…`, by default today)."""
|
||||
unknown = [k for k in request.args if not k.startswith("_") and k not in TEA_SEARCH]
|
||||
if unknown:
|
||||
raise ValueError(f"parámetro de búsqueda no admitido: {unknown[0]!r}")
|
||||
if request.args.get("alteracion") and not tea.alterations_validated():
|
||||
raise PermissionError("las alteraciones del EEG no se muestran hasta validar sus referencias")
|
||||
since, cutoff = _dates("date")
|
||||
cutoff = cutoff or now().date()
|
||||
stage_from, stage_to = _dates("fecha-etapa")
|
||||
mchat, css = _bound("mchat"), _bound("css")
|
||||
|
||||
def within(value, bounds):
|
||||
low, high = bounds
|
||||
return value is not None and (low is None or value >= low) and (high is None or value <= high)
|
||||
|
||||
found = []
|
||||
for e in tea.episodes(queries, cutoff):
|
||||
stage = e.stage
|
||||
if since is not None and e.finished and stage[1] < since:
|
||||
continue
|
||||
if (status := request.args.get("status")) and status != ("finished" if e.finished else "active"):
|
||||
continue
|
||||
if (etapa := request.args.get("etapa")) and (stage is None or stage[0] not in etapa.split(",")):
|
||||
continue
|
||||
if (stage_from or stage_to) and (stage is None or not within(stage[1].toordinal(), (
|
||||
stage_from and stage_from.toordinal(), stage_to and stage_to.toordinal()))):
|
||||
continue
|
||||
if (group := request.args.get("grupo-edad")) and e.child["grupo_edad"] not in group.split(","):
|
||||
continue
|
||||
if request.args.getlist("mchat") and not within(e.child["mchat"], mchat):
|
||||
continue
|
||||
if request.args.getlist("css") and not within(e.child["css_ados2"], css):
|
||||
continue
|
||||
if result := request.args.get("resultado-eeg"):
|
||||
shown = e.eeg_result if tea.alterations_validated() else (
|
||||
"sin-eeg-valido" if e.eeg_result == "sin-eeg-valido" else "valido")
|
||||
if shown not in result.split(","):
|
||||
continue
|
||||
if (alteration := request.args.get("alteracion")) and alteration not in e.alterations():
|
||||
continue
|
||||
found.append(e)
|
||||
return sorted(found, key=lambda e: e.pseudonym)
|
||||
|
||||
@blueprint.get("/EpisodeOfCare")
|
||||
def episodes_of_care():
|
||||
try:
|
||||
found = matching()
|
||||
count, offset = page()
|
||||
except ValueError as error:
|
||||
return tea_outcome(400, "invalid", error)
|
||||
except PermissionError as error:
|
||||
return tea_outcome(403, "forbidden", error)
|
||||
simulated = simulated_data()
|
||||
shown = found[offset:offset + count]
|
||||
entries = [entry(tea.episode_of_care(e, simulated)) for e in shown]
|
||||
if request.args.get("_include"):
|
||||
entries += [entry(r, "include") for e in shown for r in _included(tea, queries, e, simulated)]
|
||||
return fhir(searchset(entries, len(found), count, offset))
|
||||
|
||||
@blueprint.get("/EpisodeOfCare/$resumen-eeg")
|
||||
def eeg_summary():
|
||||
try:
|
||||
found = matching()
|
||||
except ValueError as error:
|
||||
return tea_outcome(400, "invalid", error)
|
||||
except PermissionError as error:
|
||||
return tea_outcome(403, "forbidden", error)
|
||||
valid = [e for e in found if e.eeg_result != "sin-eeg-valido"]
|
||||
parameters = [{"name": "con_eeg_valido", "valueInteger": len(valid)},
|
||||
{"name": "sin_eeg_valido", "valueInteger": len(found) - len(valid)}]
|
||||
if tea.alterations_validated():
|
||||
by_alteration: dict[str, int] = {}
|
||||
for e in valid:
|
||||
for code in e.alterations():
|
||||
by_alteration[code] = by_alteration.get(code, 0) + 1
|
||||
parameters += [{"name": "normales", "valueInteger": sum(e.eeg_result == "normal" for e in valid)},
|
||||
{"name": "anormales", "valueInteger": sum(e.eeg_result == "anormal" for e in valid)},
|
||||
*({"name": "por_alteracion", "part": [{"name": "alteracion", "valueCode": code},
|
||||
{"name": "pacientes", "valueInteger": n}]}
|
||||
for code, n in sorted(by_alteration.items()))]
|
||||
return fhir({"resourceType": "Parameters", "parameter": parameters})
|
||||
|
||||
@blueprint.get("/Patient/<pseudonym>/$resumen-tea")
|
||||
def patient_summary(pseudonym: str):
|
||||
pac_id = tea.patient_of(queries, pseudonym)
|
||||
if pac_id is None:
|
||||
return outcome(404, "not-found", f"no hay un paciente {pseudonym!r}")
|
||||
return fhir(tea.patient_summary(queries, pac_id, now().date(), simulated_data()))
|
||||
|
||||
@blueprint.get("/ValueSet/tea-alteracion")
|
||||
def alteration_types():
|
||||
return fhir(metric_value_set())
|
||||
|
||||
|
||||
def tea_outcome(status: int, code: str, error: Exception):
|
||||
return outcome(status, code, str(error))
|
||||
|
||||
|
||||
def _included(tea, queries, e, simulated: bool) -> list[dict]:
|
||||
"""What an episode's search includes: its patient, its steps, its M-CHAT, its diagnosis and its study EEG."""
|
||||
from sqlalchemy import select
|
||||
|
||||
persons = tea._rows(queries, select(tea.PERSONS).where(tea.PERSONS.c.pac_id == e.child["pac_id"]))
|
||||
resources = [tea.patient(e.child["pac_id"], persons[0]["fecha_nacimiento"] if persons else None, simulated),
|
||||
tea.care_plan(e, simulated)]
|
||||
resources += [r for r in (tea.mchat_observation(e, simulated), tea.condition(e, simulated)) if r]
|
||||
if (eeg := e.study_eeg()) is not None:
|
||||
resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated)
|
||||
return resources
|
||||
@@ -0,0 +1,93 @@
|
||||
"""What every FHIR R4 answer of the WebApi shares: the media type, errors as `OperationOutcome`, search bundles with
|
||||
their paging links, the simulated-data tag and the project's canonical URLs."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from flask import Response, request
|
||||
|
||||
FHIR_VERSION = "4.0.1"
|
||||
MEDIA_TYPE = "application/fhir+json"
|
||||
BASE = "https://isssteleon.org/fhir"
|
||||
CODE_SYSTEM = f"{BASE}/CodeSystem"
|
||||
VALUE_SET = f"{BASE}/ValueSet"
|
||||
STRUCTURE = f"{BASE}/StructureDefinition"
|
||||
SIMULATED = {"system": f"{CODE_SYSTEM}/etiqueta", "code": "simulado", "display": "Datos simulados"}
|
||||
MAX_COUNT = 200
|
||||
DEFAULT_COUNT = 50
|
||||
|
||||
|
||||
def fhir(resource: dict, status: int = 200) -> Response:
|
||||
"""A resource as the answer, in FHIR's JSON media type."""
|
||||
return Response(json.dumps(resource, ensure_ascii=False), status=status, mimetype=MEDIA_TYPE)
|
||||
|
||||
|
||||
def outcome(status: int, code: str, diagnostics: str, severity: str = "error") -> Response:
|
||||
"""An error as an `OperationOutcome` (`code` from FHIR's issue-type), with the HTTP status it goes with."""
|
||||
return fhir({"resourceType": "OperationOutcome",
|
||||
"issue": [{"severity": severity, "code": code, "diagnostics": diagnostics}]}, status)
|
||||
|
||||
|
||||
def canonical(path: str) -> str:
|
||||
"""The absolute canonical of a project resource: `Measure/<id>`, `CodeSystem/<id>`…"""
|
||||
return f"{BASE}/{path}"
|
||||
|
||||
|
||||
def coding(system: str, code: str, display: str | None = None) -> dict:
|
||||
return {"system": system, "code": code, **({"display": display} if display else {})}
|
||||
|
||||
|
||||
def concept(system: str, code: str, display: str | None = None, text: str | None = None) -> dict:
|
||||
return {"coding": [coding(system, code, display)], **({"text": text} if text else {})}
|
||||
|
||||
|
||||
def tagged(resource: dict, simulated: bool) -> dict:
|
||||
"""The resource with the simulated-data tag in its `meta`, when its data are simulated."""
|
||||
if simulated:
|
||||
resource.setdefault("meta", {}).setdefault("tag", []).append(SIMULATED)
|
||||
return resource
|
||||
|
||||
|
||||
def simulated_data() -> bool:
|
||||
"""Patient data are simulated in the DEV deployment (`DEV_REVISION`), the only one that serves them."""
|
||||
return bool(os.environ.get("DEV_REVISION"))
|
||||
|
||||
|
||||
def page() -> tuple[int, int]:
|
||||
"""`_count` (at most `MAX_COUNT`) and `_offset` of the search. `ValueError` if one isn't a number."""
|
||||
count = int(request.args.get("_count", DEFAULT_COUNT))
|
||||
offset = int(request.args.get("_offset", 0))
|
||||
if count < 0 or offset < 0:
|
||||
raise ValueError("`_count` y `_offset` no pueden ser negativos")
|
||||
return min(count, MAX_COUNT), offset
|
||||
|
||||
|
||||
def searchset(entries: list[dict], total: int, count: int, offset: int) -> dict:
|
||||
"""A `searchset` Bundle with the page's entries, the total and the `self`, `next` and `previous` links."""
|
||||
def link(relation: str, at: int) -> dict:
|
||||
args = [(k, v) for k, v in request.args.items(multi=True) if k not in ("_count", "_offset")]
|
||||
return {"relation": relation, "url": f"{request.base_url}?{urlencode([*args, ('_count', count), ('_offset', at)])}"}
|
||||
|
||||
links = [link("self", offset)]
|
||||
if offset + count < total:
|
||||
links.append(link("next", offset + count))
|
||||
if offset > 0:
|
||||
links.append(link("previous", max(0, offset - count)))
|
||||
return {"resourceType": "Bundle", "type": "searchset", "total": total, "link": links, "entry": entries}
|
||||
|
||||
|
||||
def fhir_base() -> str:
|
||||
"""This request's FHIR endpoint, `…/<domain>/fhir/`: what a `fullUrl` is relative to."""
|
||||
url = request.base_url
|
||||
return url[:url.index("/fhir/") + len("/fhir/")] if "/fhir/" in url else url.rstrip("/") + "/"
|
||||
|
||||
|
||||
def entry(resource: dict, mode: str | None = "match") -> dict:
|
||||
"""A Bundle entry: its `fullUrl` when the resource has an id, and its search mode in a searchset."""
|
||||
item = {"resource": resource}
|
||||
if "id" in resource:
|
||||
item = {"fullUrl": f"{fhir_base()}{resource['resourceType']}/{resource['id']}", **item}
|
||||
if mode:
|
||||
item["search"] = {"mode": mode}
|
||||
return item
|
||||
@@ -0,0 +1,200 @@
|
||||
"""A domain's measures as FHIR R4 `Measure` resources, and their answers as `MeasureReport`s.
|
||||
|
||||
The definitions are dbt's (`webapi.kpis.definitions_of`); the `Measure` carries what the indicator page needs from
|
||||
each metric's `meta` (title, description, scoring, populations, strata, period types, figures and category labels as
|
||||
extensions). A report names its measure by the absolute canonical the `Measure` carries; each group and stratifier
|
||||
has a code; a composition (C2) is a `cohort` whose categories are a stratifier, and with strata, each stratum holds
|
||||
its category as a `component`. A duration reports the units without a value as their own population.
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from webapi.compositions import CompositionAnswer, CompositionDefinition
|
||||
from webapi.durations import OBSERVATION, DurationAnswer, DurationDefinition
|
||||
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, canonical, concept
|
||||
from webapi.metrics import EVENT_CUTOFF, HISTORY_ENTRY, KNOWLEDGE_CUTOFF, POPULATION_SYSTEM, Answer, Counts
|
||||
|
||||
SCORING_SYSTEM = "http://terminology.hl7.org/CodeSystem/measure-scoring"
|
||||
IMPROVEMENT_SYSTEM = "http://terminology.hl7.org/CodeSystem/measure-improvement-notation"
|
||||
GROUP_SYSTEM = f"{CODE_SYSTEM}/grupo-medida"
|
||||
STRATIFIER_SYSTEM = f"{CODE_SYSTEM}/estratificador"
|
||||
EXCLUDED = "measure-population-exclusion"
|
||||
FIGURES = f"{STRUCTURE}/figuras"
|
||||
PERIOD_TYPES = f"{STRUCTURE}/tipos-periodo"
|
||||
CATEGORY_LABEL = f"{STRUCTURE}/categoria"
|
||||
CONTRACT = f"{STRUCTURE}/contrato"
|
||||
REQUIRES_VALIDATION = f"{STRUCTURE}/requiere-validacion"
|
||||
POPULATION_LABELS = {
|
||||
"initial-population": "Unidades del periodo", "numerator": "Numerador", "denominator": "Denominador",
|
||||
"denominator-exclusion": "Excluidos del denominador", "measure-observation": "Unidades con valor",
|
||||
EXCLUDED: "Unidades sin valor",
|
||||
}
|
||||
|
||||
|
||||
def scoring(definition) -> str:
|
||||
"""The FHIR scoring: a composition is a `cohort` (its categories are a stratifier)."""
|
||||
if isinstance(definition, CompositionDefinition):
|
||||
return "cohort"
|
||||
return "continuous-variable" if isinstance(definition, DurationDefinition) else "proportion"
|
||||
|
||||
|
||||
def labels(manifest: Path) -> dict[str, tuple[str, str]]:
|
||||
"""Each metric's (title, description) in the manifest: `meta.titulo` when the label had to differ."""
|
||||
metrics = json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values()
|
||||
return {m["name"]: (m["config"].get("meta", {}).get("titulo") or m["label"], (m.get("description") or "").strip())
|
||||
for m in metrics}
|
||||
|
||||
|
||||
def fhir_id(definition) -> str:
|
||||
"""The measure's id as FHIR allows one (letters, digits, `-` and `.`): `M21_diagnosticados_con_eeg` ->
|
||||
`M21-diagnosticados-con-eeg`."""
|
||||
return definition.measure_id.replace("_", "-")
|
||||
|
||||
|
||||
def measure_url(definition) -> str:
|
||||
return canonical(f"Measure/{fhir_id(definition)}")
|
||||
|
||||
|
||||
def _populations(definition) -> list[dict]:
|
||||
"""Each population with the dbt metric that counts it as its criteria."""
|
||||
if scoring(definition) == "proportion":
|
||||
metrics = {**{c: definition.denominator.metric for c in definition.denominator.codes},
|
||||
**{c: definition.numerator.metric for c in definition.numerator.codes},
|
||||
**({c: definition.exclusion.metric for c in definition.exclusion.codes}
|
||||
if getattr(definition, "exclusion", None) else {})}
|
||||
else:
|
||||
codes = ["initial-population"] if scoring(definition) == "cohort" else ["initial-population", OBSERVATION,
|
||||
EXCLUDED]
|
||||
metrics = {c: definition.metric for c in codes}
|
||||
return [{"code": concept(POPULATION_SYSTEM, c), "description": POPULATION_LABELS.get(c, c),
|
||||
"criteria": {"language": "text/x-dbt-metric", "expression": metric}} for c, metric in metrics.items()]
|
||||
|
||||
|
||||
def measure_resource(definition, title: str, description: str) -> dict:
|
||||
"""The `Measure` of a definition: one group per group it publishes, each with its populations and strata."""
|
||||
meta = getattr(definition, "meta", {}) or {}
|
||||
strata = [{"code": concept(STRATIFIER_SYSTEM, s.name, text=s.spec.get("etiqueta", s.name))}
|
||||
for s in definition.strata]
|
||||
if isinstance(definition, CompositionDefinition):
|
||||
strata.insert(0, {"code": concept(STRATIFIER_SYSTEM, definition.category.value)})
|
||||
groups = [{"code": concept(GROUP_SYSTEM, definition.group), "population": _populations(definition),
|
||||
**({"stratifier": strata} if strata else {})}]
|
||||
groups += [{"code": concept(GROUP_SYSTEM, g.name, g.label), "population": _populations(definition)}
|
||||
for g in getattr(definition, "groups", ())]
|
||||
extensions = [{"url": CONTRACT, "valueCode": meta.get("contrato", "")},
|
||||
*({"url": PERIOD_TYPES, "valueCode": t} for t in meta.get("tipos_periodo", ())),
|
||||
*({"url": FIGURES, "valueString": f} for f in meta.get("figuras", ()))]
|
||||
category = meta.get("categoria", {})
|
||||
extensions += [{"url": CATEGORY_LABEL, "extension": [
|
||||
{"url": "codigo", "valueCode": code}, {"url": "etiqueta", "valueString": spec["etiqueta"]},
|
||||
{"url": "color", "valueString": spec["color"]}]} for code, spec in category.get("etiquetas", {}).items()]
|
||||
if meta.get("requiere_validacion"):
|
||||
extensions.append({"url": REQUIRES_VALIDATION, "valueCode": meta["requiere_validacion"]})
|
||||
resource = {
|
||||
"resourceType": "Measure", "id": fhir_id(definition), "url": measure_url(definition),
|
||||
"version": definition.version, "name": definition.metric, "title": title, "status": "active",
|
||||
"description": description or title, "extension": [e for e in extensions if e.get("valueCode", True)],
|
||||
"scoring": concept(SCORING_SYSTEM, scoring(definition)), "group": groups,
|
||||
}
|
||||
if definition.basis:
|
||||
resource["subjectCodeableConcept"] = concept(f"{CODE_SYSTEM}/unidad", definition.basis)
|
||||
if definition.improvement_notation:
|
||||
resource["improvementNotation"] = concept(IMPROVEMENT_SYSTEM, definition.improvement_notation)
|
||||
return resource
|
||||
|
||||
|
||||
def _count(code: str, n: int) -> dict:
|
||||
return {"code": concept(POPULATION_SYSTEM, code), "count": n}
|
||||
|
||||
|
||||
def _proportion_cells(definition, counts: Counts, excluded: int | None = None) -> dict:
|
||||
cells = {"population": [*(_count(c, counts.denominator) for c in definition.denominator.codes),
|
||||
*(_count(c, counts.numerator) for c in definition.numerator.codes)]}
|
||||
if excluded is not None and getattr(definition, "exclusion", None):
|
||||
cells["population"] += [_count(c, excluded) for c in definition.exclusion.codes]
|
||||
if counts.proportion is not None:
|
||||
cells["measureScore"] = {"value": counts.proportion}
|
||||
return cells
|
||||
|
||||
|
||||
def _label(spec: dict, value: str) -> str | None:
|
||||
"""A stratum value's label: from `valores` as a map of values to labels, or as a list of entries with `etiqueta`
|
||||
(a timeline stratum's), or `resto_etiqueta` for its `resto`."""
|
||||
labels_of = spec.get("valores")
|
||||
if isinstance(labels_of, dict):
|
||||
return labels_of.get(value)
|
||||
if isinstance(labels_of, list):
|
||||
found = [v.get("etiqueta") for v in labels_of if isinstance(v, dict) and v.get("valor") == value]
|
||||
return found[0] if found else (spec.get("resto_etiqueta") if value == spec.get("resto") else None)
|
||||
return None
|
||||
|
||||
|
||||
def _stratum_value(stratifier: str, value: str, display: str | None = None) -> dict:
|
||||
return concept(f"{CODE_SYSTEM}/{stratifier.replace('_', '-')}", value, display)
|
||||
|
||||
|
||||
def _groups(definition, result) -> list[dict]:
|
||||
if isinstance(result, CompositionAnswer):
|
||||
group = {"code": concept(GROUP_SYSTEM, definition.group), "population": [_count("initial-population",
|
||||
result.total)]}
|
||||
labels_of = {c: s["etiqueta"] for c, s in definition.meta.get("categoria", {}).get("etiquetas", {}).items()}
|
||||
category = definition.category.value
|
||||
stratifiers = [{"code": [concept(STRATIFIER_SYSTEM, category)], "stratum": [
|
||||
{"value": _stratum_value(category, c, labels_of.get(c)), "population": [_count("initial-population", n)]}
|
||||
for c, n in sorted(result.categories.items())]}]
|
||||
for name, by_value in result.strata.items():
|
||||
stratifiers.append({"code": [concept(STRATIFIER_SYSTEM, name), concept(STRATIFIER_SYSTEM, category)],
|
||||
"stratum": [{"component": [
|
||||
{"code": concept(STRATIFIER_SYSTEM, name), "value": _stratum_value(name, v)},
|
||||
{"code": concept(STRATIFIER_SYSTEM, category), "value": _stratum_value(category, c)},
|
||||
], "population": [_count("initial-population", n)]}
|
||||
for v, cs in sorted(by_value.items()) for c, n in sorted(cs.items())]})
|
||||
group["stratifier"] = stratifiers
|
||||
return [group]
|
||||
if isinstance(result, DurationAnswer):
|
||||
group = {"code": concept(GROUP_SYSTEM, definition.group), "population": [
|
||||
_count("initial-population", result.initial), _count(OBSERVATION, result.n),
|
||||
_count(EXCLUDED, result.excluded)]}
|
||||
if result.median is not None:
|
||||
group["measureScore"] = {"value": result.median, "unit": "d", "extension": [
|
||||
{"url": f"{STRUCTURE}/q1", "valueDecimal": result.q1},
|
||||
{"url": f"{STRUCTURE}/q3", "valueDecimal": result.q3}]}
|
||||
return [group]
|
||||
assert isinstance(result, Answer)
|
||||
spec_of = {s.name: s.spec for s in definition.strata}
|
||||
group = {"code": concept(GROUP_SYSTEM, definition.group), **_proportion_cells(definition, result.total,
|
||||
result.excluded)}
|
||||
if result.strata:
|
||||
group["stratifier"] = [{"code": [concept(STRATIFIER_SYSTEM, name, text=spec_of[name].get("etiqueta"))],
|
||||
"stratum": [{"value": _stratum_value(name, value, _label(spec_of[name], value)),
|
||||
**_proportion_cells(definition, c)}
|
||||
for value, c in sorted(values.items())]}
|
||||
for name, values in result.strata.items()]
|
||||
groups = [group]
|
||||
labels_of = {g.name: g.label for g in getattr(definition, "groups", ())}
|
||||
groups += [{"code": concept(GROUP_SYSTEM, name, labels_of.get(name)), **_proportion_cells(definition, counts)}
|
||||
for name, counts in result.groups.items()]
|
||||
return groups
|
||||
|
||||
|
||||
def measure_report(definition, question, result, period, generated_at: datetime) -> dict:
|
||||
"""An answer as a FHIR R4 `MeasureReport` (summary), naming its measure by its absolute canonical."""
|
||||
cutoff = getattr(result, "event_cutoff", None) or question.event_cutoff
|
||||
extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id}]
|
||||
if cutoff is not None:
|
||||
extensions.append({"url": EVENT_CUTOFF, "valueDate": cutoff.isoformat()})
|
||||
if question.knowledge_cutoff is not None:
|
||||
extensions.append({"url": KNOWLEDGE_CUTOFF, "valueDateTime": question.knowledge_cutoff.isoformat()})
|
||||
report = {
|
||||
"resourceType": "MeasureReport", "id": f"{fhir_id(definition)}-{result.report_id}", "status": "complete",
|
||||
"type": "summary", "measure": f"{measure_url(definition)}|{definition.version}",
|
||||
"date": generated_at.isoformat(),
|
||||
# FHIR's end is inclusive; a period of `dim_periodo` ends the day before `fin`.
|
||||
"period": {"start": period.inicio.isoformat(), "end": (period.fin - timedelta(days=1)).isoformat()},
|
||||
"extension": extensions, "group": _groups(definition, result),
|
||||
}
|
||||
if definition.improvement_notation:
|
||||
report["improvementNotation"] = concept(IMPROVEMENT_SYSTEM, definition.improvement_notation)
|
||||
return report
|
||||
@@ -0,0 +1,352 @@
|
||||
"""TEA's patients as FHIR R4 resources: the follow-up list as `EpisodeOfCare`s and the patient summary.
|
||||
|
||||
Read from dbt's views (`tea_seguimiento`, `tea_paciente_*`), which hold dates, not states: every state here is taken
|
||||
at a date, the cut-off. A child's screening is an `EpisodeOfCare` from its first M-CHAT to its first good EEG, its
|
||||
stage the furthest step reached by the cut-off (`type`, with its date as an extension), its pending steps a
|
||||
`CarePlan`. The EEG the study uses is the child's first good EEG by the cut-off; without one, the latest, as not
|
||||
valid. `Patient.id` is the salted pseudonym: `pac_id` never leaves.
|
||||
|
||||
Until the domain expert validates the reference ranges, every alteration stays hidden (`alterations_validated`):
|
||||
the alteration filter, the abnormal/normal split, and the metric and electrode observations.
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import column, select, table
|
||||
|
||||
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, concept, tagged
|
||||
from webapi.follow_up.listing import seudonimo
|
||||
|
||||
STEPS = (("SOLO_MCHAT", "fecha_mchat", "M-CHAT"), ("PSICOLOGIA", "fecha_psicologia", "Evaluación psicológica"),
|
||||
("NEUROPEDIATRIA", "fecha_neuropediatria", "Evaluación neuropediátrica"),
|
||||
("EEG", "fecha_eeg", "EEG de buena calidad"))
|
||||
CRITERIA = (("calidad_amplitud", "Canales con amplitud extrema", "canales"),
|
||||
("calidad_alta_frecuencia", "Ruido de alta frecuencia", "canales"),
|
||||
("calidad_correlacion", "Baja correlación entre canales", "canales"),
|
||||
("calidad_sin_senal", "Canales planos o sin señal", "canales"),
|
||||
("calidad_linea", "Ruido de la línea eléctrica", "dB"))
|
||||
ALTERED = ("aumentado", "disminuido")
|
||||
INTERPRETATION = "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation"
|
||||
ABSENT = "http://terminology.hl7.org/CodeSystem/data-absent-reason"
|
||||
ICD10 = "http://hl7.org/fhir/sid/icd-10"
|
||||
CATALOG = f"{CODE_SYSTEM}/tea-catalogo"
|
||||
STAGE_DATE = f"{STRUCTURE}/fecha-etapa"
|
||||
AGE_GROUP = f"{STRUCTURE}/grupo-edad"
|
||||
DEFAULT_SALT = "dev-simulado"
|
||||
|
||||
FOLLOW_UP = table("tea_seguimiento", *map(column, (
|
||||
"pac_id", "grupo_edad", "fecha_mchat", "mchat", "fecha_psicologia", "css_ados2", "modulo_ados2",
|
||||
"fecha_neuropediatria", "fecha_tea", "fecha_sin_tea", "fecha_eeg")))
|
||||
EEGS = table("tea_paciente_eegs", *map(column, (
|
||||
"procedimiento_id", "pac_id", "fecha_eeg", "con_sueno", "canales", "duracion_min", "calidad", "valido",
|
||||
*(c for name, _, _ in CRITERIA for c in (name, f"{name}_bueno")))))
|
||||
METRICS = table("tea_paciente_eeg_metricas", *map(column, (
|
||||
"procedimiento_id", "pac_id", "metrica", "valor", "grupo_edad_eeg", "ref_min", "ref_max", "valor_z", "estado")))
|
||||
ELECTRODES = table("tea_paciente_eeg_electrodos", *map(column, ("procedimiento_id", "pac_id", "metrica", "electrodo",
|
||||
"valor")))
|
||||
ADOS2 = table("tea_paciente_ados2", *map(column, (
|
||||
"procedimiento_id", "pac_id", "fecha_ados2", "modulo", "algoritmo", "css", "clasificacion", "dominio", "reactivo",
|
||||
"etiqueta", "puntaje", "puntaje_algoritmo")))
|
||||
PERSONS = table("persona", column("pac_id"), column("fecha_nacimiento"))
|
||||
|
||||
|
||||
def alterations_validated() -> bool:
|
||||
"""Whether the domain expert validated the reference ranges, effect texts and quality thresholds
|
||||
(`TEA_ALTERACIONES_VALIDADAS=1`): until then no alteration is shown."""
|
||||
return os.environ.get("TEA_ALTERACIONES_VALIDADAS", "") in ("1", "true", "si")
|
||||
|
||||
|
||||
def salt() -> str:
|
||||
return os.environ.get("SEGUIMIENTO_SAL", DEFAULT_SALT)
|
||||
|
||||
|
||||
def _date(value) -> date | None:
|
||||
if value is None or isinstance(value, date):
|
||||
return value
|
||||
return date.fromisoformat(str(value)[:10])
|
||||
|
||||
|
||||
def _rows(queries, query) -> list[dict]:
|
||||
columns, rows = queries.rows(query)
|
||||
return [dict(zip(columns, row)) for row in rows]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Episode:
|
||||
"""A child's screening at the cut-off: its follow-up row, the steps reached, the study's EEG and its metrics."""
|
||||
|
||||
child: dict
|
||||
cutoff: date
|
||||
eegs: list[dict]
|
||||
metrics: list[dict]
|
||||
|
||||
@property
|
||||
def pseudonym(self) -> str:
|
||||
return seudonimo(self.child["pac_id"], salt())
|
||||
|
||||
def reached(self) -> list[tuple[str, date, str]]:
|
||||
steps = []
|
||||
for code, field, label in STEPS:
|
||||
when = _date(self.child[field])
|
||||
if when is None or when > self.cutoff:
|
||||
break
|
||||
steps.append((code, when, label))
|
||||
return steps
|
||||
|
||||
@property
|
||||
def stage(self) -> tuple[str, date] | None:
|
||||
steps = self.reached()
|
||||
return (steps[-1][0], steps[-1][1]) if steps else None
|
||||
|
||||
@property
|
||||
def finished(self) -> bool:
|
||||
return any(code == "EEG" for code, _, _ in self.reached())
|
||||
|
||||
@property
|
||||
def pending(self) -> list[str]:
|
||||
done = {code for code, _, _ in self.reached()}
|
||||
return [label for code, _, label in STEPS if code not in done]
|
||||
|
||||
@property
|
||||
def diagnosis(self) -> bool | None:
|
||||
"""True with a F84.0 note by the cut-off, False with only notes without it, None without a note."""
|
||||
if (_date(self.child["fecha_tea"]) or date.max) <= self.cutoff:
|
||||
return True
|
||||
if (_date(self.child["fecha_sin_tea"]) or date.max) <= self.cutoff:
|
||||
return False
|
||||
return None
|
||||
|
||||
def study_eeg(self) -> dict | None:
|
||||
"""The first good EEG by the cut-off; without one, the latest by then (not valid)."""
|
||||
known = sorted((e for e in self.eegs if (_date(e["fecha_eeg"]) or date.max) <= self.cutoff),
|
||||
key=lambda e: (_date(e["fecha_eeg"]), e["procedimiento_id"]))
|
||||
good = [e for e in known if e["valido"] == 1]
|
||||
return good[0] if good else (known[-1] if known else None)
|
||||
|
||||
def alterations(self) -> list[str]:
|
||||
eeg = self.study_eeg()
|
||||
if eeg is None or eeg["valido"] != 1:
|
||||
return []
|
||||
return sorted(m["metrica"] for m in self.metrics
|
||||
if m["procedimiento_id"] == eeg["procedimiento_id"] and m["estado"] in ALTERED)
|
||||
|
||||
@property
|
||||
def eeg_result(self) -> str:
|
||||
eeg = self.study_eeg()
|
||||
if eeg is None or eeg["valido"] != 1:
|
||||
return "sin-eeg-valido"
|
||||
return "anormal" if self.alterations() else "normal"
|
||||
|
||||
|
||||
def episodes(queries, cutoff: date) -> list[Episode]:
|
||||
"""Every child of the cohort who entered the screening by the cut-off, with its EEGs and their metrics."""
|
||||
eegs, metrics = _rows(queries, select(EEGS)), _rows(queries, select(METRICS))
|
||||
by_child = {}
|
||||
for child in _rows(queries, select(FOLLOW_UP)):
|
||||
if (_date(child["fecha_mchat"]) or date.max) <= cutoff:
|
||||
by_child[child["pac_id"]] = Episode(child, cutoff, [], [])
|
||||
for eeg in eegs:
|
||||
if eeg["pac_id"] in by_child:
|
||||
by_child[eeg["pac_id"]].eegs.append(eeg)
|
||||
for metric in metrics:
|
||||
if metric["pac_id"] in by_child:
|
||||
by_child[metric["pac_id"]].metrics.append(metric)
|
||||
return list(by_child.values())
|
||||
|
||||
|
||||
def patient_of(queries, pseudonym: str) -> int | None:
|
||||
"""The `pac_id` behind a pseudonym, among the cohort's children."""
|
||||
for child in _rows(queries, select(FOLLOW_UP.c.pac_id)):
|
||||
if seudonimo(child["pac_id"], salt()) == pseudonym:
|
||||
return child["pac_id"]
|
||||
return None
|
||||
|
||||
|
||||
# --- resources -------------------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def patient(pac_id: int, birth: date | None, simulated: bool) -> dict:
|
||||
resource = {"resourceType": "Patient", "id": seudonimo(pac_id, salt())}
|
||||
if birth is not None:
|
||||
resource["birthDate"] = _date(birth).strftime("%Y-%m")
|
||||
return tagged(resource, simulated)
|
||||
|
||||
|
||||
def episode_of_care(e: Episode, simulated: bool) -> dict:
|
||||
stage = e.stage
|
||||
resource = {
|
||||
"resourceType": "EpisodeOfCare", "id": e.pseudonym, "status": "finished" if e.finished else "active",
|
||||
"patient": {"reference": f"Patient/{e.pseudonym}"},
|
||||
"period": {"start": _date(e.child["fecha_mchat"]).isoformat(),
|
||||
**({"end": stage[1].isoformat()} if e.finished else {})},
|
||||
"extension": [{"url": AGE_GROUP, "valueCoding": {"system": f"{CODE_SYSTEM}/grupo-edad",
|
||||
"code": e.child["grupo_edad"]}}],
|
||||
}
|
||||
if stage is not None:
|
||||
resource["type"] = [concept(f"{CODE_SYSTEM}/paso", stage[0])]
|
||||
resource["extension"].append({"url": STAGE_DATE, "valueDate": stage[1].isoformat()})
|
||||
return tagged(resource, simulated)
|
||||
|
||||
|
||||
def care_plan(e: Episode, simulated: bool) -> dict:
|
||||
"""The episode's steps, each `completed` with its date or `not-started`."""
|
||||
done = {code: when for code, when, _ in e.reached()}
|
||||
activities = [{"detail": {
|
||||
"code": concept(f"{CODE_SYSTEM}/paso", code, text=label),
|
||||
"status": "completed" if code in done else "not-started",
|
||||
**({"scheduledString": done[code].isoformat()} if code in done else {})}} for code, _, label in STEPS]
|
||||
return tagged({"resourceType": "CarePlan", "id": f"pasos-{e.pseudonym}", "status": "active" if not e.finished
|
||||
else "completed", "intent": "plan", "subject": {"reference": f"Patient/{e.pseudonym}"},
|
||||
"extension": [{"url": f"{STRUCTURE}/episodio", "valueReference": {
|
||||
"reference": f"EpisodeOfCare/{e.pseudonym}"}}],
|
||||
"activity": activities}, simulated)
|
||||
|
||||
|
||||
def mchat_observation(e: Episode, simulated: bool) -> dict | None:
|
||||
if e.child["mchat"] is None:
|
||||
return None
|
||||
return tagged({"resourceType": "Observation", "id": f"mchat-{e.pseudonym}", "status": "final",
|
||||
"code": concept(CATALOG, "mchat.puntaje", "M-CHAT-R/F: puntaje total"),
|
||||
"subject": {"reference": f"Patient/{e.pseudonym}"},
|
||||
"effectiveDateTime": _date(e.child["fecha_mchat"]).isoformat(),
|
||||
"valueInteger": int(e.child["mchat"])}, simulated)
|
||||
|
||||
|
||||
def condition(e: Episode, simulated: bool) -> dict | None:
|
||||
if not e.diagnosis:
|
||||
return None
|
||||
return tagged({"resourceType": "Condition", "id": f"tea-{e.pseudonym}",
|
||||
"code": concept(ICD10, "F84.0", "Autismo en la niñez"),
|
||||
"subject": {"reference": f"Patient/{e.pseudonym}"},
|
||||
"recordedDate": _date(e.child["fecha_tea"]).isoformat()}, simulated)
|
||||
|
||||
|
||||
def quality_observations(eeg: dict, pseudonym: str, simulated: bool) -> list[dict]:
|
||||
observations = []
|
||||
for name, label, unit in CRITERIA:
|
||||
if eeg[name] is None:
|
||||
continue
|
||||
value = ({"valueInteger": int(eeg[name])} if unit == "canales"
|
||||
else {"valueQuantity": {"value": float(eeg[name]), "unit": unit}})
|
||||
observations.append(tagged({
|
||||
"resourceType": "Observation", "id": f"{name.replace('_', '-')}-{eeg['procedimiento_id']}",
|
||||
"status": "final", "code": concept(CATALOG, f"eeg.{name}", label),
|
||||
"subject": {"reference": f"Patient/{pseudonym}"}, "effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
|
||||
**value, "interpretation": [concept(f"{CODE_SYSTEM}/calidad", "BUENO" if eeg[f"{name}_bueno"] else "MALO")],
|
||||
}, simulated))
|
||||
return observations
|
||||
|
||||
|
||||
def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict], pseudonym: str,
|
||||
simulated: bool) -> list[dict]:
|
||||
"""One `Observation` per metric (value, reference for the age at the EEG, H/L/N, the z-score as a component, or
|
||||
why it couldn't be evaluated) and one per metric with a component per electrode."""
|
||||
from webapi.fhir.terminology import TEA_EEG
|
||||
|
||||
observations = []
|
||||
for m in sorted((m for m in metrics if m["procedimiento_id"] == eeg["procedimiento_id"]), key=lambda m: m["metrica"]):
|
||||
spec = TEA_EEG["metricas"].get(m["metrica"], {"etiqueta": m["metrica"], "unidad": ""})
|
||||
code = concept(f"{CODE_SYSTEM}/tea-eeg-metrica", m["metrica"], spec["etiqueta"])
|
||||
resource = {"resourceType": "Observation", "id": f"{m['metrica'].replace('_', '-')}-{eeg['procedimiento_id']}",
|
||||
"status": "final", "code": code, "subject": {"reference": f"Patient/{pseudonym}"},
|
||||
"effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat()}
|
||||
if m["valor"] is None or m["valor_z"] is None:
|
||||
resource["dataAbsentReason"] = concept(ABSENT, "not-performed" if m["valor"] is None else "unknown")
|
||||
else:
|
||||
resource["valueQuantity"] = {"value": float(m["valor"]), "unit": spec["unidad"]}
|
||||
resource["interpretation"] = [concept(INTERPRETATION, {"aumentado": "H", "disminuido": "L"}.get(
|
||||
m["estado"], "N"))]
|
||||
resource["component"] = [{"code": concept(f"{CODE_SYSTEM}/puntaje", "z", "Puntaje z"),
|
||||
"valueQuantity": {"value": round(float(m["valor_z"]), 2)}}]
|
||||
if m["ref_min"] is not None:
|
||||
resource["referenceRange"] = [{"low": {"value": float(m["ref_min"]), "unit": spec["unidad"]},
|
||||
"high": {"value": float(m["ref_max"]), "unit": spec["unidad"]},
|
||||
"text": f"Grupo de edad al EEG: {m['grupo_edad_eeg']}"}]
|
||||
observations.append(tagged(resource, simulated))
|
||||
at = [x for x in electrodes if x["procedimiento_id"] == eeg["procedimiento_id"] and x["metrica"] == m["metrica"]]
|
||||
if at:
|
||||
observations.append(tagged({
|
||||
"resourceType": "Observation", "id": f"electrodos-{m['metrica'].replace('_', '-')}-{eeg['procedimiento_id']}",
|
||||
"status": "final", "code": code, "subject": {"reference": f"Patient/{pseudonym}"},
|
||||
"effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
|
||||
"component": [{"code": concept(f"{CODE_SYSTEM}/electrodo-10-20", x["electrodo"]),
|
||||
"valueQuantity": {"value": float(x["valor"])}}
|
||||
for x in sorted(at, key=lambda x: x["electrodo"])]}, simulated))
|
||||
return observations
|
||||
|
||||
|
||||
def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: list[dict], simulated: bool) -> list[dict]:
|
||||
"""The recording as a `Procedure` and its result as a `DiagnosticReport` with its observations; a bad EEG has
|
||||
no result beyond its quality, and the alterations stay out until validated."""
|
||||
quality = quality_observations(eeg, pseudonym, simulated)
|
||||
altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated)
|
||||
if eeg["valido"] == 1 and alterations_validated() else [])
|
||||
procedure = tagged({"resourceType": "Procedure", "id": f"eeg-{eeg['procedimiento_id']}", "status": "completed",
|
||||
"code": concept(CATALOG, "eeg", "Electroencefalograma"),
|
||||
"subject": {"reference": f"Patient/{pseudonym}"},
|
||||
"performedDateTime": _date(eeg["fecha_eeg"]).isoformat()}, simulated)
|
||||
report = {"resourceType": "DiagnosticReport", "id": f"eeg-{eeg['procedimiento_id']}", "status": "final",
|
||||
"code": concept(CATALOG, "eeg", "Electroencefalograma"), "subject": {"reference": f"Patient/{pseudonym}"},
|
||||
"effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
|
||||
"result": [{"reference": f"Observation/{o['id']}"} for o in quality + altered],
|
||||
"conclusionCode": [concept(f"{CODE_SYSTEM}/calidad", eeg["calidad"])]}
|
||||
if eeg["duracion_min"] is not None or eeg["canales"] is not None:
|
||||
report["extension"] = [e for e in (
|
||||
{"url": f"{STRUCTURE}/duracion-min", "valueDecimal": float(eeg["duracion_min"])}
|
||||
if eeg["duracion_min"] is not None else None,
|
||||
{"url": f"{STRUCTURE}/canales", "valueInteger": int(eeg["canales"])} if eeg["canales"] is not None else None,
|
||||
) if e]
|
||||
if eeg["valido"] != 1:
|
||||
report["conclusion"] = "EEG de mala calidad: no es válido para el estudio."
|
||||
return [procedure, tagged(report, simulated), *quality, *altered]
|
||||
|
||||
|
||||
def ados2_observation(rows: list[dict], pseudonym: str, simulated: bool) -> dict | None:
|
||||
"""The first ADOS-2 as one `Observation`: module, algorithm, CSS, classification, the two domain totals and the
|
||||
items, each item with its algorithm score."""
|
||||
if not rows:
|
||||
return None
|
||||
first = min(rows, key=lambda r: (_date(r["fecha_ados2"]) or date.max, r["procedimiento_id"]))
|
||||
items = [r for r in rows if r["procedimiento_id"] == first["procedimiento_id"] and r["reactivo"]]
|
||||
components = []
|
||||
if first["modulo"]:
|
||||
components.append({"code": concept(CATALOG, "ados2.modulo", "Módulo"),
|
||||
"valueCodeableConcept": concept(CATALOG, f"ados2.modulo.{first['modulo']}")})
|
||||
if first["algoritmo"]:
|
||||
components.append({"code": concept(CATALOG, "ados2.algoritmo", "Algoritmo"), "valueString": first["algoritmo"]})
|
||||
if first["css"] is not None:
|
||||
components.append({"code": concept(CATALOG, "ados2.css", "Puntaje de severidad (CSS)"),
|
||||
"valueInteger": int(first["css"])})
|
||||
if first["clasificacion"]:
|
||||
components.append({"code": concept(CATALOG, "ados2.clasificacion", "Clasificación"),
|
||||
"valueCodeableConcept": concept(CATALOG, f"ados2.clasificacion.{first['clasificacion']}")})
|
||||
for domain, label in (("SA", "Afecto social"), ("RRB", "Comportamiento restringido y repetitivo")):
|
||||
total = sum(int(r["puntaje_algoritmo"]) for r in items if r["dominio"] == domain)
|
||||
components.append({"code": concept(f"{CODE_SYSTEM}/ados2-dominio", domain, label), "valueInteger": total})
|
||||
components += [{"code": concept(CATALOG, r["reactivo"], r["etiqueta"]), "valueInteger": int(r["puntaje"]),
|
||||
"extension": [{"url": f"{STRUCTURE}/puntaje-algoritmo", "valueInteger": int(r["puntaje_algoritmo"])},
|
||||
{"url": f"{STRUCTURE}/dominio", "valueCode": r["dominio"]}]}
|
||||
for r in sorted(items, key=lambda r: r["reactivo"])]
|
||||
return tagged({"resourceType": "Observation", "id": f"ados2-{first['procedimiento_id']}", "status": "final",
|
||||
"code": concept(CATALOG, "ados2", "ADOS-2"), "subject": {"reference": f"Patient/{pseudonym}"},
|
||||
"effectiveDateTime": _date(first["fecha_ados2"]).isoformat(), "component": components}, simulated)
|
||||
|
||||
|
||||
def patient_summary(queries, pac_id: int, today: date, simulated: bool) -> dict:
|
||||
"""The `$resumen-tea` collection: the patient, its first ADOS-2 and the EEG the study uses, as of today."""
|
||||
pseudonym = seudonimo(pac_id, salt())
|
||||
persons = _rows(queries, select(PERSONS).where(PERSONS.c.pac_id == pac_id))
|
||||
resources = [patient(pac_id, persons[0]["fecha_nacimiento"] if persons else None, simulated)]
|
||||
ados2 = ados2_observation(_rows(queries, select(ADOS2).where(ADOS2.c.pac_id == pac_id)), pseudonym, simulated)
|
||||
resources += [ados2] if ados2 else []
|
||||
(child,) = _rows(queries, select(FOLLOW_UP).where(FOLLOW_UP.c.pac_id == pac_id)) or [None]
|
||||
if child is not None:
|
||||
e = Episode(child, today, _rows(queries, select(EEGS).where(EEGS.c.pac_id == pac_id)),
|
||||
_rows(queries, select(METRICS).where(METRICS.c.pac_id == pac_id)))
|
||||
eeg = e.study_eeg()
|
||||
if eeg is not None:
|
||||
electrodes = _rows(queries, select(ELECTRODES).where(ELECTRODES.c.pac_id == pac_id))
|
||||
resources += eeg_resources(eeg, pseudonym, e.metrics, electrodes, simulated)
|
||||
return {"resourceType": "Bundle", "type": "collection", "entry": [{"resource": r} for r in resources]}
|
||||
@@ -0,0 +1,53 @@
|
||||
# TEA's EEG vocabulary for the FHIR answers: what each metric's alteration may mean (`efectos`, by state), and where
|
||||
# each 10-20 electrode sits on the map the WebApp draws (x to the right, y forward, both from -1 to 1).
|
||||
# The effect texts are placeholders pending the domain expert's review, like the reference ranges in dbt's var `tea`.
|
||||
|
||||
[metricas.ritmo_posterior]
|
||||
etiqueta = "Ritmo posterior"
|
||||
unidad = "Hz"
|
||||
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
|
||||
efectos.disminuido = ["Ritmo más lento de lo esperado para la edad.", "Posible relación con retraso en la maduración cortical."]
|
||||
|
||||
[metricas.husos_sueno_n2]
|
||||
etiqueta = "Husos de sueño N2"
|
||||
unidad = "husos/min"
|
||||
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
|
||||
efectos.disminuido = ["Posible relación con alteraciones del sueño.", "Posible efecto en la consolidación de la memoria y el aprendizaje."]
|
||||
|
||||
[metricas.husos_sueno_n3]
|
||||
etiqueta = "Husos de sueño N3"
|
||||
unidad = "husos/min"
|
||||
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
|
||||
efectos.disminuido = ["Posible relación con alteraciones del sueño.", "Posible efecto en la consolidación de la memoria y el aprendizaje."]
|
||||
|
||||
[metricas.picos_paroxisticos]
|
||||
etiqueta = "Picos paroxísticos"
|
||||
unidad = "picos/min"
|
||||
efectos.aumentado = ["Actividad paroxística mayor de la esperada.", "Correlacionar con la clínica."]
|
||||
|
||||
[metricas.gradiente_anteroposterior]
|
||||
etiqueta = "Gradiente anteroposterior"
|
||||
unidad = "razón posterior/anterior"
|
||||
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
|
||||
efectos.disminuido = ["Organización anteroposterior menos marcada de lo esperado.", "Posible relación con retraso en la maduración cortical."]
|
||||
|
||||
[electrodos]
|
||||
Fp1 = [-0.25, 0.77]
|
||||
Fp2 = [0.25, 0.77]
|
||||
F7 = [-0.65, 0.47]
|
||||
F3 = [-0.33, 0.4]
|
||||
Fz = [0.0, 0.38]
|
||||
F4 = [0.33, 0.4]
|
||||
F8 = [0.65, 0.47]
|
||||
T3 = [-0.8, 0.0]
|
||||
C3 = [-0.4, 0.0]
|
||||
Cz = [0.0, 0.0]
|
||||
C4 = [0.4, 0.0]
|
||||
T4 = [0.8, 0.0]
|
||||
T5 = [-0.65, -0.47]
|
||||
P3 = [-0.33, -0.4]
|
||||
Pz = [0.0, -0.38]
|
||||
P4 = [0.33, -0.4]
|
||||
T6 = [0.65, -0.47]
|
||||
O1 = [-0.25, -0.77]
|
||||
O2 = [0.25, -0.77]
|
||||
@@ -0,0 +1,74 @@
|
||||
"""The project's code systems as FHIR R4 `CodeSystem` resources, generated from what defines them: the domain's
|
||||
catalog (`core/catalogos/<domain>.toml`: studies, results and their values), TEA's screening stages and diagnostic
|
||||
results, and TEA's EEG metrics with their effect texts (`tea_eeg.toml`)."""
|
||||
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
from webapi.fhir.common import CODE_SYSTEM, canonical
|
||||
from webapi.orchestration.reference.catalogs import ruta_de_catalogo
|
||||
|
||||
TEA_EEG = tomllib.loads((Path(__file__).parent / "tea_eeg.toml").read_text(encoding="utf-8"))
|
||||
STAGES = (("SOLO_MCHAT", "Solo M-CHAT"), ("PSICOLOGIA", "Hasta evaluación psicológica"),
|
||||
("NEUROPEDIATRIA", "Hasta evaluación neuropediátrica"), ("EEG", "Con EEG"))
|
||||
DIAGNOSES = (("EN_PROCESO", "En proceso"), ("SIN_TEA", "Nota sin F84.0"), ("CONFIRMADO", "Diagnóstico confirmado"))
|
||||
QUALITY = (("BUENO", "Bueno"), ("MALO", "Malo"), ("SIN_ANALIZAR", "Sin analizar"))
|
||||
|
||||
|
||||
def _code_system(id_: str, title: str, concepts: list[dict], *, hierarchy: bool = False) -> dict:
|
||||
resource = {"resourceType": "CodeSystem", "id": id_, "url": f"{CODE_SYSTEM}/{id_}", "name": id_.replace("-", "_"),
|
||||
"title": title, "status": "active", "content": "complete", "concept": concepts}
|
||||
if hierarchy:
|
||||
resource["hierarchyMeaning"] = "part-of"
|
||||
return resource
|
||||
|
||||
|
||||
def catalog(domain: str) -> dict:
|
||||
"""The domain's catalog: each study, its results under it and each coded result's values under the result."""
|
||||
studies = tomllib.loads(ruta_de_catalogo(domain).read_text(encoding="utf-8"))
|
||||
concepts = []
|
||||
for study_id, study in studies.items():
|
||||
results = []
|
||||
for name, result in study.get("resultados", {}).items():
|
||||
values = [{"code": f"{study_id}.{name}.{v['valor']}", "display": v["etiqueta"]}
|
||||
for v in result.get("valores", ())]
|
||||
results.append({"code": f"{study_id}.{name}", "display": result["etiqueta"],
|
||||
**({"concept": values} if values else {})})
|
||||
concepts.append({"code": study_id, "display": study["etiqueta"], **({"concept": results} if results else {})})
|
||||
return _code_system(f"{domain}-catalogo", f"Catálogo de {domain.upper()}", concepts, hierarchy=True)
|
||||
|
||||
|
||||
def tea_code_systems() -> dict[str, dict]:
|
||||
metrics = [{"code": code, "display": spec["etiqueta"], "property": [
|
||||
{"code": "unidad", "valueString": spec["unidad"]},
|
||||
*({"code": f"efecto-{state}", "valueString": text} for state, texts in spec.get("efectos", {}).items()
|
||||
for text in texts)]} for code, spec in TEA_EEG["metricas"].items()]
|
||||
systems = [
|
||||
_code_system("paso", "Etapa del tamizaje de TEA", [{"code": c, "display": d} for c, d in STAGES]),
|
||||
_code_system("estado", "Resultado diagnóstico de TEA", [{"code": c, "display": d} for c, d in DIAGNOSES]),
|
||||
_code_system("calidad", "Calidad del EEG", [{"code": c, "display": d} for c, d in QUALITY]),
|
||||
{**_code_system("tea-eeg-metrica", "Métricas del EEG", metrics),
|
||||
"property": [{"code": "unidad", "type": "string"}, {"code": "efecto-aumentado", "type": "string"},
|
||||
{"code": "efecto-disminuido", "type": "string"}]},
|
||||
_code_system("electrodo-10-20", "Electrodos del sistema 10-20",
|
||||
[{"code": e, "display": e} for e in TEA_EEG["electrodos"]]),
|
||||
_code_system("grupo-edad", "Grupo de edad al primer M-CHAT", [
|
||||
{"code": "16_23", "display": "16 a 23 meses"}, {"code": "24_29", "display": "24 a 29 meses"},
|
||||
{"code": "30_36", "display": "30 a 36 meses"}, {"code": "sin_dato", "display": "Sin dato"}]),
|
||||
]
|
||||
return {s["id"]: s for s in systems}
|
||||
|
||||
|
||||
def code_systems(domain: str) -> dict[str, dict]:
|
||||
"""Every code system the domain's FHIR endpoint serves, by id."""
|
||||
systems = {f"{domain}-catalogo": catalog(domain)}
|
||||
if domain == "tea":
|
||||
systems.update(tea_code_systems())
|
||||
return systems
|
||||
|
||||
|
||||
def metric_value_set() -> dict:
|
||||
"""The alteration types: the EEG metrics' `ValueSet`."""
|
||||
return {"resourceType": "ValueSet", "id": "tea-alteracion", "url": canonical("ValueSet/tea-alteracion"),
|
||||
"name": "tea_alteracion", "title": "Tipos de alteración del EEG", "status": "active",
|
||||
"compose": {"include": [{"system": f"{CODE_SYSTEM}/tea-eeg-metrica"}]}}
|
||||
@@ -1,4 +1,3 @@
|
||||
from datetime import date, timedelta
|
||||
from pathlib import PurePath
|
||||
from typing import Any
|
||||
|
||||
@@ -11,15 +10,12 @@ from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
|
||||
MAX_LISTED_EVENTS = 20
|
||||
|
||||
|
||||
@register_connector
|
||||
class EdfConnector(FileConnector):
|
||||
"""EEG recordings (`.edf`), one row per file, shaped for `tea.EegEstudio`:
|
||||
patient and dates from the header, an estimated background rhythm from
|
||||
the posterior channels, a text summary of the recording, and the file
|
||||
itself (column `estudio`, stored in `eeg_estudio.eeg_estudio`)."""
|
||||
"""EEG recordings (`.edf`), one row per file, shaped for `tea.Eeg`: the laboratory's study id, the patient
|
||||
and the study date from the header, the channels and duration of the recording, and the file itself (column
|
||||
`estudio`, stored in `eeg.eeg_estudio`). The quality criteria, sleep and metrics are the EEG analysis'."""
|
||||
|
||||
kind = "edf"
|
||||
label = "EEG (EDF)"
|
||||
@@ -57,49 +53,12 @@ class EdfConnector(FileConnector):
|
||||
eeg = EegRecording.read(raw)
|
||||
except ExtractionError as exc:
|
||||
raise ConnectorError(f"{name}: {exc}") from exc
|
||||
patient = eeg.patient
|
||||
study_date = eeg.start.date() if eeg.start else None
|
||||
rhythm = eeg.background_rhythm()
|
||||
return {
|
||||
"id_registro_laboratorio": eeg.recording_fields["admin_code"] or PurePath(name).stem,
|
||||
"paciente": patient.code,
|
||||
"sexo": patient.sex,
|
||||
"fecha_nacimiento_declarada": patient.birthdate,
|
||||
"edad_meses": age_in_months(patient.birthdate, study_date),
|
||||
"fecha_estudio": study_date,
|
||||
"duracion_min": round(eeg.duration_seconds / 60) if eeg.duration_seconds else None,
|
||||
"ritmo_base_frecuencia": rhythm["frequency_hz"],
|
||||
"ritmo_base_amplitud": rhythm["amplitude_uv"],
|
||||
"descripcion_senal": describe(eeg),
|
||||
"paciente": eeg.patient.code,
|
||||
"fecha_estudio": eeg.start.date() if eeg.start else None,
|
||||
"canales": len(eeg.channels),
|
||||
"duracion_min": round(eeg.duration_seconds / 60, 1) if eeg.duration_seconds else None,
|
||||
"archivo": name,
|
||||
"estudio": raw,
|
||||
}
|
||||
|
||||
|
||||
def describe(eeg: EegRecording) -> str:
|
||||
channels = eeg.channels
|
||||
parts = [
|
||||
f"{eeg.variant}, {len(channels)} canales a {channels[0].sample_rate:g} Hz" if channels else eeg.variant,
|
||||
f"duración {timedelta(seconds=round(eeg.duration_seconds))}",
|
||||
"montaje: " + ", ".join(c.label for c in channels),
|
||||
]
|
||||
fields = eeg.recording_fields
|
||||
if fields["equipment"]:
|
||||
parts.append(f"equipo: {fields['equipment']}")
|
||||
if fields["technician"]:
|
||||
parts.append(f"técnico: {fields['technician']}")
|
||||
events = eeg.annotations()
|
||||
if events:
|
||||
listed = "; ".join(f"{timedelta(seconds=round(e.onset_seconds))} {e.text}" for e in events[:MAX_LISTED_EVENTS])
|
||||
more = f" (+{len(events) - MAX_LISTED_EVENTS})" if len(events) > MAX_LISTED_EVENTS else ""
|
||||
parts.append(f"eventos: {listed}{more}")
|
||||
return ". ".join(parts) + "."
|
||||
|
||||
|
||||
def age_in_months(birthdate: date | None, on: date | None) -> float | None:
|
||||
if birthdate is None or on is None or on < birthdate:
|
||||
return None
|
||||
months = (on.year - birthdate.year) * 12 + (on.month - birthdate.month)
|
||||
if on.day < birthdate.day:
|
||||
months -= 1
|
||||
return float(months)
|
||||
|
||||
@@ -7,7 +7,7 @@ from datetime import date, datetime
|
||||
from enum import Enum
|
||||
from typing import Annotated, Any, Optional, Type
|
||||
|
||||
from pydantic import BeforeValidator, StringConstraints, ValidationInfo
|
||||
from pydantic import BeforeValidator, Field, StringConstraints, ValidationInfo
|
||||
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
from extraction import ExtractionError
|
||||
@@ -140,7 +140,7 @@ CodigoPostal = Annotated[str, StringConstraints(pattern=r"^[0-9]{5}$")]
|
||||
|
||||
|
||||
def edf_file(v: Any) -> Any:
|
||||
"""`eeg_estudio.eeg_estudio`: an EDF file MNE can open (TEA amendment).
|
||||
"""`eeg.eeg_estudio`: an EDF file MNE can open (TEA amendment).
|
||||
JSON sources may carry it base64-encoded."""
|
||||
if v is None or (isinstance(v, str) and not v.strip()):
|
||||
return None
|
||||
@@ -168,3 +168,9 @@ FlexDate = Annotated[Optional[date], BeforeValidator(coerce_date)]
|
||||
RequiredDate = Annotated[date, BeforeValidator(required_date)]
|
||||
PostalCode = Annotated[Optional[CodigoPostal], BeforeValidator(coerce_postal_code)]
|
||||
EdfFile = Annotated[Optional[bytes], BeforeValidator(edf_file)]
|
||||
|
||||
|
||||
def Bounded(kind: type, low: float | None = None, high: float | None = None): # noqa: N802 (used like a type)
|
||||
"""An optional number within [low, high], either bound open when None: a score or a count out of range is a
|
||||
validation error, not a stored value."""
|
||||
return Optional[Annotated[kind, Field(ge=low, le=high)]]
|
||||
|
||||
@@ -24,18 +24,14 @@ from persistance.cama import ordenes_estudio_repository as cama_ordenes_estudio_
|
||||
from persistance.cama import paciente_repository as cama_paciente_repository
|
||||
from persistance.repository import Repository
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from persistance.tea import antecedentes_maternos_gestacion_repository as tea_antecedentes_maternos_gestacion_repository
|
||||
from persistance.tea import eeg_estudio_repository as tea_eeg_estudio_repository
|
||||
from persistance.tea import eeg_segmento_repository as tea_eeg_segmento_repository
|
||||
from persistance.tea import evaluacion_psicologica_repository as tea_evaluacion_psicologica_repository
|
||||
from persistance.tea import instrumento_aplicado_repository as tea_instrumento_aplicado_repository
|
||||
from persistance.tea import nota_medica_repository as tea_nota_medica_repository
|
||||
from persistance.tea import ados2_repository as tea_ados2_repository
|
||||
from persistance.tea import eeg_metrica_electrodo_repository as tea_eeg_metrica_electrodo_repository
|
||||
from persistance.tea import eeg_metrica_repository as tea_eeg_metrica_repository
|
||||
from persistance.tea import eeg_repository as tea_eeg_repository
|
||||
from persistance.tea import evaluacion_neuropediatrica_repository as tea_evaluacion_neuropediatrica_repository
|
||||
from persistance.tea import mchat_repository as tea_mchat_repository
|
||||
from persistance.tea import ordenes_estudio_repository as tea_ordenes_estudio_repository
|
||||
from persistance.tea import pacientes_repository as tea_pacientes_repository
|
||||
from persistance.tea import parto_neonatal_repository as tea_parto_neonatal_repository
|
||||
from persistance.tea import (
|
||||
potenciales_evocados_auditivos_repository as tea_potenciales_evocados_auditivos_repository,
|
||||
)
|
||||
from webapi.imports.schemas.cacu.biometria_hematica import (
|
||||
BiometriaHematicaImportSchema as CacuBiometriaHematicaImportSchema,
|
||||
)
|
||||
@@ -62,22 +58,16 @@ from webapi.imports.schemas.cama.ordenes_estudio import (
|
||||
OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.cama.paciente import PacienteImportSchema as CamaPacienteImportSchema
|
||||
from webapi.imports.schemas.tea.antecedentes_maternos_gestacion import (
|
||||
AntecedentesMaternosGestacionImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema
|
||||
from webapi.imports.schemas.tea.eeg_segmento import EegSegmentoImportSchema
|
||||
from webapi.imports.schemas.tea.evaluacion_psicologica import EvaluacionPsicologicaImportSchema
|
||||
from webapi.imports.schemas.tea.instrumento_aplicado import InstrumentoAplicadoImportSchema
|
||||
from webapi.imports.schemas.tea.nota_medica import NotaMedicaImportSchema as TeaNotaMedicaImportSchema
|
||||
from webapi.imports.schemas.tea.ados2 import Ados2ImportSchema
|
||||
from webapi.imports.schemas.tea.eeg import EegImportSchema
|
||||
from webapi.imports.schemas.tea.eeg_metrica import EegMetricaImportSchema
|
||||
from webapi.imports.schemas.tea.eeg_metrica_electrodo import EegMetricaElectrodoImportSchema
|
||||
from webapi.imports.schemas.tea.evaluacion_neuropediatrica import EvaluacionNeuropediatricaImportSchema
|
||||
from webapi.imports.schemas.tea.mchat import MchatImportSchema
|
||||
from webapi.imports.schemas.tea.ordenes_estudio import (
|
||||
OrdenesEstudioImportSchema as TeaOrdenesEstudioImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.tea.pacientes import PacientesImportSchema
|
||||
from webapi.imports.schemas.tea.parto_neonatal import PartoNeonatalImportSchema
|
||||
from webapi.imports.schemas.tea.potenciales_evocados_auditivos import (
|
||||
PotencialesEvocadosAuditivosImportSchema,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -131,8 +121,7 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
|
||||
"cacu.EpisodioClinico": EntitySpec(
|
||||
schema=CacuEpisodioClinicoImportSchema,
|
||||
repository=cacu_episodio_clinico_repository,
|
||||
# No hospital-visible identifier of its own, like EvaluacionPsicologica
|
||||
# or PartoNeonatal; a patient can have several episodes.
|
||||
# No hospital-visible identifier of its own; a patient can have several episodes.
|
||||
conflict_fields=None,
|
||||
),
|
||||
"cama.Paciente": EntitySpec(
|
||||
@@ -175,48 +164,37 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
|
||||
repository=tea_ordenes_estudio_repository,
|
||||
conflict_fields=("ord_id_hospital",),
|
||||
),
|
||||
"tea.NotaMedica": EntitySpec(
|
||||
schema=TeaNotaMedicaImportSchema,
|
||||
repository=tea_nota_medica_repository,
|
||||
conflict_fields=("nm_id_hospital",),
|
||||
"tea.Mchat": EntitySpec(
|
||||
schema=MchatImportSchema,
|
||||
repository=tea_mchat_repository,
|
||||
conflict_fields=("mch_id",),
|
||||
),
|
||||
"tea.EvaluacionPsicologica": EntitySpec(
|
||||
schema=EvaluacionPsicologicaImportSchema,
|
||||
repository=tea_evaluacion_psicologica_repository,
|
||||
conflict_fields=None,
|
||||
"tea.Ados2": EntitySpec(
|
||||
schema=Ados2ImportSchema,
|
||||
repository=tea_ados2_repository,
|
||||
conflict_fields=("ado_id",),
|
||||
),
|
||||
"tea.PotencialesEvocadosAuditivos": EntitySpec(
|
||||
schema=PotencialesEvocadosAuditivosImportSchema,
|
||||
repository=tea_potenciales_evocados_auditivos_repository,
|
||||
conflict_fields=None,
|
||||
"tea.EvaluacionNeuropediatrica": EntitySpec(
|
||||
schema=EvaluacionNeuropediatricaImportSchema,
|
||||
repository=tea_evaluacion_neuropediatrica_repository,
|
||||
conflict_fields=("neu_id",),
|
||||
),
|
||||
"tea.EegEstudio": EntitySpec(
|
||||
schema=EegEstudioImportSchema,
|
||||
repository=tea_eeg_estudio_repository,
|
||||
# The EDF file and its scanned report describe the same study; both
|
||||
# the `edf` connector (from the file's own admin code) and a
|
||||
# `document` source (read from the report text) populate this field,
|
||||
# so merge_duplicates/on_conflict=upsert can land them on one row.
|
||||
"tea.Eeg": EntitySpec(
|
||||
schema=EegImportSchema,
|
||||
repository=tea_eeg_repository,
|
||||
# The EDF file and its report describe the same study; the `edf` connector (from the file's own admin
|
||||
# code) and a `document` source both fill this field, so merge_duplicates/on_conflict=upsert land them on
|
||||
# one row.
|
||||
conflict_fields=("eeg_id_registro_laboratorio",),
|
||||
),
|
||||
"tea.EegSegmento": EntitySpec(
|
||||
schema=EegSegmentoImportSchema,
|
||||
repository=tea_eeg_segmento_repository,
|
||||
conflict_fields=None,
|
||||
"tea.EegMetrica": EntitySpec(
|
||||
schema=EegMetricaImportSchema,
|
||||
repository=tea_eeg_metrica_repository,
|
||||
conflict_fields=("met_id",),
|
||||
),
|
||||
"tea.InstrumentoAplicado": EntitySpec(
|
||||
schema=InstrumentoAplicadoImportSchema,
|
||||
repository=tea_instrumento_aplicado_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.AntecedentesMaternosGestacion": EntitySpec(
|
||||
schema=AntecedentesMaternosGestacionImportSchema,
|
||||
repository=tea_antecedentes_maternos_gestacion_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.PartoNeonatal": EntitySpec(
|
||||
schema=PartoNeonatalImportSchema,
|
||||
repository=tea_parto_neonatal_repository,
|
||||
conflict_fields=None,
|
||||
"tea.EegMetricaElectrodo": EntitySpec(
|
||||
schema=EegMetricaElectrodoImportSchema,
|
||||
repository=tea_eeg_metrica_electrodo_repository,
|
||||
conflict_fields=("mel_id",),
|
||||
),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Import schema for `core.tea.models.Ados2`: module, algorithm, CSS, classification and the 28 algorithm items.
|
||||
|
||||
The domain subtotals and the total aren't imported: they're sums of the items' algorithm scores."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import CLASIFICACION_ADOS2_ALIAS, ClasificacionAdos2, ModuloAdos2
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Bounded, Catalog, CatalogValue, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_MODULO_ADOS2_CATALOG = Catalog(ModuloAdos2)
|
||||
_CLASIFICACION_ADOS2_CATALOG = Catalog(ClasificacionAdos2, CLASIFICACION_ADOS2_ALIAS)
|
||||
_ITEM = Bounded(int, 0, 3)
|
||||
|
||||
|
||||
class Ados2ImportSchema(ImportSchema):
|
||||
ado_id: SourceId = None
|
||||
ado_pac_id: Optional[int] = None
|
||||
ado_ord_id: OptionalStr = None
|
||||
ado_fecha: FlexDate = None
|
||||
ado_modulo: CatalogValue(_MODULO_ADOS2_CATALOG) = None
|
||||
ado_algoritmo: OptionalStr = None
|
||||
ado_css: Bounded(int, 1, 10) = None
|
||||
ado_clasificacion: CatalogValue(_CLASIFICACION_ADOS2_CATALOG) = None
|
||||
|
||||
# Social affect (SA)
|
||||
ado_sa_a2: _ITEM = None
|
||||
ado_sa_a6: _ITEM = None
|
||||
ado_sa_a7: _ITEM = None
|
||||
ado_sa_a8: _ITEM = None
|
||||
ado_sa_b1: _ITEM = None
|
||||
ado_sa_b2: _ITEM = None
|
||||
ado_sa_b3: _ITEM = None
|
||||
ado_sa_b4: _ITEM = None
|
||||
ado_sa_b5: _ITEM = None
|
||||
ado_sa_b6: _ITEM = None
|
||||
ado_sa_b7: _ITEM = None
|
||||
ado_sa_b8: _ITEM = None
|
||||
ado_sa_b9: _ITEM = None
|
||||
ado_sa_b10: _ITEM = None
|
||||
ado_sa_b11: _ITEM = None
|
||||
ado_sa_b12: _ITEM = None
|
||||
ado_sa_b13: _ITEM = None
|
||||
ado_sa_b14: _ITEM = None
|
||||
ado_sa_b15: _ITEM = None
|
||||
ado_sa_b16b: _ITEM = None
|
||||
ado_sa_b18: _ITEM = None
|
||||
|
||||
# Restricted and repetitive behaviour (RRB)
|
||||
ado_rrb_a3: _ITEM = None
|
||||
ado_rrb_a4: _ITEM = None
|
||||
ado_rrb_a5: _ITEM = None
|
||||
ado_rrb_d1: _ITEM = None
|
||||
ado_rrb_d2: _ITEM = None
|
||||
ado_rrb_d4: _ITEM = None
|
||||
ado_rrb_d5: _ITEM = None
|
||||
@@ -1,55 +0,0 @@
|
||||
"""Import schema for `core.tea.models.AntecedentesMaternosGestacion`. All fields
|
||||
optional, like TEA's Core; system-managed `amg_created_at`/`amg_updated_at`/`amg_fuente_sistema` are excluded."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import (
|
||||
CategoriaPesoMaterno,
|
||||
FuenteAntecedenteMaterno,
|
||||
TipoEmbarazo,
|
||||
TrastornoHipertensivoGestacion,
|
||||
VolumenLiquidoAmniotico,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr
|
||||
|
||||
_FUENTE_ANTECEDENTE_MATERNO_CATALOG = Catalog(FuenteAntecedenteMaterno)
|
||||
_CATEGORIA_PESO_MATERNO_CATALOG = Catalog(CategoriaPesoMaterno)
|
||||
_TIPO_EMBARAZO_CATALOG = Catalog(TipoEmbarazo)
|
||||
_TRASTORNO_HIPERTENSIVO_GESTACION_CATALOG = Catalog(TrastornoHipertensivoGestacion)
|
||||
_VOLUMEN_LIQUIDO_AMNIOTICO_CATALOG = Catalog(VolumenLiquidoAmniotico)
|
||||
|
||||
|
||||
class AntecedentesMaternosGestacionImportSchema(ImportSchema):
|
||||
amg_pac_id: Optional[int] = None
|
||||
amg_id_madre_seudonimo: OptionalStr = None
|
||||
amg_fuente_antecedente: CatalogValue(_FUENTE_ANTECEDENTE_MATERNO_CATALOG) = None
|
||||
amg_flag_vinculo_verificado: Optional[int] = None
|
||||
amg_imc_pregestacional: Optional[float] = None
|
||||
amg_categoria_peso_materno: CatalogValue(_CATEGORIA_PESO_MATERNO_CATALOG) = None
|
||||
amg_tabaquismo_gestacion: Optional[int] = None
|
||||
amg_acido_folico_preconcepcional: Optional[int] = None
|
||||
amg_intervalo_intergenesico_meses: Optional[int] = None
|
||||
amg_antecedente_aborto: Optional[int] = None
|
||||
amg_embarazo_multiple: CatalogValue(_TIPO_EMBARAZO_CATALOG) = None
|
||||
amg_infeccion_gestacion: Optional[int] = None
|
||||
amg_infeccion_tipo: OptionalStr = None
|
||||
amg_infeccion_hospitalizacion: Optional[int] = None
|
||||
amg_diabetes_gestacional: Optional[int] = None
|
||||
amg_hipertension_preeclampsia: CatalogValue(_TRASTORNO_HIPERTENSIVO_GESTACION_CATALOG) = None
|
||||
amg_hipotiroidismo: Optional[int] = None
|
||||
amg_hipertiroidismo: Optional[int] = None
|
||||
amg_incompatibilidad_rh: Optional[int] = None
|
||||
amg_crisis_convulsivas: Optional[int] = None
|
||||
amg_proceso_proinflamatorio: Optional[int] = None
|
||||
amg_enfermedad_autoinmune: Optional[int] = None
|
||||
amg_migrana: Optional[int] = None
|
||||
amg_asma: Optional[int] = None
|
||||
amg_hipoxia_materna: Optional[int] = None
|
||||
amg_estres_agudo: Optional[int] = None
|
||||
amg_trastorno_neurologico: Optional[int] = None
|
||||
amg_liquido_amniotico: CatalogValue(_VOLUMEN_LIQUIDO_AMNIOTICO_CATALOG) = None
|
||||
amg_medicamentos_gestacion: OptionalStr = None
|
||||
amg_farmaco_riesgo_neurodesarrollo: Optional[int] = None
|
||||
amg_observaciones: OptionalStr = None
|
||||
amg_ocr_confianza: Optional[float] = None
|
||||
amg_nlp_version: OptionalStr = None
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Import schema for `core.tea.models.Eeg`: the study, its EDF and what the EEG analysis writes back (sleep,
|
||||
channels, duration and the five quality criteria)."""
|
||||
from typing import Optional
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Bounded, EdfFile, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_CHANNELS = Bounded(int, 0, None)
|
||||
|
||||
|
||||
class EegImportSchema(ImportSchema):
|
||||
# The source's own id, kept so the metrics that reference it still point at this record.
|
||||
eeg_id: SourceId = None
|
||||
eeg_pac_id: Optional[int] = None
|
||||
eeg_ord_id: OptionalStr = None
|
||||
eeg_id_registro_laboratorio: OptionalStr = None
|
||||
eeg_fecha_estudio: FlexDate = None
|
||||
eeg_con_sueno: Bounded(int, 0, 1) = None
|
||||
eeg_canales: Bounded(int, 1, 256) = None
|
||||
eeg_duracion_min: Bounded(float, 0, None) = None
|
||||
eeg_canales_amplitud: _CHANNELS = None
|
||||
eeg_canales_alta_frecuencia: _CHANNELS = None
|
||||
eeg_canales_correlacion: _CHANNELS = None
|
||||
eeg_canales_sin_senal: _CHANNELS = None
|
||||
eeg_ruido_linea_db: Bounded(float, 0, None) = None
|
||||
eeg_estudio: EdfFile = None
|
||||
@@ -1,69 +0,0 @@
|
||||
"""Import schema for `core.tea.models.EegEstudio`. All fields optional, like TEA's
|
||||
Core; system-managed `eeg_created_at`/`eeg_updated_at` are excluded."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import (
|
||||
CalidadTecnicaEeg,
|
||||
ConclusionEeg,
|
||||
DistribucionAnormalidad,
|
||||
EstadoRegistroEeg,
|
||||
FuenteInterpretacionEeg,
|
||||
Lentificacion,
|
||||
RespuestaFotoestimulacion,
|
||||
Simetria,
|
||||
TipoGrafoelemento,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, EdfFile, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_FUENTE_INTERPRETACION_EEG_CATALOG = Catalog(FuenteInterpretacionEeg)
|
||||
_ESTADO_REGISTRO_EEG_CATALOG = Catalog(EstadoRegistroEeg)
|
||||
_CALIDAD_TECNICA_EEG_CATALOG = Catalog(CalidadTecnicaEeg)
|
||||
_SIMETRIA_CATALOG = Catalog(Simetria)
|
||||
_TIPO_GRAFOELEMENTO_CATALOG = Catalog(TipoGrafoelemento)
|
||||
_DISTRIBUCION_ANORMALIDAD_CATALOG = Catalog(DistribucionAnormalidad)
|
||||
_LENTIFICACION_CATALOG = Catalog(Lentificacion)
|
||||
_RESPUESTA_FOTOESTIMULACION_CATALOG = Catalog(RespuestaFotoestimulacion)
|
||||
_CONCLUSION_EEG_CATALOG = Catalog(ConclusionEeg)
|
||||
|
||||
|
||||
class EegEstudioImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id still point at this record.
|
||||
eeg_id: SourceId = None
|
||||
eeg_ord_id: OptionalStr = None
|
||||
eeg_pac_id: Optional[int] = None
|
||||
eeg_reporte_disponible: Optional[int] = None
|
||||
eeg_fuente_interpretacion: CatalogValue(_FUENTE_INTERPRETACION_EEG_CATALOG) = None
|
||||
eeg_fecha_nacimiento_archivo: FlexDate = None
|
||||
eeg_edad_meses: Optional[float] = None
|
||||
eeg_fecha_estudio: FlexDate = None
|
||||
eeg_fecha_reporte: FlexDate = None
|
||||
eeg_dias_respuesta: Optional[int] = None
|
||||
eeg_medico_interpreta: OptionalStr = None
|
||||
eeg_estado_registro: CatalogValue(_ESTADO_REGISTRO_EEG_CATALOG) = None
|
||||
eeg_privacion_sueno: Optional[int] = None
|
||||
eeg_sedacion: Optional[int] = None
|
||||
eeg_sedacion_farmaco: OptionalStr = None
|
||||
eeg_duracion_min: Optional[float] = None
|
||||
eeg_calidad_tecnica: CatalogValue(_CALIDAD_TECNICA_EEG_CATALOG) = None
|
||||
eeg_descripcion_senal: OptionalStr = None
|
||||
eeg_ritmo_base_frecuencia: Optional[float] = None
|
||||
eeg_ritmo_base_amplitud: Optional[int] = None
|
||||
eeg_simetria: CatalogValue(_SIMETRIA_CATALOG) = None
|
||||
eeg_anormalidad_presente: Optional[int] = None
|
||||
eeg_actividad_epileptiforme: Optional[int] = None
|
||||
eeg_tipo_grafoelemento: CatalogValue(_TIPO_GRAFOELEMENTO_CATALOG) = None
|
||||
eeg_distribucion_anormalidad: CatalogValue(_DISTRIBUCION_ANORMALIDAD_CATALOG) = None
|
||||
eeg_localizacion: OptionalStr = None
|
||||
eeg_activacion_sueno: Optional[int] = None
|
||||
eeg_lentificacion: CatalogValue(_LENTIFICACION_CATALOG) = None
|
||||
eeg_crisis_registradas: Optional[int] = None
|
||||
eeg_respuesta_fotoestimulacion: CatalogValue(_RESPUESTA_FOTOESTIMULACION_CATALOG) = None
|
||||
eeg_conclusion_texto: OptionalStr = None
|
||||
eeg_conclusion_categoria: CatalogValue(_CONCLUSION_EEG_CATALOG) = None
|
||||
eeg_id_registro_laboratorio: OptionalStr = None
|
||||
eeg_pdf_ruta: OptionalStr = None
|
||||
eeg_ocr_confianza: Optional[float] = None
|
||||
eeg_nlp_version: OptionalStr = None
|
||||
eeg_utilizable: Optional[int] = None
|
||||
eeg_estudio: EdfFile = None
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Import schema for `core.tea.models.EegMetrica`: a metric the EEG analysis measured. A blank value is a metric
|
||||
that can't be evaluated."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import MetricaEeg
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr, SourceId
|
||||
|
||||
_METRICA_CATALOG = Catalog(MetricaEeg)
|
||||
|
||||
|
||||
class EegMetricaImportSchema(ImportSchema):
|
||||
met_id: SourceId = None
|
||||
met_eeg_id: OptionalStr = None
|
||||
met_codigo: CatalogValue(_METRICA_CATALOG) = None
|
||||
met_valor: Optional[float] = None
|
||||
@@ -0,0 +1,12 @@
|
||||
"""Import schema for `core.tea.models.EegMetricaElectrodo`: a metric's z-score at one 10-20 electrode."""
|
||||
from typing import Optional
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import OptionalStr, SourceId
|
||||
|
||||
|
||||
class EegMetricaElectrodoImportSchema(ImportSchema):
|
||||
mel_id: SourceId = None
|
||||
mel_met_id: OptionalStr = None
|
||||
mel_electrodo: OptionalStr = None
|
||||
mel_valor: Optional[float] = None
|
||||
@@ -1,21 +0,0 @@
|
||||
"""Import schema for `core.tea.models.EegSegmento`. All fields optional, like
|
||||
TEA's Core."""
|
||||
from typing import Optional
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import OptionalStr
|
||||
|
||||
|
||||
class EegSegmentoImportSchema(ImportSchema):
|
||||
seg_eeg_id: OptionalStr = None
|
||||
seg_estado: OptionalStr = None
|
||||
seg_inicio_s: Optional[float] = None
|
||||
seg_fin_s: Optional[float] = None
|
||||
seg_duracion_s: Optional[float] = None
|
||||
seg_fuente: OptionalStr = None
|
||||
seg_frecuencia_flash_hz: Optional[float] = None
|
||||
seg_n_destellos: Optional[int] = None
|
||||
seg_cobertura: Optional[float] = None
|
||||
seg_rms_uv: Optional[float] = None
|
||||
seg_emg: Optional[float] = None
|
||||
seg_p2p_max_uv: Optional[float] = None
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Import schema for `core.tea.models.EvaluacionNeuropediatrica`: the note and its ICD-10 diagnosis."""
|
||||
from typing import Annotated, Optional
|
||||
|
||||
from pydantic import BeforeValidator, StringConstraints
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import FlexDate, OptionalStr, SourceId, optional_str
|
||||
|
||||
|
||||
def _upper(v):
|
||||
v = optional_str(v)
|
||||
return v.strip().upper() if isinstance(v, str) else v
|
||||
|
||||
|
||||
# A letter, two digits and optionally a dot with one or two more (F84.0); the dot may be missing (F840).
|
||||
_CIE10 = Annotated[
|
||||
Optional[Annotated[str, StringConstraints(pattern=r"^[A-Z][0-9]{2}(\.?[0-9]{1,2})?$")]],
|
||||
BeforeValidator(_upper),
|
||||
]
|
||||
|
||||
|
||||
class EvaluacionNeuropediatricaImportSchema(ImportSchema):
|
||||
neu_id: SourceId = None
|
||||
neu_pac_id: Optional[int] = None
|
||||
neu_ord_id: OptionalStr = None
|
||||
neu_fecha: FlexDate = None
|
||||
neu_cie_codigo: _CIE10 = None
|
||||
@@ -1,86 +0,0 @@
|
||||
"""Import schema for `core.tea.models.EvaluacionPsicologica`, including the 28
|
||||
ADOS-2 item columns. All fields optional, like TEA's Core; system-managed `psi_created_at`/`psi_updated_at` are excluded."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import (
|
||||
ClasificacionAdos2,
|
||||
InstrumentoTamizaje,
|
||||
ModuloAdos2,
|
||||
NivelRiesgoTamizaje,
|
||||
VentanaMadurativa,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa)
|
||||
_INSTRUMENTO_TAMIZAJE_CATALOG = Catalog(InstrumentoTamizaje)
|
||||
_NIVEL_RIESGO_TAMIZAJE_CATALOG = Catalog(NivelRiesgoTamizaje)
|
||||
_MODULO_ADOS2_CATALOG = Catalog(ModuloAdos2)
|
||||
_CLASIFICACION_ADOS2_CATALOG = Catalog(ClasificacionAdos2)
|
||||
|
||||
|
||||
class EvaluacionPsicologicaImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id still point at this record.
|
||||
psi_id: SourceId = None
|
||||
psi_ord_id: OptionalStr = None
|
||||
psi_pac_id: Optional[int] = None
|
||||
psi_fecha_entrevista_inicial: FlexDate = None
|
||||
psi_fecha_ados2: FlexDate = None
|
||||
psi_fecha_evaluacion: FlexDate = None
|
||||
psi_psicologo: OptionalStr = None
|
||||
psi_edad_meses: Optional[float] = None
|
||||
psi_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None
|
||||
psi_instrumento_tamizaje: CatalogValue(_INSTRUMENTO_TAMIZAJE_CATALOG) = None
|
||||
psi_tamizaje_puntaje: Optional[int] = None
|
||||
psi_tamizaje_riesgo: CatalogValue(_NIVEL_RIESGO_TAMIZAJE_CATALOG) = None
|
||||
psi_ados2_modulo: CatalogValue(_MODULO_ADOS2_CATALOG) = None
|
||||
|
||||
# Items ADOS-2, dominio SA (Interaccion Social Reciproca)
|
||||
psi_ados2_sa_a2: Optional[int] = None
|
||||
psi_ados2_sa_a6: Optional[int] = None
|
||||
psi_ados2_sa_a7: Optional[int] = None
|
||||
psi_ados2_sa_a8: Optional[int] = None
|
||||
psi_ados2_sa_b1: Optional[int] = None
|
||||
psi_ados2_sa_b2: Optional[int] = None
|
||||
psi_ados2_sa_b3: Optional[int] = None
|
||||
psi_ados2_sa_b4: Optional[int] = None
|
||||
psi_ados2_sa_b5: Optional[int] = None
|
||||
psi_ados2_sa_b6: Optional[int] = None
|
||||
psi_ados2_sa_b7: Optional[int] = None
|
||||
psi_ados2_sa_b8: Optional[int] = None
|
||||
psi_ados2_sa_b9: Optional[int] = None
|
||||
psi_ados2_sa_b10: Optional[int] = None
|
||||
psi_ados2_sa_b11: Optional[int] = None
|
||||
psi_ados2_sa_b12: Optional[int] = None
|
||||
psi_ados2_sa_b13: Optional[int] = None
|
||||
psi_ados2_sa_b14: Optional[int] = None
|
||||
psi_ados2_sa_b15: Optional[int] = None
|
||||
psi_ados2_sa_b16b: Optional[int] = None
|
||||
psi_ados2_sa_b18: Optional[int] = None
|
||||
|
||||
# Items ADOS-2, dominio RRB (Conductas Restringidas y Repetitivas)
|
||||
psi_ados2_rrb_a3: Optional[int] = None
|
||||
psi_ados2_rrb_a4: Optional[int] = None
|
||||
psi_ados2_rrb_a5: Optional[int] = None
|
||||
psi_ados2_rrb_d1: Optional[int] = None
|
||||
psi_ados2_rrb_d2: Optional[int] = None
|
||||
psi_ados2_rrb_d4: Optional[int] = None
|
||||
psi_ados2_rrb_d5: Optional[int] = None
|
||||
|
||||
psi_ados2_sa: Optional[int] = None
|
||||
psi_ados2_rrb: Optional[int] = None
|
||||
psi_ados2_total: Optional[int] = None
|
||||
psi_ados2_css: Optional[int] = None
|
||||
psi_ados2_css_sa: Optional[int] = None
|
||||
psi_ados2_css_rrb: Optional[int] = None
|
||||
psi_ados2_clasificacion: CatalogValue(_CLASIFICACION_ADOS2_CATALOG) = None
|
||||
psi_rgd: Optional[int] = None
|
||||
psi_cociente_desarrollo: Optional[float] = None
|
||||
psi_css_umbral_aplicado: Optional[int] = None
|
||||
psi_caso_confirmado: Optional[int] = None
|
||||
psi_cars_total: Optional[float] = None
|
||||
psi_otros_instrumentos: OptionalStr = None
|
||||
psi_regresion_desarrollo: Optional[int] = None
|
||||
psi_diagnostico_texto: OptionalStr = None
|
||||
psi_ocr_confianza: Optional[float] = None
|
||||
psi_nlp_version: OptionalStr = None
|
||||
@@ -1,13 +0,0 @@
|
||||
"""Import schema for `core.tea.models.InstrumentoAplicado`. All fields
|
||||
optional, like TEA's Core."""
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import OptionalStr
|
||||
|
||||
|
||||
class InstrumentoAplicadoImportSchema(ImportSchema):
|
||||
ins_psi_id: OptionalStr = None
|
||||
ins_instrumento: OptionalStr = None
|
||||
ins_informante: OptionalStr = None
|
||||
ins_area: OptionalStr = None
|
||||
ins_interpretacion: OptionalStr = None
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Import schema for `core.tea.models.Mchat`: one M-CHAT-R/F and its total score."""
|
||||
from typing import Optional
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Bounded, FlexDate, OptionalStr, SourceId
|
||||
|
||||
|
||||
class MchatImportSchema(ImportSchema):
|
||||
mch_id: SourceId = None
|
||||
mch_pac_id: Optional[int] = None
|
||||
mch_ord_id: OptionalStr = None
|
||||
mch_fecha: FlexDate = None
|
||||
mch_puntaje: Bounded(int, 0, 20) = None
|
||||
@@ -1,46 +0,0 @@
|
||||
"""Import schema for `core.tea.models.NotaMedica`. All fields optional, like TEA's
|
||||
Core; system-managed `nm_created_at`/`nm_updated_at`/`nm_fuente_sistema` are excluded."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import Especialidad, Pronostico, TipoNota, VentanaMadurativa
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr
|
||||
|
||||
_TIPO_NOTA_CATALOG = Catalog(TipoNota)
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad)
|
||||
_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa)
|
||||
_PRONOSTICO_CATALOG = Catalog(Pronostico)
|
||||
|
||||
|
||||
class NotaMedicaImportSchema(ImportSchema):
|
||||
nm_pac_id: Optional[int] = None
|
||||
nm_id_hospital: OptionalStr = None
|
||||
nm_nota_previa_id: OptionalStr = None
|
||||
nm_tipo_nota: CatalogValue(_TIPO_NOTA_CATALOG) = None
|
||||
nm_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
nm_fecha: FlexDate = None
|
||||
nm_edad_meses: Optional[float] = None
|
||||
nm_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None
|
||||
nm_medico_tratante: OptionalStr = None
|
||||
nm_motivo_consulta: OptionalStr = None
|
||||
nm_interrogatorio: OptionalStr = None
|
||||
nm_regresion_referida: Optional[int] = None
|
||||
nm_antecedente_familiar_tea: Optional[int] = None
|
||||
nm_perimetro_cefalico: Optional[float] = None
|
||||
nm_diagnostico_texto: OptionalStr = None
|
||||
nm_cie_codigo: OptionalStr = None
|
||||
nm_cie_descripcion: OptionalStr = None
|
||||
nm_tratamiento_texto: OptionalStr = None
|
||||
nm_receta: OptionalStr = None
|
||||
nm_plan_estudios: OptionalStr = None
|
||||
nm_pronostico: CatalogValue(_PRONOSTICO_CATALOG) = None
|
||||
nm_observaciones: OptionalStr = None
|
||||
nm_masa_corporal: Optional[float] = None
|
||||
nm_talla: Optional[float] = None
|
||||
nm_imc_visita: Optional[float] = None
|
||||
nm_frecuencia_cardiaca: Optional[int] = None
|
||||
nm_frecuencia_respiratoria: Optional[int] = None
|
||||
nm_presion_arterial_sistolica: Optional[int] = None
|
||||
nm_presion_arterial_diastolica: Optional[int] = None
|
||||
nm_temperatura: Optional[float] = None
|
||||
nm_pdf_ruta: OptionalStr = None
|
||||
@@ -1,37 +1,17 @@
|
||||
"""Import schema for `core.tea.models.OrdenesEstudio`. All fields optional, like
|
||||
TEA's Core; system-managed `ord_*_created_at`/`ord_updated_at`/`ord_fuente_sistema` are excluded."""
|
||||
"""Import schema for `core.tea.models.OrdenesEstudio`: the order of an ADOS-2, a neuropediatrics note or an EEG."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import TIPO_ESTUDIO_ALIAS, Especialidad, EstatusEstudio, TipoEstudio, VentanaMadurativa
|
||||
from core.tea.enums import TIPO_ESTUDIO_ALIAS, TipoEstudio
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad)
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
_ESTATUS_ESTUDIO_CATALOG = Catalog(EstatusEstudio)
|
||||
_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa)
|
||||
|
||||
|
||||
class OrdenesEstudioImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id still point at this record.
|
||||
ord_id: SourceId = None
|
||||
ord_pac_id: Optional[int] = None
|
||||
ord_nota_medica_id: OptionalStr = None
|
||||
ord_id_hospital: OptionalStr = None
|
||||
ord_fecha: FlexDate = None
|
||||
ord_medico_solicitante: OptionalStr = None
|
||||
ord_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
ord_diagnostico_asignado: OptionalStr = None
|
||||
ord_cie_asignado: OptionalStr = None
|
||||
ord_dias_vigencia: Optional[int] = None
|
||||
ord_fecha_vencimiento: FlexDate = None
|
||||
ord_tipo_estudio: CatalogValue(_TIPO_ESTUDIO_CATALOG) = None
|
||||
ord_estatus: CatalogValue(_ESTATUS_ESTUDIO_CATALOG) = None
|
||||
ord_fecha_realizacion: FlexDate = None
|
||||
ord_fecha_resultado: FlexDate = None
|
||||
ord_dias_espera: Optional[int] = None
|
||||
ord_proveedor: OptionalStr = None
|
||||
ord_edad_meses: Optional[float] = None
|
||||
ord_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None
|
||||
ord_pdf_ruta: OptionalStr = None
|
||||
ord_observaciones: OptionalStr = None
|
||||
ord_fecha: FlexDate = None
|
||||
|
||||
@@ -1,24 +1,14 @@
|
||||
"""Import schema for `core.tea.models.Pacientes`. All fields optional, like TEA's
|
||||
Core; system-managed `pac_created_at`/`pac_updated_at`/`pac_fuente_sistema` are excluded.
|
||||
"""Import schema for `core.tea.models.Pacientes`.
|
||||
|
||||
`pac_id` is importable: every other TEA table references the patient by the
|
||||
source system's integer id, so it has to be kept, not renumbered."""
|
||||
`pac_id` is importable: every other TEA table references the patient by the source system's integer id, so it is
|
||||
kept, not renumbered."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import Parentesco, SexoBiologico
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr
|
||||
|
||||
_SEXO_CATALOG = Catalog(SexoBiologico)
|
||||
_PARENTESCO_CATALOG = Catalog(Parentesco)
|
||||
from webapi.imports.schemas.coercion import FlexDate, OptionalStr
|
||||
|
||||
|
||||
class PacientesImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: OptionalStr = None
|
||||
pac_id_titular: OptionalStr = None
|
||||
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
|
||||
pac_fecha_nacimiento: FlexDate = None
|
||||
pac_sexo: CatalogValue(_SEXO_CATALOG) = None
|
||||
pac_codigo_postal_vigente: OptionalStr = None
|
||||
pac_dependencia: OptionalStr = None
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
"""Import schema for `core.tea.models.PartoNeonatal`. All fields optional, like
|
||||
TEA's Core; system-managed `pnn_created_at`/`pnn_updated_at`/`pnn_fuente_sistema` are excluded."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import (
|
||||
ClasificacionEdadGestacional,
|
||||
ComplicacionIntraparto,
|
||||
FuenteAntecedenteNeonatal,
|
||||
TamanoParaEdadGestacional,
|
||||
TipoParto,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr
|
||||
|
||||
_FUENTE_ANTECEDENTE_NEONATAL_CATALOG = Catalog(FuenteAntecedenteNeonatal)
|
||||
_TIPO_PARTO_CATALOG = Catalog(TipoParto)
|
||||
_COMPLICACION_INTRAPARTO_CATALOG = Catalog(ComplicacionIntraparto)
|
||||
_CLASIFICACION_EDAD_GESTACIONAL_CATALOG = Catalog(ClasificacionEdadGestacional)
|
||||
_TAMANO_PARA_EDAD_GESTACIONAL_CATALOG = Catalog(TamanoParaEdadGestacional)
|
||||
|
||||
|
||||
class PartoNeonatalImportSchema(ImportSchema):
|
||||
pnn_pac_id: Optional[int] = None
|
||||
pnn_fuente_antecedente: CatalogValue(_FUENTE_ANTECEDENTE_NEONATAL_CATALOG) = None
|
||||
pnn_tipo_parto: CatalogValue(_TIPO_PARTO_CATALOG) = None
|
||||
pnn_complicaciones_intraparto: Optional[int] = None
|
||||
pnn_complicacion_tipo: CatalogValue(_COMPLICACION_INTRAPARTO_CATALOG) = None
|
||||
pnn_peso_nacer_g: Optional[int] = None
|
||||
pnn_talla_nacer_cm: Optional[float] = None
|
||||
pnn_perimetro_cefalico_nacer_cm: Optional[float] = None
|
||||
pnn_edad_gestacional_sem: Optional[float] = None
|
||||
pnn_clasificacion_eg: CatalogValue(_CLASIFICACION_EDAD_GESTACIONAL_CATALOG) = None
|
||||
pnn_tamano_para_eg: CatalogValue(_TAMANO_PARA_EDAD_GESTACIONAL_CATALOG) = None
|
||||
pnn_peso_nacer_zscore: Optional[float] = None
|
||||
pnn_apgar_1min: Optional[int] = None
|
||||
pnn_apgar_5min: Optional[int] = None
|
||||
pnn_ingreso_ucin: Optional[int] = None
|
||||
pnn_dias_ucin: Optional[int] = None
|
||||
pnn_encefalopatia_hipoxico_isquemica: Optional[int] = None
|
||||
pnn_hipotermia_nacer: Optional[int] = None
|
||||
pnn_hiperbilirrubinemia: Optional[int] = None
|
||||
pnn_fototerapia: Optional[int] = None
|
||||
pnn_hipoglucemia_neonatal: Optional[int] = None
|
||||
pnn_anoxia: Optional[int] = None
|
||||
pnn_sindrome_congenito: Optional[int] = None
|
||||
pnn_sindrome_congenito_desc: OptionalStr = None
|
||||
pnn_flag_riesgo_neonatal: Optional[int] = None
|
||||
pnn_observaciones: OptionalStr = None
|
||||
pnn_ocr_confianza: Optional[float] = None
|
||||
pnn_nlp_version: OptionalStr = None
|
||||
@@ -1,26 +0,0 @@
|
||||
"""Import schema for `core.tea.models.PotencialesEvocadosAuditivos`. All fields
|
||||
optional, like TEA's Core; system-managed `pea_created_at`/`pea_updated_at` are excluded."""
|
||||
from typing import Optional
|
||||
|
||||
from core.tea.enums import GradoHipoacusia
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr
|
||||
|
||||
_GRADO_HIPOACUSIA_CATALOG = Catalog(GradoHipoacusia)
|
||||
|
||||
|
||||
class PotencialesEvocadosAuditivosImportSchema(ImportSchema):
|
||||
pea_ord_id: OptionalStr = None
|
||||
pea_pac_id: Optional[int] = None
|
||||
pea_fecha_estudio: FlexDate = None
|
||||
pea_medico_interpreta: OptionalStr = None
|
||||
pea_umbral_od: Optional[int] = None
|
||||
pea_umbral_oi: Optional[int] = None
|
||||
pea_latencia_v_od: Optional[float] = None
|
||||
pea_latencia_v_oi: Optional[float] = None
|
||||
pea_interpico_i_v_od: Optional[float] = None
|
||||
pea_interpico_i_v_oi: Optional[float] = None
|
||||
pea_grado_hipoacusia: CatalogValue(_GRADO_HIPOACUSIA_CATALOG) = None
|
||||
pea_conclusion_texto: OptionalStr = None
|
||||
pea_flag_diferencial_auditivo: Optional[int] = None
|
||||
pea_ocr_confianza: Optional[float] = None
|
||||
+19
-4
@@ -10,6 +10,7 @@ durations (`webapi.durations`; without `corte_evento`, the day of the last load)
|
||||
import json
|
||||
from collections.abc import Callable
|
||||
from datetime import date, datetime, timezone
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from core.indicadores.tipos import FechaHoraUTC
|
||||
@@ -24,28 +25,42 @@ LOADS = table("carga", column("inicio", FechaHoraUTC))
|
||||
|
||||
|
||||
def definitions_of(project: str, manifest: Path) -> dict:
|
||||
"""Every measure the manifest defines for the domain, by its id (the end of its url)."""
|
||||
"""Every measure the manifest defines for the domain, by its id (the end of its url). A measure that waits for
|
||||
a validation (`meta.requiere_validacion`) is left out until it's given."""
|
||||
return {i: d for i, d in _defined(project, manifest).items() if not _awaits_validation(d)}
|
||||
|
||||
|
||||
@lru_cache
|
||||
def _defined(project: str, manifest: Path) -> dict:
|
||||
every = {**measure_definitions(manifest), **composition_definitions(manifest), **duration_definitions(manifest)}
|
||||
return {d.measure_id: d for d in every.values() if d.url.startswith(f"{project}/")}
|
||||
|
||||
|
||||
def _awaits_validation(definition) -> bool:
|
||||
"""TEA's EEG alterations, the one validation so far, stay hidden until the domain expert validates them."""
|
||||
if not definition.meta.get("requiere_validacion"):
|
||||
return False
|
||||
from webapi.fhir.tea import alterations_validated
|
||||
|
||||
return not alterations_validated()
|
||||
|
||||
|
||||
def kpis_blueprint(project: str, repositories, manifest: Path, *,
|
||||
now: Callable[[], datetime] = lambda: datetime.now(timezone.utc)) -> Blueprint:
|
||||
"""The blueprint of a domain, to register with `url_prefix="/<domain>"`. `repositories` is the domain's
|
||||
`persistance.<domain>` module."""
|
||||
blueprint = Blueprint(f"{project}_kpis", __name__)
|
||||
definitions = definitions_of(project, manifest)
|
||||
|
||||
@blueprint.get("/indicadores")
|
||||
def list_kpis():
|
||||
"""The measures answered on request: id, url, version and scoring."""
|
||||
return jsonify([{"id": i, "url": d.url, "version": d.version, "scoring": scoring_of(d)}
|
||||
for i, d in sorted(definitions.items())])
|
||||
for i, d in sorted(definitions_of(project, manifest).items())])
|
||||
|
||||
@blueprint.get("/indicadores/<measure_id>")
|
||||
def get_kpi(measure_id: str):
|
||||
"""A measure's periods as a FHIR Bundle of MeasureReports, computed on request and kept in the history."""
|
||||
definition = definitions.get(measure_id)
|
||||
definition = definitions_of(project, manifest).get(measure_id)
|
||||
if definition is None:
|
||||
return jsonify({"error": f"no hay un indicador {measure_id!r} calculado bajo pedido"}), 404
|
||||
try:
|
||||
|
||||
+218
-14
@@ -30,6 +30,7 @@ from sqlalchemy import (
|
||||
case,
|
||||
cast,
|
||||
column,
|
||||
desc,
|
||||
distinct,
|
||||
func,
|
||||
literal,
|
||||
@@ -37,6 +38,7 @@ from sqlalchemy import (
|
||||
select,
|
||||
table,
|
||||
text,
|
||||
true,
|
||||
)
|
||||
|
||||
AGGREGATION_VERSION = "md19.1" # the unit-row contract the publication views read
|
||||
@@ -44,7 +46,11 @@ TOTAL = "total"
|
||||
NO_DATA = "sin_dato"
|
||||
AGE_AT_PERIOD_START = "edad_al_inicio_del_periodo"
|
||||
TIMELINE_AT_PERIOD_START = "linea_de_tiempo_al_inicio_del_periodo"
|
||||
TIMELINE_BY_CUTOFF = "linea_de_tiempo_al_corte"
|
||||
OF_THE_CHOSEN = "del_elegido"
|
||||
COLUMN = "columna"
|
||||
STATUS_AT_PERIOD_END = "estado_al_fin_del_periodo"
|
||||
KNOWN_VERSION = "version_conocida"
|
||||
|
||||
|
||||
class UndecidedRule(ValueError):
|
||||
@@ -56,7 +62,8 @@ class Population:
|
||||
"""A simple metric: the units its measure counts, filtered, the FHIR populations it is, and its dates.
|
||||
|
||||
`dated_at` are dates the event cut-off applies to besides the model's own (a biopsy's report); `known_at`, the
|
||||
dates the knowledge cut-off applies to.
|
||||
dates the knowledge cut-off applies to. `at_end`, with a status at the period's end: dates that must have (or must
|
||||
not have) been reached by the period's end, each with when it became known.
|
||||
"""
|
||||
|
||||
metric: str
|
||||
@@ -65,6 +72,53 @@ class Population:
|
||||
codes: tuple[str, ...]
|
||||
dated_at: tuple[str, ...]
|
||||
known_at: tuple[str, ...]
|
||||
at_end: tuple["ReachedByEnd", ...] = ()
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ReachedByEnd:
|
||||
"""A date reached by the period's end (`reached`) or not: dated before the period's end and the event cut-off,
|
||||
and known by the knowledge cut-off."""
|
||||
|
||||
date: str
|
||||
known_at: str | None
|
||||
reached: bool
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class StatusAtEnd:
|
||||
"""Who a period counts and with which row: every unit that entered (`entry`) on or before the period's end and
|
||||
hadn't left (`exit`, known at `exit_known`) before its start, whether or not it has a fact in the period. Each
|
||||
unit is counted with its row of highest `order` dated on or before the period's end (its status then) and known
|
||||
by the cut-offs (`known_at`). With no `order`, the model has one row per unit."""
|
||||
|
||||
entry: str
|
||||
exit: str
|
||||
exit_known: str | None
|
||||
order: str | None
|
||||
known_at: tuple[str, ...]
|
||||
|
||||
@classmethod
|
||||
def of(cls, spec: dict | None) -> "StatusAtEnd | None":
|
||||
if spec is None:
|
||||
return None
|
||||
if spec["tipo"] != STATUS_AT_PERIOD_END:
|
||||
raise NotImplementedError(f"populations of kind {spec['tipo']!r} aren't answered")
|
||||
return cls(spec["ingreso"], spec["salida"], spec.get("salida_conocida_en"), spec.get("orden"),
|
||||
tuple(spec.get("conocida_en", ())))
|
||||
|
||||
def columns(self) -> set[str]:
|
||||
return {self.entry, self.exit, *((self.exit_known,) if self.exit_known else ()),
|
||||
*((self.order,) if self.order else ()), *self.known_at}
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Group:
|
||||
"""One of several groups of a measure: its numerator is the measure's own with this filter instead."""
|
||||
|
||||
name: str
|
||||
label: str
|
||||
filter_sql: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -76,7 +130,11 @@ class Stratum:
|
||||
`fecha` and `conocida_en`) held before the period's start. `valores` are tried in order and the first whose
|
||||
condition holds is the value, else `resto`; a condition (`si`) is a list of alternatives, each a map from a
|
||||
timeline `tipo` to whether there was one;
|
||||
- `del_elegido`: in a composition, the `valor` column of the fact that gave the unit its category.
|
||||
- `linea_de_tiempo_al_corte`: the same, with what the timeline held by the question's event cut-off (all of it
|
||||
without one) instead of before the period's start: a patient's characteristic learned after the fact that
|
||||
put her in the period, such as the stage of a cancer whose biopsy the period counts;
|
||||
- `del_elegido`: in a composition, the `valor` column of the fact that gave the unit its category;
|
||||
- `columna`: a column of the event model (`columna`), one value per unit; `sin_dato` when null.
|
||||
"""
|
||||
|
||||
name: str
|
||||
@@ -89,7 +147,7 @@ class Stratum:
|
||||
|
||||
@classmethod
|
||||
def of(cls, name: str, spec: dict) -> "Stratum":
|
||||
if spec["tipo"] not in (AGE_AT_PERIOD_START, TIMELINE_AT_PERIOD_START, OF_THE_CHOSEN):
|
||||
if spec["tipo"] not in (AGE_AT_PERIOD_START, TIMELINE_AT_PERIOD_START, TIMELINE_BY_CUTOFF, OF_THE_CHOSEN, COLUMN):
|
||||
raise NotImplementedError(f"strata of kind {spec['tipo']!r} aren't answered")
|
||||
return cls(name, spec["tipo"], spec)
|
||||
|
||||
@@ -112,11 +170,26 @@ class MeasureDefinition:
|
||||
rules: dict[str, str]
|
||||
strata: tuple[Stratum, ...]
|
||||
improvement_notation: str | None = None
|
||||
population: StatusAtEnd | None = None
|
||||
groups: tuple[Group, ...] = ()
|
||||
exclusion: Population | None = None
|
||||
meta: dict = dataclasses.field(default_factory=dict, compare=False, hash=False)
|
||||
|
||||
@property
|
||||
def measure_id(self) -> str:
|
||||
return self.url.rsplit("/", 1)[-1]
|
||||
|
||||
def for_group(self, group: Group) -> "MeasureDefinition":
|
||||
"""The definition as one of its groups: the denominator's units, filtered by the group."""
|
||||
numerator = dataclasses.replace(self.denominator, metric=f"{self.numerator.metric}:{group.name}",
|
||||
codes=self.numerator.codes, filter_sql=_both(self.denominator.filter_sql,
|
||||
group.filter_sql))
|
||||
return dataclasses.replace(self, numerator=numerator, group=group.name, groups=(), strata=(), exclusion=None)
|
||||
|
||||
|
||||
def _both(first: str | None, second: str | None) -> str | None:
|
||||
return " and ".join(f"({c})" for c in (first, second) if c) or None
|
||||
|
||||
|
||||
def measure_definitions(manifest: Path) -> dict[str, MeasureDefinition]:
|
||||
"""The ratio metrics of the manifest that declare a `measure_url`, by that url."""
|
||||
@@ -143,10 +216,20 @@ def measure_definitions(manifest: Path) -> dict[str, MeasureDefinition]:
|
||||
group=meta["grupo"], basis=meta["basis"], rules=dict(meta.get("parametros", {})),
|
||||
strata=tuple(Stratum.of(name, s) for name, s in meta.get("estratos", {}).items()),
|
||||
improvement_notation=meta.get("improvement_notation"),
|
||||
population=StatusAtEnd.of(meta.get("poblacion")),
|
||||
groups=tuple(Group(g["grupo"], g.get("etiqueta", g["grupo"]), _unraw(g["filtro"]))
|
||||
for g in meta.get("grupos", ())),
|
||||
exclusion=_population(metrics[meta["exclusion"]], model) if "exclusion" in meta else None,
|
||||
meta=meta,
|
||||
)
|
||||
return definitions
|
||||
|
||||
|
||||
def _unraw(template: str) -> str:
|
||||
"""A `meta` template as written, without the `{% raw %}` that keeps dbt from rendering it."""
|
||||
return template.replace("{% raw %}", "").replace("{% endraw %}", "")
|
||||
|
||||
|
||||
def _semantic_model_of(metric: dict, semantic: dict) -> dict:
|
||||
measure = metric["type_params"]["measure"]["name"]
|
||||
for model in semantic.values():
|
||||
@@ -167,6 +250,8 @@ def _population(metric: dict, model: dict) -> Population:
|
||||
filter_sql=" and ".join(f"({f['where_sql_template']})" for f in filters) or None,
|
||||
codes=tuple(meta["poblaciones_fhir"]), dated_at=tuple(meta.get("fechada_en", ())),
|
||||
known_at=tuple(meta.get("conocida_en", ())),
|
||||
at_end=tuple(ReachedByEnd(a["fecha"], a.get("conocida_en"), bool(a.get("alcanzada", True)))
|
||||
for a in meta.get("al_fin", ())),
|
||||
)
|
||||
|
||||
|
||||
@@ -195,12 +280,25 @@ class MeasureQueries:
|
||||
names = {definition.time_dimension, *definition.dimensions.values(), definition.numerator.measure_expr}
|
||||
# When a fact became known is a load's start (`carga.inicio`): compared with the type it's stored in.
|
||||
known = {definition.dimensions[n] for p in (definition.numerator, definition.denominator) for n in p.known_at}
|
||||
known |= {definition.dimensions[a.known_at] for p in (definition.numerator, definition.denominator)
|
||||
for a in p.at_end if a.known_at}
|
||||
for rule in (getattr(definition, "category", None), getattr(definition, "observation", None)):
|
||||
known |= {definition.dimensions[n] for n in (rule.known_at if rule else ())}
|
||||
self.status = getattr(definition, "population", None)
|
||||
if self.status is not None:
|
||||
names |= {definition.dimensions[n] for n in self.status.columns()}
|
||||
known |= {definition.dimensions[n] for n in (*self.status.known_at, self.status.exit_known) if n}
|
||||
version = (getattr(definition, "meta", None) or {}).get(KNOWN_VERSION)
|
||||
if version is not None:
|
||||
known.add(definition.dimensions[version])
|
||||
self.events = table(definition.relation, *(
|
||||
column(name, FechaHoraUTC) if name in known else column(name) for name in sorted(names)
|
||||
if name.isidentifier()))
|
||||
self.periods = period_table
|
||||
if version is not None:
|
||||
self.events = self._known_version(definition.dimensions[version])
|
||||
if self.status is not None:
|
||||
self.events = self._status_rows()
|
||||
self.birth_day = table("dim_fecha", *map(column, DIM_FECHA)).alias("dia_nacimiento")
|
||||
self.start_day = table("dim_fecha", *map(column, DIM_FECHA)).alias("dia_inicio")
|
||||
self.age_groups = table("dim_grupo_edad", *map(column, DIM_GRUPO_EDAD))
|
||||
@@ -223,9 +321,70 @@ class MeasureQueries:
|
||||
if self.q.knowledge_cutoff is not None:
|
||||
conditions += [self._column(name) <= self.q.knowledge_cutoff for name in population.known_at]
|
||||
conditions += [self._column(name).is_not(None) for name in population.known_at]
|
||||
for date in population.at_end:
|
||||
reached = self._reached_by_end(date.date, date.known_at)
|
||||
conditions.append(reached if date.reached else case((reached, 0), else_=1) == 1)
|
||||
return and_(*conditions) if conditions else None
|
||||
|
||||
def _reached_by_end(self, date: str, known_at: str | None):
|
||||
"""The date is reached by the period's end: dated before it and by the event cut-off, known by the
|
||||
knowledge cut-off. Only with a status at the period's end, whose rows carry the period's bounds."""
|
||||
if self.status is None:
|
||||
raise ValueError(f"{self.d.url}: `al_fin` needs a population at the period's end")
|
||||
value = self._column(date)
|
||||
conditions = [value.is_not(None), value < self.events.c.periodo_fin]
|
||||
if self.q.event_cutoff is not None:
|
||||
conditions.append(value <= self.q.event_cutoff.isoformat())
|
||||
if known_at is not None and self.q.knowledge_cutoff is not None:
|
||||
conditions += [self._column(known_at).is_not(None), self._column(known_at) <= self.q.knowledge_cutoff]
|
||||
return and_(*conditions)
|
||||
|
||||
def _known_version(self, version: str):
|
||||
"""Each unit's rows as they were known at the knowledge cut-off, for a model with one set of rows per unit
|
||||
and knowledge version (`meta.version_conocida`, the column that dates each version): the unit's latest
|
||||
version by the cut-off, or its latest of all without one. A subquery with the model's name, read as the
|
||||
model is."""
|
||||
base = self.events
|
||||
latest = func.rank().over(partition_by=base.c[self.d.numerator.measure_expr], order_by=desc(base.c[version]))
|
||||
versions = select(*base.c, latest.label("lugar_de_version"))
|
||||
if self.q.knowledge_cutoff is not None:
|
||||
versions = versions.where(base.c[version] <= self.q.knowledge_cutoff)
|
||||
versions = versions.subquery("versiones")
|
||||
return (select(*(c for c in versions.c if c.name != "lugar_de_version"))
|
||||
.where(versions.c.lugar_de_version == 1).subquery(self.d.relation))
|
||||
|
||||
def _status_rows(self):
|
||||
"""Each unit the period counts, with its row of highest order: a subquery with the model's name, so the
|
||||
rest of the SQL (filters, strata, counts) reads it as it reads the model, plus the period's bounds.
|
||||
|
||||
A unit is in when it entered by the period's end and hadn't left before its start; a later exit, or one not
|
||||
yet dated or known by the cut-offs, doesn't count. Its rows are those dated before the period's end and by
|
||||
the event cut-off, and known by the knowledge cut-off.
|
||||
"""
|
||||
rule, base, p = self.status, self.events, self.periods.c
|
||||
col = lambda name: base.c[self.d.dimensions[name]] # noqa: E731
|
||||
when, unit = base.c[self.d.time_dimension], base.c[self.d.numerator.measure_expr]
|
||||
conditions = [p.periodo_id == self.q.period_id, when.is_not(None), when < p.fin, col(rule.entry) < p.fin]
|
||||
left = [col(rule.exit).is_not(None), col(rule.exit) < p.inicio]
|
||||
if self.q.event_cutoff is not None:
|
||||
conditions.append(when <= self.q.event_cutoff.isoformat())
|
||||
left.append(col(rule.exit) <= self.q.event_cutoff.isoformat())
|
||||
if self.q.knowledge_cutoff is not None:
|
||||
conditions += [col(n) <= self.q.knowledge_cutoff for n in rule.known_at]
|
||||
if rule.exit_known:
|
||||
left += [col(rule.exit_known).is_not(None), col(rule.exit_known) <= self.q.knowledge_cutoff]
|
||||
conditions.append(case((and_(*left), 1), else_=0) == 0)
|
||||
order = [desc(col(rule.order))] if rule.order else [desc(when)]
|
||||
ranked = (select(*base.c, p.periodo_id.label("periodo_id"), p.inicio.label("periodo_inicio"),
|
||||
p.fin.label("periodo_fin"),
|
||||
func.row_number().over(partition_by=unit, order_by=order).label("lugar_al_fin"))
|
||||
.select_from(base.join(self.periods, true())).where(*conditions).subquery("al_fin_del_periodo"))
|
||||
return (select(*(c for c in ranked.c if c.name != "lugar_al_fin")).where(ranked.c.lugar_al_fin == 1)
|
||||
.subquery(self.d.relation))
|
||||
|
||||
def _in_question(self):
|
||||
if self.status is not None:
|
||||
return self.events.c.periodo_id == self.q.period_id
|
||||
when, p = self.events.c[self.d.time_dimension], self.periods.c
|
||||
conditions = [p.periodo_id == self.q.period_id]
|
||||
if self.q.event_cutoff is not None:
|
||||
@@ -233,12 +392,16 @@ class MeasureQueries:
|
||||
return and_(*conditions)
|
||||
|
||||
def _from(self, *, with_strata: bool):
|
||||
if self.status is not None:
|
||||
if with_strata and any(s.kind not in (COLUMN, OF_THE_CHOSEN) for s in self.d.strata):
|
||||
raise NotImplementedError(f"{self.d.url}: a status at the period's end takes column strata only")
|
||||
return self.events
|
||||
when, p = self.events.c[self.d.time_dimension], self.periods.c
|
||||
joined = self.events.join(self.periods, and_(when >= p.inicio, when < p.fin))
|
||||
if not with_strata:
|
||||
return joined
|
||||
for stratum in self.d.strata:
|
||||
if stratum.kind == OF_THE_CHOSEN:
|
||||
if stratum.kind in (OF_THE_CHOSEN, COLUMN):
|
||||
continue
|
||||
if stratum.kind == AGE_AT_PERIOD_START:
|
||||
joined = (joined
|
||||
@@ -252,7 +415,8 @@ class MeasureQueries:
|
||||
return joined
|
||||
|
||||
def _timeline(self, stratum: Stratum):
|
||||
"""Per patient, one 0/1 column per timeline `tipo` the stratum asks about: had one before the period's start.
|
||||
"""Per patient, one 0/1 column per timeline `tipo` the stratum asks about: had one before the period's start
|
||||
(or, for `linea_de_tiempo_al_corte`, by the event cut-off).
|
||||
|
||||
Known by the knowledge cut-off, if the question has one. Joined, not correlated, so the value can be grouped
|
||||
by on every engine.
|
||||
@@ -263,7 +427,11 @@ class MeasureQueries:
|
||||
line = table(stratum.spec["linea"], column("pac_id"), column("tipo"), column("fecha"),
|
||||
column("conocida_en", FechaHoraUTC))
|
||||
period = self.periods.alias(f"periodo_{stratum.name}")
|
||||
conditions = [line.c.tipo.in_(kinds), line.c.fecha < period.c.inicio]
|
||||
conditions = [line.c.tipo.in_(kinds)]
|
||||
if stratum.kind == TIMELINE_AT_PERIOD_START:
|
||||
conditions.append(line.c.fecha < period.c.inicio)
|
||||
elif self.q.event_cutoff is not None:
|
||||
conditions.append(line.c.fecha <= self.q.event_cutoff.isoformat())
|
||||
if self.q.knowledge_cutoff is not None:
|
||||
conditions.append(line.c.conocida_en <= self.q.knowledge_cutoff)
|
||||
had = (select(line.c.pac_id, *(func.max(case((line.c.tipo == k, 1), else_=0)).label(k) for k in kinds))
|
||||
@@ -283,6 +451,8 @@ class MeasureQueries:
|
||||
return func.coalesce(self.age_groups.c.etiqueta, NO_DATA)
|
||||
if stratum.kind == OF_THE_CHOSEN:
|
||||
return self._column(stratum.spec["valor"])
|
||||
if stratum.kind == COLUMN:
|
||||
return func.coalesce(self._column(stratum.spec["columna"]), NO_DATA)
|
||||
had = self._timeline(stratum).c
|
||||
|
||||
def holds(alternative: dict):
|
||||
@@ -306,9 +476,15 @@ class MeasureQueries:
|
||||
return (select(value, *self._cells()).select_from(self._from(with_strata=True))
|
||||
.where(self._in_question()).group_by(value))
|
||||
|
||||
def excluded(self) -> Select:
|
||||
"""The units of the measure's exclusion (`meta.exclusion`): in the period, but out of its denominator."""
|
||||
unit, condition = self.events.c[self.d.exclusion.measure_expr], self._filter(self.d.exclusion)
|
||||
counted = unit if condition is None else case((condition, unit))
|
||||
return select(func.count(distinct(counted))).select_from(self._from(with_strata=False)).where(self._in_question())
|
||||
|
||||
def rows(self, report_id: int, unit_model, stratum_model) -> Iterable[tuple[type, Select]]:
|
||||
"""What `INSERT … SELECT` writes: each unit in each population code, then each unit's value of each stratum."""
|
||||
for population in (self.d.denominator, self.d.numerator):
|
||||
for population in (self.d.denominator, self.d.numerator, *((self.d.exclusion,) if self.d.exclusion else ())):
|
||||
unit = self.events.c[population.measure_expr]
|
||||
condition = self._filter(population)
|
||||
where = self._in_question() if condition is None else and_(self._in_question(), condition)
|
||||
@@ -372,6 +548,8 @@ class Answer:
|
||||
total: Counts
|
||||
strata: dict[str, dict[str, Counts]]
|
||||
stored_before: bool
|
||||
groups: dict[str, Counts] = dataclasses.field(default_factory=dict) # by group, for a measure with several
|
||||
excluded: int | None = None # the units of its exclusion, when it has one
|
||||
|
||||
@property
|
||||
def numerator(self) -> int:
|
||||
@@ -397,7 +575,8 @@ def answer(project: str, definition: MeasureDefinition, question: Question, *, p
|
||||
key, key_sha = key_of(definition, question, values)
|
||||
stored = history.find(definition.url, key_sha)
|
||||
if stored is not None:
|
||||
return _from_counts(definition, stored, history.counts(stored))
|
||||
return _from_counts(definition, stored, history.counts(stored),
|
||||
history.group_counts(stored) if definition.groups else {})
|
||||
|
||||
period = periods.get(question.period_id)
|
||||
if period is None:
|
||||
@@ -408,6 +587,13 @@ def answer(project: str, definition: MeasureDefinition, question: Question, *, p
|
||||
for stratum in definition.strata:
|
||||
_, cells = queries.rows(sql.counts_by_stratum(stratum))
|
||||
strata[stratum.name] = {value: Counts(n, d) for value, n, d in cells}
|
||||
excluded = queries.rows(sql.excluded())[1][0][0] if definition.exclusion else None
|
||||
group_sql, groups = [], {}
|
||||
for group in definition.groups:
|
||||
g = MeasureQueries(definition.for_group(group), question, values, periods.model.__table__)
|
||||
_, ((n, d),) = queries.rows(g.counts())
|
||||
groups[group.name] = Counts(n, d)
|
||||
group_sql.append(g)
|
||||
models = import_module(f"core.{project}.indicadores.models")
|
||||
(any_rule,) = parameters.list(limit=1)
|
||||
report = models.MeasureReport(
|
||||
@@ -418,15 +604,21 @@ def answer(project: str, definition: MeasureDefinition, question: Question, *, p
|
||||
status="complete", tipo="summary", generado_en=now or datetime.now(timezone.utc),
|
||||
agregacion_version=AGGREGATION_VERSION,
|
||||
huella=hashlib.sha256(json.dumps([key_sha, numerator, denominator, sorted(
|
||||
(s, v, c.numerator, c.denominator) for s, cells in strata.items() for v, c in cells.items())]).encode()
|
||||
(s, v, c.numerator, c.denominator) for s, cells in strata.items() for v, c in cells.items()),
|
||||
excluded, sorted((g, c.numerator, c.denominator) for g, c in groups.items())]).encode()
|
||||
).hexdigest(),
|
||||
)
|
||||
report_id = history.record(report, lambda rid: sql.rows(rid, models.MeasureReportUnidad,
|
||||
models.MeasureReportUnidadEstrato))
|
||||
return Answer(report_id, Counts(numerator, denominator), strata, stored_before=False)
|
||||
|
||||
def rows(rid):
|
||||
for queries_of in (sql, *group_sql):
|
||||
yield from queries_of.rows(rid, models.MeasureReportUnidad, models.MeasureReportUnidadEstrato)
|
||||
|
||||
report_id = history.record(report, rows)
|
||||
return Answer(report_id, Counts(numerator, denominator), strata, stored_before=False, groups=groups,
|
||||
excluded=excluded)
|
||||
|
||||
|
||||
def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict) -> Answer:
|
||||
def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict, by_group: dict | None = None) -> Answer:
|
||||
numerator, denominator = (f"{definition.measure_id}.{c}" for c in (definition.numerator.codes[0],
|
||||
definition.denominator.codes[0]))
|
||||
cells: dict[tuple[str, str], list[int]] = {}
|
||||
@@ -440,7 +632,19 @@ def _from_counts(definition: MeasureDefinition, report_id: int, counts: dict) ->
|
||||
for (stratum, value), (n, d) in cells.items():
|
||||
if stratum != TOTAL:
|
||||
strata.setdefault(stratum, {})[value] = Counts(n, d)
|
||||
return Answer(report_id, Counts(*cells.get((TOTAL, TOTAL), (0, 0))), strata, stored_before=True)
|
||||
excluded = None
|
||||
if definition.exclusion is not None:
|
||||
code = f"{definition.measure_id}.{definition.exclusion.codes[0]}"
|
||||
excluded = sum(n for (stratum, _, resultado, _), n in counts.items() if stratum == TOTAL and resultado == code)
|
||||
groups = {}
|
||||
if definition.groups:
|
||||
by_group = by_group or {}
|
||||
groups = {g.name: Counts(by_group.get((g.name, numerator), 0), by_group.get((g.name, denominator), 0))
|
||||
for g in definition.groups}
|
||||
totals = Counts(by_group.get((definition.group, numerator), 0), by_group.get((definition.group, denominator), 0))
|
||||
else:
|
||||
totals = Counts(*cells.get((TOTAL, TOTAL), (0, 0)))
|
||||
return Answer(report_id, totals, strata, stored_before=True, groups=groups, excluded=excluded)
|
||||
|
||||
|
||||
# --- the contract --------------------------------------------------------------------------------------------------
|
||||
|
||||
@@ -15,7 +15,7 @@ from pathlib import Path
|
||||
from webapi.orchestration.context import Context
|
||||
from webapi.orchestration.runner import run
|
||||
|
||||
PROJECTS = ("cacu", "cama")
|
||||
PROJECTS = ("cacu", "cama", "tea")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> None:
|
||||
|
||||
@@ -15,6 +15,7 @@ from pathlib import Path
|
||||
from typing import NamedTuple
|
||||
|
||||
import core
|
||||
from extraction.nlp.text import fold
|
||||
from core.indicadores.catalogos import TIPOS_DE_VALOR
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
@@ -54,6 +55,7 @@ def catalogo_desde_toml(ruta: Path, *, tablas: TablasKit) -> Catalogo:
|
||||
for nombre, resultado in estudio.get("resultados", {}).items():
|
||||
resultado_id = f"{estudio_id}.{nombre}"
|
||||
tipo_valor = _tipo_de_valor(resultado, resultado_id)
|
||||
_claves_de_extraccion(resultado, resultado_id)
|
||||
resultados.append(
|
||||
tablas.CatResultado(
|
||||
resultado_id=resultado_id,
|
||||
@@ -93,6 +95,64 @@ def codigos_hospital(proyecto: str) -> dict[str, str]:
|
||||
return codigos
|
||||
|
||||
|
||||
class ResultadoExtraible(NamedTuple):
|
||||
"""A result read from a document's text: the captions it's printed under and, if coded, each value's spellings."""
|
||||
|
||||
resultado_id: str
|
||||
tipo_valor: str
|
||||
etiquetas_fuente: tuple[str, ...]
|
||||
alias: dict[str, tuple[str, ...]] # valor -> its spellings, the label included
|
||||
buscar_en_texto: bool # also as a mention anywhere in the text, without a caption
|
||||
provisional: bool
|
||||
|
||||
|
||||
def resultados_extraibles(proyecto: str) -> dict[str, ResultadoExtraible]:
|
||||
"""`resultado_id` -> how it's found in a document, for every result of the catalog with `etiquetas_fuente`.
|
||||
|
||||
The mapping lives in the catalog so that a new caption or spelling from the laboratory is one line there:
|
||||
the next load reads it, and nothing already stored is renamed.
|
||||
"""
|
||||
extraibles = {}
|
||||
for estudio_id, estudio in _leer(ruta_de_catalogo(proyecto)).items():
|
||||
for nombre, resultado in estudio.get("resultados", {}).items():
|
||||
resultado_id = f"{estudio_id}.{nombre}"
|
||||
_claves_de_extraccion(resultado, resultado_id)
|
||||
if "etiquetas_fuente" not in resultado:
|
||||
continue
|
||||
extraibles[resultado_id] = ResultadoExtraible(
|
||||
resultado_id=resultado_id,
|
||||
tipo_valor=resultado["tipo_valor"],
|
||||
etiquetas_fuente=tuple(resultado["etiquetas_fuente"]),
|
||||
alias={v["valor"]: (v["etiqueta"], *v.get("alias", ())) for v in resultado.get("valores", ())},
|
||||
buscar_en_texto=bool(resultado.get("buscar_en_texto", False)),
|
||||
provisional=bool(resultado.get("provisional", False)),
|
||||
)
|
||||
return extraibles
|
||||
|
||||
|
||||
def _claves_de_extraccion(resultado: dict, resultado_id: str) -> None:
|
||||
"""The extraction keys of a result: captions as a non-empty list of texts, and no spelling on two values."""
|
||||
etiquetas = resultado.get("etiquetas_fuente")
|
||||
if etiquetas is not None and (not isinstance(etiquetas, list) or not etiquetas
|
||||
or not all(isinstance(e, str) and e.strip() for e in etiquetas)):
|
||||
raise CatalogoInvalido(f"{resultado_id}: etiquetas_fuente es una lista de textos, no vacía.")
|
||||
if etiquetas is None and ("buscar_en_texto" in resultado or any("alias" in v for v in resultado.get("valores", ()))):
|
||||
raise CatalogoInvalido(f"{resultado_id}: alias y buscar_en_texto solo sirven con etiquetas_fuente.")
|
||||
if etiquetas is not None and resultado.get("tipo_valor") not in ("codigo", "numero", "fecha", "texto"):
|
||||
raise CatalogoInvalido(f"{resultado_id}: un resultado de tipo {resultado.get('tipo_valor')} no se extrae de texto.")
|
||||
if resultado.get("buscar_en_texto") and resultado.get("tipo_valor") != "codigo":
|
||||
raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo se busca como mención en el texto.")
|
||||
de: dict[str, str] = {}
|
||||
for valor in resultado.get("valores", ()):
|
||||
for forma in (valor.get("etiqueta", ""), *valor.get("alias", ())):
|
||||
clave = " ".join(fold(forma).split())
|
||||
if de.get(clave, valor["valor"]) != valor["valor"]:
|
||||
raise CatalogoInvalido(
|
||||
f"{resultado_id}: {forma!r} se escribe igual para {de[clave]!r} y {valor['valor']!r}."
|
||||
)
|
||||
de[clave] = valor["valor"]
|
||||
|
||||
|
||||
def _leer(ruta: Path) -> dict:
|
||||
return tomllib.loads(Path(ruta).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@@ -51,12 +51,6 @@ valor = 1
|
||||
estado = "provisional"
|
||||
fuente = "Propuesta T-21g: el horizonte de `cama/cohorte_tamizaje` (sin definir, MD-Q14). Decide clínica con modelos (MD-Q5)"
|
||||
|
||||
[tea.riesgos.horizonte_banda]
|
||||
# Años desde el M-CHAT índice: el horizonte del desenlace de la cohorte de tamizaje (48 meses).
|
||||
valor = 4
|
||||
estado = "provisional"
|
||||
fuente = "Responsable de TEA, 2026-10-21: 48 meses. Sin uso mientras la cohorte de TEA sea propuesta (T-21h)"
|
||||
|
||||
[comun.catalogos.banda_riesgo]
|
||||
# Las bandas del resumen de riesgos, de menor a mayor.
|
||||
valor = [
|
||||
@@ -90,10 +84,10 @@ estado = "provisional"
|
||||
fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-10-12). Cortes del grupo blanco (indicadores_kit_0), sin confirmar"
|
||||
|
||||
# ===========================================================================
|
||||
# TEA · los 18 indicadores de ulises (M2 a M19, K1 a K8)
|
||||
# TEA · the screening's indicators (M21 to M30)
|
||||
#
|
||||
# Copia de ulises/parametros.toml, con el prefijo "tea.". La clave es la
|
||||
# ruta con puntos: [tea.cohorte.edad_min_meses] -> "tea.cohorte.edad_min_meses".
|
||||
# The key is the dotted path: [tea.cohorte.edad_min_meses] -> "tea.cohorte.edad_min_meses".
|
||||
# The measures read their rules from dbt's var `tea` (Transformation/dbt_project.yml), which holds the same values.
|
||||
# Las listas y tablas se guardan en def_parametro como JSON.
|
||||
# El umbral de supresión es comun.umbral_supresion; tea.supresion.activa lo apaga.
|
||||
# Documentos citados (repositorio analisis-tea, carpeta docs/):
|
||||
@@ -102,9 +96,10 @@ fuente = "Propuesta para v0.5.0, falta que clínica la confirme (usuario, 2026-1
|
||||
# ===========================================================================
|
||||
|
||||
[tea.cohorte.edad_min_meses]
|
||||
# The cohort: children whose first M-CHAT was at 16 to 36 completed months.
|
||||
valor = 16
|
||||
estado = "confirmado"
|
||||
fuente = "contexto §1: ADOS-2 y EEG ligado, de 16 a 36 meses cumplidos a la fecha del EEG (director)"
|
||||
fuente = "Responsable del proyecto, 2026-11-11: edad cumplida al primer M-CHAT, de 16 a 36 meses"
|
||||
|
||||
[tea.cohorte.edad_max_meses]
|
||||
valor = 36
|
||||
@@ -117,97 +112,23 @@ valor = 30.4375
|
||||
estado = "confirmado"
|
||||
fuente = "analisis-tea/tea/comun.py, edad_meses"
|
||||
|
||||
[tea.cohorte.plazo_ados2_eeg_dias]
|
||||
# ADOS-2 y EEG a este número de días o menos, en cualquier orden: solo marca diagnostico_eeg_en_plazo.
|
||||
valor = 30
|
||||
estado = "confirmado"
|
||||
fuente = "contexto §1: más de un mes de diferencia afecta la validez (director)"
|
||||
|
||||
[tea.cohorte.ventanas]
|
||||
# Ventanas madurativas por meses cumplidos a la fecha del EEG, sin huecos.
|
||||
# Age groups, by completed months at the first M-CHAT, without gaps: the windows of the TEA page.
|
||||
valor = [
|
||||
{ clave = "V1_16_23", desde = 16, hasta = 23, etiqueta = "16 a 23 meses", color = "#9DBFE3" },
|
||||
{ clave = "V2_24_30", desde = 24, hasta = 30, etiqueta = "24 a 30 meses", color = "#5E93CC" },
|
||||
{ clave = "V3_31_36", desde = 31, hasta = 36, etiqueta = "31 a 36 meses", color = "#1B4A80" },
|
||||
{ clave = "16_23", desde = 16, hasta = 23, etiqueta = "16 a 23 meses", color = "#9DBFE3" },
|
||||
{ clave = "24_29", desde = 24, hasta = 29, etiqueta = "24 a 29 meses", color = "#5E93CC" },
|
||||
{ clave = "30_36", desde = 30, hasta = 36, etiqueta = "30 a 36 meses", color = "#1B4A80" },
|
||||
]
|
||||
estado = "confirmado"
|
||||
fuente = "contexto §1: revisión bibliográfica del proyecto. Colores: paleta de ejemplo (provisional)"
|
||||
|
||||
[tea.instrumentos.informantes_ramos]
|
||||
# Orden de preferencia cuando contestaron varios: la madre; si no contestó, el padre.
|
||||
valor = ["MADRE", "PADRE", "OTRO_CUIDADOR", "NO_REGISTRADO"]
|
||||
estado = "confirmado"
|
||||
fuente = "contexto §1 (equipo); psicología no registra al cuidador principal"
|
||||
|
||||
[tea.instrumentos.informantes_otros]
|
||||
valor = ["MADRE", "PADRE", "OTRO_CUIDADOR", "OBSERVACION_CLINICA", "MAESTRO", "NO_REGISTRADO"]
|
||||
estado = "confirmado"
|
||||
fuente = "analisis-tea/tea/config.py, INFORMANTE_PRIORIDAD['_otros']; confirmado por el responsable de TEA, 2026-10-21"
|
||||
|
||||
[tea.ramos.areas]
|
||||
# «TOTAL» no cuenta como área.
|
||||
valor = [
|
||||
{ clave = "COGNOSCITIVO", etiqueta = "Cognoscitivo" },
|
||||
{ clave = "LINGUISTICO", etiqueta = "Lingüístico" },
|
||||
{ clave = "FISICO", etiqueta = "Físico" },
|
||||
{ clave = "SOCIOEMOCIONAL", etiqueta = "Socioemocional" },
|
||||
{ clave = "ADAPTATIVO", etiqueta = "Adaptativo" },
|
||||
]
|
||||
estado = "confirmado"
|
||||
fuente = "spec v2, catálogo de ins_area; contexto §1"
|
||||
|
||||
[tea.poblacion.css_min_tea]
|
||||
# M21 y M22: TEA positivo si el CSS del ADOS-2 es al menos este valor.
|
||||
valor = 3
|
||||
estado = "confirmado"
|
||||
fuente = "responsable de TEA, 2026-10-21: CSS de 3 a 4, espectro; de 5 a 10, autismo"
|
||||
fuente = "Responsable del proyecto, 2026-11-10: las ventanas de la página de TEA. Colores: paleta de ejemplo (provisional)"
|
||||
|
||||
[tea.diagnostico.cie_tea]
|
||||
# M24 y M25: códigos CIE-10 de la nota médica que confirman el diagnóstico, sin punto (F84.0 -> F840).
|
||||
# M21 to M25: ICD-10 codes of the neuropediatrics note that confirm the diagnosis, without the dot (F84.0 -> F840).
|
||||
# F84 without its subcode doesn't count.
|
||||
valor = ["F840"]
|
||||
estado = "confirmado"
|
||||
fuente = "usuario (2026-10-15): solo F84.0 (autismo)"
|
||||
|
||||
[tea.diagnostico.instrumentos_mchat]
|
||||
# M25: valores de psi_instrumento_tamizaje que son un M-CHAT.
|
||||
valor = ["M_CHAT_R", "M_CHAT_RF"]
|
||||
estado = "confirmado"
|
||||
fuente = "Core, enum InstrumentoTamizaje (psi_instrumento_tamizaje)"
|
||||
|
||||
[tea.atencion.plazo_referencia_evaluacion_dias]
|
||||
# K1: inicio de la evaluación a más tardar este número de días después de la referencia.
|
||||
valor = 90
|
||||
estado = "confirmado"
|
||||
fuente = "estandares: NICE QS51, enunciado 1 (3 meses)"
|
||||
|
||||
[tea.parto.apgar_corte]
|
||||
# Apgar a los 5 minutos: menor de este valor, igual, y mayor (8 a 10).
|
||||
valor = 7
|
||||
estado = "confirmado"
|
||||
fuente = "lista, M17: menor de 7, 7, y 8 a 10"
|
||||
|
||||
# Las cuatro reglas siguientes las usa el mapeo (tea/mapeo.py) al cargar:
|
||||
# un cambio pide volver a cargar.
|
||||
[tea.antecedentes_maternos.no_registrado]
|
||||
valor = "NO_REGISTRADO"
|
||||
estado = "confirmado"
|
||||
fuente = "spec v2: NO_REGISTRADO = sin dato"
|
||||
|
||||
[tea.antecedentes_maternos.hipertension_ninguno]
|
||||
valor = "NINGUNO"
|
||||
estado = "confirmado"
|
||||
fuente = "spec v2, catálogo de amg_hipertension_preeclampsia"
|
||||
|
||||
[tea.antecedentes_maternos.embarazo_no_unico]
|
||||
valor = ["GEMELAR", "TRIPLE_O_MAS"]
|
||||
estado = "confirmado"
|
||||
fuente = "spec v2, catálogo de amg_embarazo_multiple"
|
||||
|
||||
[tea.antecedentes_maternos.liquido_anormal]
|
||||
valor = ["OLIGOHIDRAMNIOS", "POLIHIDRAMNIOS"]
|
||||
estado = "confirmado"
|
||||
fuente = "spec v2, catálogo de amg_liquido_amniotico"
|
||||
|
||||
[tea.supresion.activa]
|
||||
# Apagada: el tablero es de uso interno del equipo y los médicos. Con false no se
|
||||
# suprime nada, aunque comun.umbral_supresion tenga valor.
|
||||
@@ -232,54 +153,6 @@ valor = { etiqueta = "Sin dato", color = "#C9CDD2" }
|
||||
estado = "confirmado"
|
||||
fuente = "lista: «sin dato» siempre se muestra como categoría propia"
|
||||
|
||||
[tea.catalogos.sexo]
|
||||
valor = [
|
||||
{ clave = "F", etiqueta = "Femenino", color = "#E0A030" },
|
||||
{ clave = "M", etiqueta = "Masculino", color = "#2F6DB3" },
|
||||
{ clave = "I", etiqueta = "Indeterminado", color = "#8A9199" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "spec v2, pac_sexo; colores provisionales"
|
||||
|
||||
[tea.catalogos.resultado_mchat]
|
||||
valor = [
|
||||
{ clave = "RIESGO_BAJO", etiqueta = "Riesgo bajo", color = "#F3E6D3" },
|
||||
{ clave = "RIESGO_MEDIO", etiqueta = "Riesgo medio", color = "#E8C28E" },
|
||||
{ clave = "RIESGO_ALTO", etiqueta = "Riesgo alto", color = "#B55A1F" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "spec v2, interpretación del M-CHAT-R/F (bajo 0–2, medio 3–7, alto 8–20); colores provisionales"
|
||||
|
||||
[tea.catalogos.interpretacion_ramos]
|
||||
valor = [
|
||||
{ clave = "DESARROLLO_ADECUADO", etiqueta = "Desarrollo adecuado", color = "#9DBFE3" },
|
||||
{ clave = "MONITOREO", etiqueta = "Monitoreo", color = "#E8C28E" },
|
||||
{ clave = "RETRASO", etiqueta = "Retraso", color = "#B55A1F" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "nota_para_cargas.md, interpretación de Ramos; colores provisionales"
|
||||
|
||||
[tea.catalogos.grado_hipoacusia]
|
||||
valor = [
|
||||
{ clave = "NORMAL", etiqueta = "Normal", color = "#F3E6D3" },
|
||||
{ clave = "LEVE", etiqueta = "Leve", color = "#E8C28E" },
|
||||
{ clave = "MODERADA", etiqueta = "Moderada", color = "#D98E4A" },
|
||||
{ clave = "SEVERA", etiqueta = "Severa", color = "#B55A1F" },
|
||||
{ clave = "PROFUNDA", etiqueta = "Profunda", color = "#B55A1F" },
|
||||
{ clave = "NO_CONCLUYENTE", etiqueta = "No concluyente", color = "#8A9199" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "spec v2, pea_grado_hipoacusia; colores provisionales"
|
||||
|
||||
[tea.catalogos.apgar_5min]
|
||||
valor = [
|
||||
{ clave = "MENOR_7", etiqueta = "Menor de 7", color = "#B55A1F" },
|
||||
{ clave = "SIETE", etiqueta = "7", color = "#E8C28E" },
|
||||
{ clave = "OCHO_A_DIEZ", etiqueta = "8 a 10", color = "#9DBFE3" },
|
||||
]
|
||||
estado = "provisional"
|
||||
fuente = "lista, M17; colores provisionales"
|
||||
|
||||
# ===========================================================================
|
||||
# CaCu · reglas de IND1 (movidas de campo/parametros_campo.toml)
|
||||
# ===========================================================================
|
||||
|
||||
@@ -25,8 +25,9 @@ def event_views(manifest: Path, project: str) -> list:
|
||||
"""`drop view if exists` and `create view … as <compiled SQL>` for every model the project's measures read,
|
||||
parents first.
|
||||
|
||||
Those are the project's models semantic models count over (`models/<project>/…`) and the timelines its strata
|
||||
read (`meta.estratos.*.linea`), with the non-ephemeral models they're built on; an ephemeral one is already inlined
|
||||
Those are the project's models semantic models count over (`models/<project>/…`), the timelines its strata
|
||||
read (`meta.estratos.*.linea`) and the views the WebApi reads (`meta.lee_la_webapi`), with the non-ephemeral
|
||||
models they're built on; an ephemeral one is already inlined
|
||||
in its child's compiled SQL. Another domain's models aren't created: their tables may not exist here.
|
||||
"""
|
||||
m = json.loads(manifest.read_text(encoding="utf-8"))
|
||||
@@ -37,6 +38,9 @@ def event_views(manifest: Path, project: str) -> list:
|
||||
roots |= {by_name[spec["linea"]] for metric in m["metrics"].values()
|
||||
if metric["config"].get("meta", {}).get("measure_url", "").startswith(f"{project}/")
|
||||
for spec in metric["config"]["meta"].get("estratos", {}).values() if "linea" in spec}
|
||||
# The views the WebApi reads directly (a follow-up list, a patient summary).
|
||||
roots |= {uid for uid, n in nodes.items() if n["resource_type"] == "model" and n["fqn"][1] == project
|
||||
and n["config"].get("meta", {}).get("lee_la_webapi")}
|
||||
ordered: list[str] = []
|
||||
|
||||
def visit(uid: str) -> None:
|
||||
@@ -69,10 +73,14 @@ def catalog_layers(project: str, manifest: Path) -> list[list]:
|
||||
contract = CONTRACTS[scoring_of(d)]
|
||||
measures.append(t.CatMeasure(measure_id=d.measure_id, url=d.url, version=d.version, titulo=labels[d.metric],
|
||||
contrato=contract, unidad=d.basis))
|
||||
codes = dict.fromkeys((*d.denominator.codes, *d.numerator.codes, *((OBSERVATION,) if contract == "C3r" else ())))
|
||||
exclusion = getattr(d, "exclusion", None)
|
||||
codes = dict.fromkeys((*d.denominator.codes, *d.numerator.codes, *((OBSERVATION,) if contract == "C3r" else ()),
|
||||
*(exclusion.codes if exclusion else ())))
|
||||
children += [t.CatMeasureResultado(resultado_id=f"{d.measure_id}.{c}", measure_id=d.measure_id, poblacion=c,
|
||||
etiqueta=c) for c in codes]
|
||||
children.append(t.CatMeasureGrupo(measure_id=d.measure_id, grupo=d.group, etiqueta=d.group, orden=0))
|
||||
children += [t.CatMeasureGrupo(measure_id=d.measure_id, grupo=g.name, etiqueta=g.label, orden=i)
|
||||
for i, g in enumerate(getattr(d, "groups", ()), 1)]
|
||||
children += [t.CatMeasureEstrato(measure_id=d.measure_id, estrato_id=s.name) for s in d.strata]
|
||||
stratum_rows = [t.CatEstrato(estrato_id=s, etiqueta=labels_of[s], unidad="paciente") for s in strata]
|
||||
return [stratum_rows + measures, children]
|
||||
|
||||
@@ -7,6 +7,7 @@ derivadas. La lee `plata_desde_staging` (`plata.carga.carga_desde_staging`).
|
||||
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente
|
||||
from core.cama.nota_medica.enums import ESPECIALIDAD_ALIAS, Especialidad
|
||||
|
||||
from webapi.orchestration.silver.extracted import DesdeTexto
|
||||
from webapi.orchestration.silver.orders_and_notes import nota_medica, orden_de_estudio
|
||||
from webapi.orchestration.silver.procedures import DeStaging, Hija, Padre
|
||||
|
||||
@@ -23,6 +24,23 @@ def _biopsia_que_pasa(fila) -> bool:
|
||||
return fila.bx_fecha_solicitud is not None or fila.bx_fecha_reporte is not None
|
||||
|
||||
|
||||
# Results read from text, with how the catalog says each is printed (`etiquetas_fuente`, `alias`): the
|
||||
# radiologist's interpretation, the pathology report's text layer, and the note's diagnosis and prognosis.
|
||||
DE_LA_INTERPRETACION = DesdeTexto(
|
||||
"cama", ("mastografia.densidad", "mastografia.tamano_lesion_mm"), texto=lambda f: f.mast_interpretacion,
|
||||
)
|
||||
DEL_REPORTE_DE_PATOLOGIA = DesdeTexto(
|
||||
"cama",
|
||||
("biopsia.tipo_histologico", "biopsia.grado_nottingham", "biopsia.receptor_estrogeno",
|
||||
"biopsia.receptor_estrogeno_pct", "biopsia.receptor_progesterona", "biopsia.receptor_progesterona_pct",
|
||||
"biopsia.her2", "biopsia.ki67_pct"),
|
||||
texto=lambda f: f.bx_pdf_blob,
|
||||
)
|
||||
DE_LA_NOTA = DesdeTexto(
|
||||
"cama", ("nota_medica.estadio_clinico",),
|
||||
texto=lambda f: "\n".join(t for t in (f.nm_diagnostico_texto, f.nm_pronostico) if t),
|
||||
)
|
||||
|
||||
DESDE_STAGING = (
|
||||
DeStaging(
|
||||
Mastografia, "mast_id", "toma", estudio_id="mastografia", fecha="mast_fecha_toma",
|
||||
@@ -33,14 +51,17 @@ DESDE_STAGING = (
|
||||
DeStaging(
|
||||
Mastografia, "mast_id", "reporte", estudio_id="mastografia", fecha="mast_fecha_reporte",
|
||||
solo_si=lambda f: f.mast_fecha_reporte is not None, padres=(LA_MASTOGRAFIA_DE_SU_FILA,),
|
||||
resultados={"mast_birads": "mastografia.birads"},
|
||||
derivadas=DE_LA_INTERPRETACION.derivadas,
|
||||
resultados={"mast_birads": "mastografia.birads", **DE_LA_INTERPRETACION.resultados},
|
||||
fuentes=DE_LA_INTERPRETACION.fuentes,
|
||||
),
|
||||
DeStaging(
|
||||
BiopsiaMama, "bx_id", "orden", estudio_id="biopsia", fecha="bx_fecha_solicitud",
|
||||
solo_si=_biopsia_que_pasa, padres=(LA_MASTOGRAFIA_DE_SU_FILA,), columnas={"orden_numero": "ord_numero_hospital"},
|
||||
derivadas=DEL_REPORTE_DE_PATOLOGIA.derivadas, fuentes=DEL_REPORTE_DE_PATOLOGIA.fuentes,
|
||||
hijas=(Hija("biopsia", "reporte", solo_si=("bx_fecha_reporte",), fecha="bx_fecha_reporte",
|
||||
resultados={"bx_grado_histologico": "biopsia.grado"}),),
|
||||
resultados={"bx_grado_histologico": "biopsia.grado", **DEL_REPORTE_DE_PATOLOGIA.resultados}),),
|
||||
),
|
||||
orden_de_estudio(OrdenesEstudio, ESPECIALIDAD_ALIAS, ESPECIALIDADES),
|
||||
nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES),
|
||||
nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES, extraidos=DE_LA_NOTA),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Results of the catalog read from a staging row's text: a report's interpretation, a note, a PDF's text layer.
|
||||
|
||||
The catalog says how each result is printed (`etiquetas_fuente`, each value's `alias`;
|
||||
`reference.catalogs.resultados_extraibles`); `DesdeTexto` turns that into Extraction's field specs and into the
|
||||
derived columns, results and sources of a `DeStaging`. A coded value comes out as its `valor_id` when one of its
|
||||
spellings matches, and always with what was read as `valor_fuente`: a spelling the catalog doesn't know yet stays
|
||||
stored as text, counted as out of catalog by the silver check, and becomes a code on the next load after its alias
|
||||
is added. Nothing extracted is written anywhere but silver's two tables.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from functools import lru_cache
|
||||
|
||||
from extraction import BBox, ExtractionError, FieldKind, FieldSpec, Line, read_document
|
||||
from extraction.nlp.extractors import RecordExtractor, SegmentLine
|
||||
|
||||
from webapi.orchestration.reference.catalogs import ResultadoExtraible, resultados_extraibles
|
||||
|
||||
# A value read after a caption, kept as its source when the catalog doesn't know it: enough to recognize it.
|
||||
LARGO_DE_FUENTE = 120
|
||||
TIPOS = {"codigo": FieldKind.CHOICE, "numero": FieldKind.DECIMAL, "fecha": FieldKind.DATE, "texto": FieldKind.TEXT}
|
||||
SUFIJO_DE_TEXTO = "#texto" # the plain-text twin of a coded field: what follows its caption, matched or not
|
||||
|
||||
|
||||
def especificaciones(resultado: ResultadoExtraible) -> tuple[FieldSpec, ...]:
|
||||
"""Extraction's fields for one result: the result itself and, if coded, the text after its caption."""
|
||||
choices = {forma: valor for valor, formas in resultado.alias.items() for forma in formas}
|
||||
campo = FieldSpec(
|
||||
resultado.resultado_id, TIPOS[resultado.tipo_valor], labels=resultado.etiquetas_fuente,
|
||||
choices=choices, scan_free_text=resultado.buscar_en_texto,
|
||||
)
|
||||
if resultado.tipo_valor != "codigo":
|
||||
return (campo,)
|
||||
return campo, FieldSpec(resultado.resultado_id + SUFIJO_DE_TEXTO, FieldKind.TEXT, labels=resultado.etiquetas_fuente)
|
||||
|
||||
|
||||
def lineas_de_texto(texto: str, nombre: str = "texto") -> list[SegmentLine]:
|
||||
"""A plain text as the lines of one page, as a reader would give them."""
|
||||
renglones = [r for r in texto.splitlines() if r.strip()]
|
||||
alto = 1 / max(len(renglones), 1)
|
||||
return [SegmentLine(nombre, 1, Line(r, BBox(0, i * alto, 1, (i + 1) * alto))) for i, r in enumerate(renglones)]
|
||||
|
||||
|
||||
def lineas_de_pdf(contenido: bytes) -> list[SegmentLine]:
|
||||
"""The text layer of a PDF, without OCR: a load doesn't run OCR, and a scan without text gives no lines."""
|
||||
try:
|
||||
documento = read_document("documento.pdf", contenido, ocr_mode="never")
|
||||
except ExtractionError:
|
||||
return []
|
||||
return [SegmentLine(documento.name, p.number, linea) for p in documento.pages for linea in p.lines]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DesdeTexto:
|
||||
"""Catalog results read from what `texto` gives for a row: a text, a PDF's bytes, or nothing.
|
||||
|
||||
`derivadas`, `resultados` and `fuentes` go into the `DeStaging` (or its `Hija`) as they are. The row is read
|
||||
once for all its results.
|
||||
"""
|
||||
|
||||
proyecto: str
|
||||
resultado_ids: tuple[str, ...]
|
||||
texto: Callable[[object], str | bytes | None]
|
||||
_extraer: Callable = field(init=False, repr=False, compare=False)
|
||||
|
||||
def __post_init__(self):
|
||||
extraibles = resultados_extraibles(self.proyecto)
|
||||
faltan = [r for r in self.resultado_ids if r not in extraibles]
|
||||
if faltan:
|
||||
raise ValueError(f"Sin etiquetas_fuente en el catálogo de {self.proyecto}: {', '.join(faltan)}.")
|
||||
tipos = {r: extraibles[r].tipo_valor for r in self.resultado_ids}
|
||||
extractor = RecordExtractor([e for r in self.resultado_ids for e in especificaciones(extraibles[r])])
|
||||
|
||||
@lru_cache(maxsize=256)
|
||||
def extraer(contenido: str | bytes) -> dict[str, tuple]:
|
||||
lineas = lineas_de_pdf(contenido) if isinstance(contenido, bytes) else lineas_de_texto(contenido)
|
||||
leidos = extractor.extract(lineas)
|
||||
return {r: _valor_y_fuente(leidos.get(r), leidos.get(r + SUFIJO_DE_TEXTO), tipos[r]) for r in tipos}
|
||||
|
||||
object.__setattr__(self, "_extraer", extraer)
|
||||
|
||||
def leer(self, fila) -> dict[str, tuple]:
|
||||
"""`resultado_id` -> (value, source) read from the row; (None, None) when it isn't there."""
|
||||
contenido = self.texto(fila)
|
||||
if not contenido or (isinstance(contenido, str) and not contenido.strip()):
|
||||
return dict.fromkeys(self.resultado_ids, (None, None))
|
||||
return self._extraer(contenido)
|
||||
|
||||
@property
|
||||
def derivadas(self) -> dict[str, Callable]:
|
||||
columnas = {}
|
||||
for r in self.resultado_ids:
|
||||
columnas[_columna(r)] = lambda f, r=r: self.leer(f)[r][0]
|
||||
columnas[_columna(r) + "_fuente"] = lambda f, r=r: self.leer(f)[r][1]
|
||||
return columnas
|
||||
|
||||
@property
|
||||
def resultados(self) -> dict[str, str]:
|
||||
return {_columna(r): r for r in self.resultado_ids}
|
||||
|
||||
@property
|
||||
def fuentes(self) -> dict[str, str]:
|
||||
return {_columna(r): _columna(r) + "_fuente" for r in self.resultado_ids}
|
||||
|
||||
|
||||
def _columna(resultado_id: str) -> str:
|
||||
return "extraido:" + resultado_id
|
||||
|
||||
|
||||
def _valor_y_fuente(leido, texto, tipo_valor: str) -> tuple:
|
||||
"""A coded value with the spelling it matched, or, unmatched, with what followed its caption; others as read."""
|
||||
if tipo_valor != "codigo":
|
||||
return (None, None) if leido is None else (leido.value, None)
|
||||
if leido is not None:
|
||||
return leido.value, leido.raw
|
||||
if texto is not None and str(texto.value).strip():
|
||||
return None, str(texto.value).strip()[:LARGO_DE_FUENTE]
|
||||
return None, None
|
||||
@@ -9,11 +9,13 @@ da sus tablas y su catálogo de especialidades. Es la normalización que hacían
|
||||
como llegó;
|
||||
- el CIE-10 de la nota, sin espacios ni punto y en mayúsculas; su identificador del hospital, en `id_hospital`;
|
||||
- el motivo de consulta y el diagnóstico en texto, solo si el proyecto los pide (`con_textos`, CaCu: T-24b),
|
||||
sin normalizarlos (I-K61).
|
||||
sin normalizarlos (I-K61);
|
||||
- the catalog results a project reads from the note's texts (`extraidos`, CaMa's clinical stage).
|
||||
"""
|
||||
|
||||
from collections.abc import Collection, Mapping
|
||||
|
||||
from webapi.orchestration.silver.extracted import DesdeTexto
|
||||
from webapi.orchestration.silver.values import INTENCION, cie, codigo_de_especialidad, texto_limpio
|
||||
from webapi.orchestration.silver.procedures import DeStaging
|
||||
|
||||
@@ -52,22 +54,26 @@ def orden_de_estudio(staging: type, alias: Mapping[str, str], codigos: Collectio
|
||||
|
||||
|
||||
def nota_medica(
|
||||
staging: type, alias: Mapping[str, str], codigos: Collection[str], *, con_textos: bool = False
|
||||
staging: type, alias: Mapping[str, str], codigos: Collection[str], *, con_textos: bool = False,
|
||||
extraidos: DesdeTexto | None = None,
|
||||
) -> DeStaging:
|
||||
textos = {
|
||||
"motivo": lambda f: texto_limpio(f.nm_motivo_consulta),
|
||||
"diagnostico_texto": lambda f: texto_limpio(f.nm_diagnostico_texto),
|
||||
} if con_textos else {}
|
||||
leidos = extraidos.derivadas if extraidos else {}
|
||||
return DeStaging(
|
||||
staging, "nm_id", "encuentro", estudio_id="nota_medica", fecha="nm_fecha",
|
||||
columnas={"id_hospital": "nm_id_hospital"}, # para ligarla después con sus órdenes (provisional)
|
||||
derivadas={
|
||||
"cie_codigo": lambda f: cie(f.nm_cie_codigo), **especialidad("nm_especialidad", alias, codigos), **textos,
|
||||
**leidos,
|
||||
},
|
||||
resultados={
|
||||
"cie_codigo": "nota_medica.diagnostico",
|
||||
"especialidad": "nota_medica.especialidad",
|
||||
**({f: f"nota_medica.{f}" for f in textos}),
|
||||
**(extraidos.resultados if extraidos else {}),
|
||||
},
|
||||
fuentes={"especialidad": "especialidad_fuente"},
|
||||
fuentes={"especialidad": "especialidad_fuente", **(extraidos.fuentes if extraidos else {})},
|
||||
)
|
||||
|
||||
@@ -14,6 +14,7 @@ llave lógica del procedimiento (`fuente_tabla`, `fuente_id`, `estudio_id`,
|
||||
|
||||
from collections.abc import Callable, Iterable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from types import SimpleNamespace
|
||||
from typing import NamedTuple
|
||||
|
||||
from webapi.orchestration.reference.catalogs import Catalogo
|
||||
@@ -59,6 +60,16 @@ class Hija:
|
||||
resultados: Mapping[str, str] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Junta:
|
||||
"""Another staging row whose columns the row's content takes: the row of `staging` whose `llave` equals the
|
||||
row's column `columna` (an electrode value takes its metric's code and EEG). Without a match, they're null."""
|
||||
|
||||
staging: type
|
||||
llave: str
|
||||
columna: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DeStaging:
|
||||
"""Un procedimiento que sale de cada fila de una tabla de staging (staging directo, T-20c).
|
||||
@@ -72,6 +83,10 @@ class DeStaging:
|
||||
no es un reporte); no es un descarte.
|
||||
- `descartar(fila, pacientes)`: el motivo por el que la fila no entra, que se cuenta en
|
||||
`descartes`. `pacientes`: los `pac_id` de la tabla de pacientes del staging.
|
||||
- `juntas`: rows of other staging tables whose columns join the content before the derived ones.
|
||||
- `observa_en`: the row gives no procedure of its own; its observations go on the procedure this parent key
|
||||
names (a metric of an EEG is a result of the EEG's recording). `clase` is unused then.
|
||||
A result's template can name the content's columns (`eeg.{metrica}`) besides `{estudio}`.
|
||||
|
||||
Staging llega resuelto y completo (usuario, 2026-10-21): la carga no valida que no falte nada.
|
||||
Un procedimiento sin paciente ni padre queda huérfano y se cuenta al escribir (I-MD17).
|
||||
@@ -92,6 +107,8 @@ class DeStaging:
|
||||
paciente: str | None = "pac_id"
|
||||
solo_si: Callable | None = None
|
||||
descartar: Callable | None = None
|
||||
juntas: tuple[Junta, ...] = ()
|
||||
observa_en: Padre | None = None
|
||||
|
||||
|
||||
class LotePlata(NamedTuple):
|
||||
@@ -124,6 +141,7 @@ def plata_desde_staging(
|
||||
pacientes = set(pacientes)
|
||||
tipos, vigentes = _tipos_y_vigentes(catalogo)
|
||||
procedimientos, observaciones, descartes = [], [], {}
|
||||
indices: dict[tuple[str, str], dict] = {}
|
||||
for c in correspondencias:
|
||||
tabla = c.staging.__tablename__
|
||||
for fila in filas.get(tabla, ()):
|
||||
@@ -133,7 +151,13 @@ def plata_desde_staging(
|
||||
continue
|
||||
if c.solo_si is not None and not c.solo_si(fila):
|
||||
continue
|
||||
contenido = {**fila.model_dump(), **{nombre: f(fila) for nombre, f in c.derivadas.items()}}
|
||||
contenido = fila.model_dump()
|
||||
if c.juntas:
|
||||
for junta in c.juntas:
|
||||
unida = _junta(junta, filas, indices).get(contenido.get(junta.columna))
|
||||
contenido = {**(unida or dict.fromkeys(junta.staging.model_fields)), **contenido}
|
||||
fila = SimpleNamespace(**contenido)
|
||||
contenido = {**contenido, **{nombre: f(fila) for nombre, f in c.derivadas.items()}}
|
||||
contenido["pac_id"] = None if c.paciente is None else contenido.get(c.paciente)
|
||||
contenido.update({destino: contenido.get(origen) for destino, origen in c.columnas.items()})
|
||||
_repartir(c, tabla, tabla, fuente_id, contenido, tuple(c.columnas), codigos_hospital,
|
||||
@@ -168,6 +192,14 @@ def en_orden_de_padres(procedimientos: list[dict]) -> list[dict]:
|
||||
return sorted(procedimientos, key=lambda p: (de(p["llave"]), ORDEN_DE_CLASES.index(p["llave"][3])))
|
||||
|
||||
|
||||
def _junta(junta: Junta, filas: Mapping[str, Iterable], indices: dict) -> dict:
|
||||
"""The rows of the joined table by their key, as dictionaries; built once per batch."""
|
||||
clave = (junta.staging.__tablename__, junta.llave)
|
||||
if clave not in indices:
|
||||
indices[clave] = {getattr(f, junta.llave): f.model_dump() for f in filas.get(clave[0], ())}
|
||||
return indices[clave]
|
||||
|
||||
|
||||
def _tipos_y_vigentes(catalogo: Catalogo) -> tuple[dict, set]:
|
||||
tipos = {r.resultado_id: r.tipo_valor for r in catalogo.resultados}
|
||||
vigentes = {(v.resultado_id, v.valor_id) for v in catalogo.valores if v.estado == "vigente"}
|
||||
@@ -183,6 +215,11 @@ def _repartir(c, nombre: str, fuente_tabla: str, fuente_id, contenido: dict, col
|
||||
motivo = f"{nombre}: {c.estudio_de} fuera de catálogo"
|
||||
descartes[motivo] = descartes.get(motivo, 0) + 1
|
||||
return
|
||||
if c.observa_en is not None:
|
||||
dueno = _parent(c.observa_en, contenido)
|
||||
if dueno is not None:
|
||||
observaciones += _observaciones(dueno, contenido, c.resultados, c.fuentes, tipos, vigentes)
|
||||
return
|
||||
llave = (fuente_tabla, str(fuente_id), estudio_id, c.clase)
|
||||
procedimientos.append({
|
||||
"llave": llave,
|
||||
@@ -225,7 +262,9 @@ def _observaciones(llave: Llave, contenido: dict, resultados: Mapping[str, str],
|
||||
tipos: dict, vigentes: set) -> list[dict]:
|
||||
filas = []
|
||||
for columna, plantilla in resultados.items():
|
||||
resultado_id = plantilla.format(estudio=llave[2])
|
||||
resultado_id = plantilla.format_map({**contenido, "estudio": llave[2]})
|
||||
if resultado_id not in tipos and "{" in plantilla.replace("{estudio}", ""):
|
||||
continue # a value of the row names a result the catalog doesn't have (an unknown metric)
|
||||
filas.append({
|
||||
"procedimiento": llave,
|
||||
"pac_id": contenido.get("pac_id"),
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
"""TEA in the two-table silver: what each staging row gives, as `DESDE_STAGING` (read by `carga_desde_staging`).
|
||||
|
||||
- an order is an `orden` of the study it asks for (`ord_tipo_estudio`, in Core's code or one of its aliases);
|
||||
- the M-CHAT is a `toma`, the ADOS-2 and the neuropediatrics note are `encuentro`s, the EEG is a `toma`; each
|
||||
hangs from its order when it has one;
|
||||
- an EEG metric is a result of its EEG's recording, not a procedure; a metric's electrode value is a `parte` of the
|
||||
EEG (`codigo_fuente` the electrode) with the metric's result. Both find their EEG through the metric's row.
|
||||
"""
|
||||
|
||||
from core.tea.enums import (
|
||||
CLASIFICACION_ADOS2_ALIAS,
|
||||
TIPO_ESTUDIO_ALIAS,
|
||||
ClasificacionAdos2,
|
||||
ModuloAdos2,
|
||||
TipoEstudio,
|
||||
)
|
||||
from core.tea.models import (
|
||||
ADOS2_ITEMS,
|
||||
Ados2,
|
||||
Eeg,
|
||||
EegMetrica,
|
||||
EegMetricaElectrodo,
|
||||
EvaluacionNeuropediatrica,
|
||||
Mchat,
|
||||
OrdenesEstudio,
|
||||
Pacientes,
|
||||
)
|
||||
|
||||
from webapi.orchestration.silver.procedures import DeStaging, Junta, Padre
|
||||
from webapi.orchestration.silver.values import INTENCION, cie, codigo_de_especialidad, texto_limpio
|
||||
|
||||
PACIENTES = Pacientes # where persons come from
|
||||
ORDENES = OrdenesEstudio.__tablename__
|
||||
EEG = Eeg.__tablename__
|
||||
|
||||
|
||||
def _codigo(columna: str, enum, alias: dict | None = None):
|
||||
codigos = {e.value for e in enum}
|
||||
return lambda f: codigo_de_especialidad(getattr(f, columna), alias or {}, codigos)
|
||||
|
||||
|
||||
def _su_orden(estudio_id: str, columna: str) -> Padre:
|
||||
"""The order a study row names by its `*_ord_id`."""
|
||||
return Padre(estudio_id=estudio_id, clase="orden", fuente_id=columna, tabla=ORDENES)
|
||||
|
||||
|
||||
def _metrica(f) -> str | None:
|
||||
"""A metric's result in the catalog: its code in lower case (`RITMO_POSTERIOR` -> `ritmo_posterior`)."""
|
||||
codigo = texto_limpio(f.met_codigo)
|
||||
return None if codigo is None else codigo.lower()
|
||||
|
||||
|
||||
SU_EEG = Padre(estudio_id="eeg", clase="toma", fuente_id="met_eeg_id", tabla=EEG)
|
||||
|
||||
|
||||
DESDE_STAGING = (
|
||||
DeStaging(
|
||||
OrdenesEstudio, "ord_id", "orden", estudio_de="tipo_estudio", fecha="ord_fecha", paciente="ord_pac_id",
|
||||
derivadas={
|
||||
"tipo_estudio": _codigo("ord_tipo_estudio", TipoEstudio, TIPO_ESTUDIO_ALIAS),
|
||||
"intencion": lambda f: INTENCION,
|
||||
},
|
||||
columnas={"id_hospital": "ord_id_hospital", "codigo_fuente": "ord_tipo_estudio"},
|
||||
resultados={"intencion": "orden.intencion"},
|
||||
),
|
||||
DeStaging(
|
||||
Mchat, "mch_id", "toma", estudio_id="mchat", fecha="mch_fecha", paciente="mch_pac_id",
|
||||
padres=(_su_orden("mchat", "mch_ord_id"),),
|
||||
resultados={"mch_puntaje": "mchat.puntaje"},
|
||||
),
|
||||
DeStaging(
|
||||
Ados2, "ado_id", "encuentro", estudio_id="ados2", fecha="ado_fecha", paciente="ado_pac_id",
|
||||
padres=(_su_orden("ados2", "ado_ord_id"),),
|
||||
derivadas={
|
||||
"modulo": _codigo("ado_modulo", ModuloAdos2),
|
||||
"clasificacion": _codigo("ado_clasificacion", ClasificacionAdos2, CLASIFICACION_ADOS2_ALIAS),
|
||||
"algoritmo": lambda f: texto_limpio(f.ado_algoritmo),
|
||||
},
|
||||
resultados={
|
||||
"modulo": "ados2.modulo",
|
||||
"algoritmo": "ados2.algoritmo",
|
||||
"clasificacion": "ados2.clasificacion",
|
||||
"ado_css": "ados2.css",
|
||||
**{f"ado_{item}": f"ados2.{item}" for item in ADOS2_ITEMS},
|
||||
},
|
||||
fuentes={"modulo": "ado_modulo", "clasificacion": "ado_clasificacion"},
|
||||
),
|
||||
DeStaging(
|
||||
EvaluacionNeuropediatrica, "neu_id", "encuentro", estudio_id="evaluacion_neuropediatrica",
|
||||
fecha="neu_fecha", paciente="neu_pac_id", padres=(_su_orden("evaluacion_neuropediatrica", "neu_ord_id"),),
|
||||
derivadas={"cie_codigo": lambda f: cie(f.neu_cie_codigo)},
|
||||
resultados={"cie_codigo": "evaluacion_neuropediatrica.diagnostico"},
|
||||
),
|
||||
DeStaging(
|
||||
Eeg, "eeg_id", "toma", estudio_id="eeg", fecha="eeg_fecha_estudio", paciente="eeg_pac_id",
|
||||
padres=(_su_orden("eeg", "eeg_ord_id"),), columnas={"id_hospital": "eeg_id_registro_laboratorio"},
|
||||
resultados={
|
||||
"eeg_con_sueno": "eeg.con_sueno",
|
||||
"eeg_canales": "eeg.canales",
|
||||
"eeg_duracion_min": "eeg.duracion_min",
|
||||
"eeg_canales_amplitud": "eeg.calidad_amplitud",
|
||||
"eeg_canales_alta_frecuencia": "eeg.calidad_alta_frecuencia",
|
||||
"eeg_canales_correlacion": "eeg.calidad_correlacion",
|
||||
"eeg_canales_sin_senal": "eeg.calidad_sin_senal",
|
||||
"eeg_ruido_linea_db": "eeg.calidad_linea",
|
||||
},
|
||||
),
|
||||
DeStaging(
|
||||
EegMetrica, "met_id", "toma", estudio_id="eeg", paciente=None, observa_en=SU_EEG,
|
||||
derivadas={"metrica": _metrica},
|
||||
resultados={"met_valor": "eeg.{metrica}"},
|
||||
),
|
||||
DeStaging(
|
||||
EegMetricaElectrodo, "mel_id", "parte", estudio_id="eeg", paciente=None,
|
||||
juntas=(Junta(EegMetrica, "met_id", "mel_met_id"),), padres=(SU_EEG,),
|
||||
derivadas={"metrica": _metrica},
|
||||
columnas={"codigo_fuente": "mel_electrodo"},
|
||||
resultados={"mel_valor": "eeg.{metrica}"},
|
||||
),
|
||||
)
|
||||
@@ -14,7 +14,7 @@ from importlib import import_module
|
||||
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
PROJECTS = ("cacu", "cama")
|
||||
PROJECTS = ("cacu", "cama", "tea")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""TEA's tables: in `Core`, in the domain's registry.
|
||||
|
||||
`TABLAS` is what the shared code receives to work with this project; TEA's person adds nothing (its `sexo` stays null).
|
||||
"""
|
||||
|
||||
from core.tea.indicadores.models import (
|
||||
CatMeasure,
|
||||
CatMeasureResultado,
|
||||
CatMeasureValor,
|
||||
CatMeasureGrupo,
|
||||
CatEstrato,
|
||||
CatEstratoValor,
|
||||
CatMeasureEstrato,
|
||||
MeasureReportUnidad,
|
||||
MeasureReportUnidadEstrato,
|
||||
CatEstudio,
|
||||
CatResultado,
|
||||
CatValor,
|
||||
Observacion,
|
||||
Procedimiento,
|
||||
CohorteArmado,
|
||||
CohorteExclusion,
|
||||
CohorteMiembro,
|
||||
CohorteVariable,
|
||||
EvaluacionRiesgo,
|
||||
EvaluacionRiesgoLote,
|
||||
Carga,
|
||||
DefParametro,
|
||||
DimFecha,
|
||||
DimGrupoEdad,
|
||||
DimPeriodo,
|
||||
MeasureReport,
|
||||
PeriodoObservacion,
|
||||
Persona,
|
||||
)
|
||||
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
from webapi.orchestration.tables import TablasKit
|
||||
|
||||
__all__ = ["TABLAS", "COHORTES"]
|
||||
|
||||
TABLAS = TablasKit(
|
||||
Persona=Persona,
|
||||
PeriodoObservacion=PeriodoObservacion,
|
||||
Carga=Carga,
|
||||
DefParametro=DefParametro,
|
||||
DimPeriodo=DimPeriodo,
|
||||
DimFecha=DimFecha,
|
||||
DimGrupoEdad=DimGrupoEdad,
|
||||
MeasureReport=MeasureReport,
|
||||
CatEstudio=CatEstudio,
|
||||
CatResultado=CatResultado,
|
||||
CatValor=CatValor,
|
||||
Procedimiento=Procedimiento,
|
||||
Observacion=Observacion,
|
||||
CatMeasure=CatMeasure,
|
||||
CatMeasureResultado=CatMeasureResultado,
|
||||
CatMeasureValor=CatMeasureValor,
|
||||
CatMeasureGrupo=CatMeasureGrupo,
|
||||
CatEstrato=CatEstrato,
|
||||
CatEstratoValor=CatEstratoValor,
|
||||
CatMeasureEstrato=CatMeasureEstrato,
|
||||
MeasureReportUnidad=MeasureReportUnidad,
|
||||
MeasureReportUnidadEstrato=MeasureReportUnidadEstrato,
|
||||
)
|
||||
|
||||
# Cohorts for models and their risk estimates: TEA builds none yet, the tables are the domain's.
|
||||
COHORTES = TablasCohorte(
|
||||
CohorteArmado=CohorteArmado,
|
||||
CohorteMiembro=CohorteMiembro,
|
||||
CohorteExclusion=CohorteExclusion,
|
||||
CohorteVariable=CohorteVariable,
|
||||
EvaluacionRiesgoLote=EvaluacionRiesgoLote,
|
||||
EvaluacionRiesgo=EvaluacionRiesgo,
|
||||
)
|
||||
@@ -26,7 +26,7 @@ from typing import Any
|
||||
|
||||
from webapi.imports.audit import JsonlAuditSink, report_dir, sanitize_message
|
||||
|
||||
DOMAINS = ("cacu", "cama") # the domains whose measures the cycle computes
|
||||
DOMAINS = ("cacu", "cama", "tea") # the domains whose measures the cycle computes
|
||||
_SUMMARY_MAX = 400
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
Reference in New Issue
Block a user