Merge feature/tea-eeg-analysis into dev (TEA candidate composition)

This commit is contained in:
Angel Capetillo Zavala
2026-11-20 14:44:47 -06:00
26 changed files with 1486 additions and 312 deletions
+1
View File
@@ -70,6 +70,7 @@ Los errores de la solicitud se responden con `{"error": "..."}` y código 400
| `INDICADORES_DESDE`, `INDICADORES_HASTA` | hace 5 años, este año | Años que recalcula el servicio |
| `INDICADORES_INTERVALO_S` | `20` | Cada cuánto revisa la cola |
| `INDICADORES_AL_INICIAR` | `1` | Recalcular los tres dominios al arrancar |
| `EEG_ANALYSIS_CLUSTER` | `auto` | Where TEA's cycle analyses the stored EDFs before loading silver: `auto` (`DASK_SCHEDULER_ADDRESS` if set, otherwise a local Dask cluster), `local`, `remote`, `sync` (in the service's own process) or `off` (only `python -m models tea analyze` and `POST /governance/eeg/run` analyse) |
| `PORT`, `WEBAPI_WORKERS`, `WEBAPI_TIMEOUT` | `5000`, `2`, `600` | gunicorn en el contenedor |
| `NOTEBOOK_JOBS_DIR` | sin carpeta | Carpeta compartida con el servicio `notebooks`; con ella los notebooks corren aislados en ese contenedor |
| `NOTEBOOK_EXECUTOR` | `contenedor` con `NOTEBOOK_JOBS_DIR`, si no `local` | Dónde corren los notebooks; `local` es en el propio proceso, sin aislar (desarrollo) |
+2 -1
View File
@@ -21,6 +21,8 @@ dependencies = [
"sqlglot>=25.0",
"rapidfuzz>=3.9",
"watchdog>=6.0",
# Every FHIR answer is validated against R4B's models before it leaves (`webapi.fhir.common`).
"fhir-resources>=8.3",
]
[project.optional-dependencies]
@@ -44,7 +46,6 @@ packages = ["webapi"]
[dependency-groups]
dev = [
"fhir-resources>=8",
"pytest>=8.0.0",
"reportlab>=4.0",
]
+47 -26
View File
@@ -17,7 +17,8 @@ with the ADOS-2, neuropediatrics note, good-quality EEG). Ages are at the first
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.
Every EEG's verdict and quality checks are written as its analysis would: a good EEG has its study-wide checks
within their limits; a bad one has too few clean windows and a dead channel (T3).
Test support: writes in the session it's given, never in the domain's database.
"""
@@ -27,6 +28,7 @@ from datetime import date
from core.tea.models import (
Ados2,
Eeg,
EegCriterio,
EegMetrica,
EegMetricaElectrodo,
EvaluacionNeuropediatrica,
@@ -75,10 +77,22 @@ NOTAS = (
(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}
# The analysis's verdict, triage level, clean fraction, bad channels and line noise, and its checks:
# (code, electrode, value, text, unit, low, high, decisive, abnormal).
GOOD = {"valido": 1, "nivel": "completo", "limpia": 0.95, "malos": 0, "linea": 3.5, "criterios": (
("clean-windows", None, 95.0, None, "%", 60.0, None, 1, 0),
("usable-scalp", None, 19.0, None, "electrodes", 12.0, None, 1, 0),
("triage-level", None, None, "completo", None, None, None, 1, 0),
("line-noise", None, 3.5, None, "dB", None, 45.0, 0, 0),
)}
BAD = {"valido": 0, "nivel": "parcial", "limpia": 0.4, "malos": 1, "linea": 3.5, "criterios": (
("dead-channel", "T3", None, "dead channel", None, None, None, 0, 1),
("clean-windows", None, 40.0, None, "%", 60.0, None, 1, 1),
("usable-scalp", None, 18.0, None, "electrodes", 12.0, None, 1, 0),
("line-noise", None, 3.5, None, "dB", None, 45.0, 0, 0),
)}
# (eeg id, pac_id, date, laboratory id, criteria, with sleep)
# (eeg id, pac_id, date, laboratory id, analysis, 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),
@@ -87,30 +101,32 @@ EEGS = (
("eeg-6", 6, date(2025, 6, 1), "LAB-6", GOOD, 1),
)
# (metric id, eeg id, code, value): a null value can't be evaluated.
# (metric id, eeg id, code, value, deviation): a null value can't be evaluated. The deviation is the analysis's
# against the metric's age baseline: (z, -1/0/+1, p5, median, p95). Child 1's slow posterior rhythm is below p5.
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),
("met-1b-rp", "eeg-1b", "RITMO_POSTERIOR", 3.2, (-4.08, -1, 4.5, 5.75, 7.0)),
("met-1b-n2", "eeg-1b", "HUSOS_SUENO_N2", 4.0, (-0.5, 0, 2.5, 4.5, 6.5)),
("met-1b-pp", "eeg-1b", "PICOS_PAROXISTICOS", 0.4, (-0.4, 0, 0.0, 0.5, 1.0)),
("met-1a-rp", "eeg-1a", "RITMO_POSTERIOR", 2.0, (-6.0, -1, 4.5, 5.75, 7.0)),
("met-6-rp", "eeg-6", "RITMO_POSTERIOR", 6.5, (0.4, 0, 5.0, 6.25, 7.5)),
("met-6-n2", "eeg-6", "HUSOS_SUENO_N2", None, (None, None, None, None, None)),
("met-6-gr", "eeg-6", "GRADIENTE_ANTEROPOSTERIOR", 2.6, (0.27, 0, 1.75, 2.5, 3.25)),
)
# (electrode value id, metric id, electrode, z-score)
# (electrode value id, metric id, electrode, value, 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),
("mel-1", "met-1b-rp", "O1", 3.0, -2.8),
("mel-2", "met-1b-rp", "O2", 3.1, -2.4),
("mel-3", "met-1b-rp", "Pz", 3.6, -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)
# What the load gives (`test_orquestacion_plata`): a bad channel is a part of its EEG, as an electrode value is.
CANALES_MALOS = sum(1 for *_, analisis, _ in EEGS for c in analisis["criterios"] if c[1] is not None)
PROCEDIMIENTOS = len(ORDENES) + len(MCHATS) + len(ADOS2) + len(NOTAS) + len(EEGS) + len(ELECTRODOS) + CANALES_MALOS
def insertar(sesion: Session) -> None:
@@ -126,14 +142,19 @@ def insertar(sesion: Session) -> None:
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:
for i, p, f, lab, analisis, 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"],
eeg_con_sueno=sueno, eeg_canales=19, eeg_duracion_min=25.0, eeg_valido=analisis["valido"],
eeg_nivel=analisis["nivel"], eeg_fraccion_limpia=analisis["limpia"], eeg_canales_malos=analisis["malos"],
eeg_ruido_linea_db=analisis["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)
sesion.add_all(EegCriterio(cri_id=f"cri-{i}-{k}", cri_eeg_id=i, cri_codigo=c, cri_electrodo=e, cri_valor=v,
cri_valor_texto=t, cri_unidad=u, cri_bajo=lo, cri_alto=hi, cri_decisivo=d,
cri_anormal=a)
for k, (c, e, v, t, u, lo, hi, d, a) in enumerate(analisis["criterios"], 1))
sesion.add_all(EegMetrica(met_id=i, met_eeg_id=e, met_codigo=c, met_valor=v, met_z=z, met_fuera=fuera, met_p5=p5,
met_mediana=mediana, met_p95=p95)
for i, e, c, v, (z, fuera, p5, mediana, p95) in METRICAS)
sesion.add_all(EegMetricaElectrodo(mel_id=i, mel_met_id=m, mel_electrodo=e, mel_valor=v, mel_z=z)
for i, m, e, v, z in ELECTRODOS)
+118
View File
@@ -0,0 +1,118 @@
"""What this module covers: the cycle's `analyze_eeg` step (TEA's EEG analysis before the silver load) and how the
cycle gets its analysis (`webapi.orchestration.eeg`).
Fixtures: `tea_base`, a migrated TEA database (`base_de`) holding one patient (`pac_id` 1, born 2024-01-01) and one
EEG `e-1` with an EDF and no analysis; `fake_analysis`, an analysis that writes sleep and 21 channels on `e-1`, as
the real one would, and notes whether a silver load existed when it ran.
"""
from datetime import date
import pytest
from hamilton import driver
from sqlmodel import Session, select
from models.eeg_analysis import Summary
from webapi.orchestration import cycle, run, steps_of
from webapi.orchestration.context import Context
from webapi.orchestration.eeg import CLUSTER_ENV, live_eeg_analysis
def _rows(sesion):
from core.tea.models import Eeg, Pacientes
sesion.add(Pacientes(pac_id=1, pac_id_hospital="H-1", pac_fecha_nacimiento=date(2024, 1, 1)))
sesion.add(Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_id_registro_laboratorio="LAB-1", eeg_fecha_estudio=date(2025, 6, 1),
eeg_estudio=b"edf"))
@pytest.fixture
def tea_base(tmp_path):
"""Patient 1 and EEG `e-1` (an EDF, nothing analysed) in a migrated TEA database."""
from conftest import base_de
base = base_de("tea", tmp_path, datos=_rows)
yield base
base.motor.dispose()
@pytest.fixture
def fake_analysis(tea_base):
"""Writes `eeg_con_sueno` 1 and `eeg_canales` 21 on `e-1`; `calls` records the loads that existed at each call."""
from core.tea.indicadores.models import Carga
from core.tea.models import Eeg
calls = []
def analysis():
with Session(tea_base.motor) as sesion:
calls.append(len(sesion.exec(select(Carga)).all()))
eeg = sesion.get(Eeg, "e-1")
eeg.eeg_con_sueno, eeg.eeg_canales = 1, 21
sesion.add(eeg)
sesion.commit()
return Summary(pending=1, valid=1, not_valid=0, failed=0)
analysis.calls = calls
return analysis
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
def test_the_eeg_analysis_runs_before_the_silver_load(proyecto):
"""Pins down: `load` depends on `analyze_eeg`, which needs only the migrated schema.
Fails if `load` stops waiting for the analysis (the cycle would load an EEG's old analysis and pick the new one up
only on the next cycle), or the analysis starts waiting for steps it doesn't need.
"""
dr = driver.Builder().with_modules(cycle).with_config({"with_cohorts": proyecto == "cacu"}).build()
deps = {n.name: {d.name for d in n.dependencies} - {"ctx"} for n in dr.graph.get_nodes() if n.name != "ctx"}
assert "analyze_eeg" in deps["load"]
assert deps["analyze_eeg"] == {"migrate"}
order = steps_of(proyecto)
assert order.index("analyze_eeg") < order.index("load")
def test_without_an_analysis_the_step_does_nothing():
"""Pins down: a context without `eeg_analysis` (CaCu, CaMa, the tests' cycles) makes the step a no-op.
Fails if the step starts running an analysis nobody configured.
"""
pasos = run(Context("cacu", 2025, 2025), only=["analyze_eeg"])
assert [(p.name, p.summary) for p in pasos] == [("analyze_eeg", {})]
def test_what_the_analysis_writes_is_loaded_by_the_same_cycle(tea_base, fake_analysis):
"""Pins down: the cycle runs the analysis once, before any silver load, and `load` then carries what it wrote
into the EEG's silver observations.
Fails if the analysis runs after `load` or more than once, or its summary stops being the step's.
"""
from core.tea.indicadores.models import Observacion, Procedimiento
pasos = tea_base.run("analyze_eeg", "catalogs", "load", eeg_analysis=fake_analysis)
assert pasos["analyze_eeg"] == {"pending": 1, "valid": 1, "not_valid": 0, "failed": 0}
assert fake_analysis.calls == [0]
with Session(tea_base.motor) as sesion:
toma = sesion.exec(select(Procedimiento).where(Procedimiento.estudio_id == "eeg",
Procedimiento.clase == "toma")).one()
valores = {o.resultado_id: o.valor_numerico for o in sesion.exec(
select(Observacion).where(Observacion.procedimiento_id == toma.procedimiento_id))}
assert valores["eeg.canales"] == 21
def test_only_tea_has_an_analysis_and_it_can_be_turned_off(monkeypatch):
"""Pins down: TEA's cycle gets the analysis, with the cluster `EEG_ANALYSIS_CLUSTER` names; the other domains
get none, `off` leaves it out, and an unknown value is refused.
Fails if another domain starts analysing EEGs, `off` stops leaving the analysis out, or a mistyped cluster is
silently taken as the default.
"""
monkeypatch.delenv(CLUSTER_ENV, raising=False)
assert live_eeg_analysis("tea").keywords == {"cluster": "auto"}
assert live_eeg_analysis("cacu") is None
monkeypatch.setenv(CLUSTER_ENV, "sync")
assert live_eeg_analysis("tea").keywords == {"cluster": "sync"}
monkeypatch.setenv(CLUSTER_ENV, "off")
assert live_eeg_analysis("tea") is None
monkeypatch.setenv(CLUSTER_ENV, "everywhere")
with pytest.raises(ValueError, match=CLUSTER_ENV):
live_eeg_analysis("tea")
+100 -6
View File
@@ -9,6 +9,7 @@ Fixtures: `client`, a Flask app in DEV (`DEV_REVISION`, so the patient routes ex
shows the alterations (`TEA_ALTERACIONES_VALIDADAS`).
"""
import json
import os
import pytest
@@ -168,8 +169,9 @@ def test_the_follow_up_filters(client, query, 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,
ADOS-2 (the list shows its CSS and module), 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."""
observations, one per check of its analysis (clean windows, usable scalp, triage level, line noise) as the
analysis's own report writes them; no metric observation while the alterations are hidden. Fails if an included
resource drops out, a check stops reaching the report or changes shape, 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}
@@ -177,11 +179,49 @@ def test_includes_bring_the_patient_its_steps_and_its_study_eeg(client):
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)
assert all(len(r["result"]) == 4 for r in reports)
assert all(r["conclusionCode"][1]["coding"][0] == {"system": "urn:tea:validation", "code": "valid"} for r in reports)
quality = [r for r in included if r["resourceType"] == "Observation" and r["id"].startswith("calidad-")]
assert {r["code"]["coding"][0]["system"] for r in quality} == {"urn:tea:validation"}
clean = next(r for r in quality if r["code"]["coding"][0]["code"] == "clean-windows")
assert (clean["valueQuantity"]["value"], clean["referenceRange"][0]["low"]["value"]) == (95.0, 60.0)
assert clean["interpretation"][0]["coding"][0]["code"] == "N"
assert clean["component"] == [{"code": {"text": "decisive"}, "valueBoolean": True}]
triage = next(r for r in quality if r["code"]["coding"][0]["code"] == "triage-level")
assert triage["valueString"] == "completo"
ados2 = [r for r in included if r["resourceType"] == "Observation" and r["code"]["coding"][0]["code"] == "ados2"]
assert ados2 and all(any(c["code"]["coding"][0]["code"] == "ados2.css" for c in r["component"]) for r in ados2)
def test_a_bad_eeg_reports_its_failed_check_and_its_bad_channel(client):
"""Pins down, on a bad EEG's rows as dbt's views give them (too few clean windows, a dead channel at T3): the report
says MALO and the analysis's not-valid with the triage level; the clean windows are abnormal and decisive; the
dead channel is an abnormal observation with its electrode as a component; every resource conforms to FHIR.
Fails if a failed check or a bad channel stops reaching FHIR, or loses its electrode or decisive flag."""
from webapi.fhir import tea
eeg = {"procedimiento_id": 9, "fecha_eeg": "2025-04-02", "calidad": "MALO", "valido": 0, "nivel": "parcial",
"duracion_min": 25.0, "canales": 19}
checks = [
{"procedimiento_id": 9, "criterio": "clean_windows", "electrodo": None, "valor": 40.0, "valor_texto": None,
"bajo": 60.0, "alto": None, "anormal": 1, "decisivo": 1, "etiqueta": "Ventanas limpias", "unidad": "%"},
{"procedimiento_id": 9, "criterio": "dead_channel", "electrodo": "T3", "valor": None,
"valor_texto": "dead channel", "bajo": None, "alto": None, "anormal": 1, "decisivo": 0,
"etiqueta": "Canal muerto", "unidad": None},
]
resources = tea.eeg_resources(eeg, "P-X", [], [], False, checks)
report = next(r for r in resources if r["resourceType"] == "DiagnosticReport")
assert [c["coding"][0]["code"] for c in report["conclusionCode"]] == ["MALO", "not-valid"]
assert report["conclusion"].endswith("(nivel de triaje: parcial).")
clean, dead = (r for r in resources if r["resourceType"] == "Observation")
assert (clean["interpretation"][0]["coding"][0]["code"], clean["component"][-1]["valueBoolean"]) == ("A", True)
assert dead["id"] == "calidad-dead-channel-T3-9" and dead["valueString"] == "dead channel"
assert dead["component"] == [{"code": {"text": "electrode"}, "valueString": "T3"},
{"code": {"text": "decisive"}, "valueBoolean": False}]
for resource in resources:
get_fhir_model_class(resource["resourceType"]).model_validate(resource)
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."""
@@ -207,8 +247,9 @@ def test_the_eeg_summary_counts_valid_eegs_and_alterations_only_when_validated(c
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."""
the metrics against their age baseline (p5 as the low end of the reference, the median as a component) and each
electrode's z-score; and its episode, with the age group. Fails if the summary takes another EEG, shows the
alterations before validation, maps the electrodes' raw values or loses the age group."""
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"
@@ -225,8 +266,61 @@ def test_the_patient_summary_shows_the_first_ados2_and_the_study_eeg(client, mon
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
assert {c["code"]["coding"][0]["code"]: c["valueQuantity"]["value"] for c in rhythm["component"]} == {
"z": -4.08, "mediana": 5.75}
(episode,) = resources(shown, "EpisodeOfCare")
assert episode["extension"][0]["valueCoding"]["code"] == "16_23"
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"]
assert [(c["code"]["coding"][0]["code"], c["valueQuantity"]["value"]) for c in electrodes["component"]] == [
("O1", -2.8), ("O2", -2.4), ("Pz", -1.1)]
def test_a_metric_the_baseline_couldnt_score_keeps_its_value():
"""Pins down: a metric with a value but no z (no baseline in production, or an age it doesn't cover) keeps its
value and has no interpretation nor reference; one without a value is `not-performed`. Fails if an unscored metric
loses its value (the summary couldn't tell it from one never measured) or gets an interpretation it doesn't have."""
from webapi.fhir import tea
eeg = {"procedimiento_id": 9, "fecha_eeg": "2025-05-20"}
row = {"procedimiento_id": 9, "ref_min": None, "ref_mediana": None, "ref_max": None, "grupo_edad_eeg": "16_23",
"estado": "no_evaluable", "valor_z": None}
unscored, unmeasured = tea.metric_observations(eeg, [{**row, "metrica": "ritmo_posterior", "valor": 6.8},
{**row, "metrica": "husos_sueno_n3", "valor": None}],
[], "P-X", False)[::-1]
assert unscored["valueQuantity"]["value"] == 6.8
assert not {"interpretation", "referenceRange", "dataAbsentReason", "component"} & set(unscored)
assert unmeasured["dataAbsentReason"]["coding"][0]["code"] == "not-performed" and "valueQuantity" not in unmeasured
def test_the_quality_checks_are_a_code_system_of_the_analysis(client):
"""Pins down: `CodeSystem/tea-eeg-criterio` is the EEG analysis's code system (`urn:tea:validation`) with every
check code and the catalog's label, and each metric has a text for every state, normal included.
Fails if a check code the quality observations use has no concept, or a metric loses its normal effect.
"""
from core.tea.enums import CriterioEeg
checks = get(client, "/tea/fhir/CodeSystem/tea-eeg-criterio")
assert checks["url"] == "urn:tea:validation"
assert {c["code"] for c in checks["concept"]} == {c.value for c in CriterioEeg}
assert next(c for c in checks["concept"] if c["code"] == "clean-windows")["display"] == "Ventanas limpias"
metrics = get(client, "/tea/fhir/CodeSystem/tea-eeg-metrica")
assert all(any(p["code"] == "efecto-normal" for p in c["property"]) for c in metrics["concept"])
def test_an_answer_that_doesnt_conform_to_fhir_never_leaves(client):
"""Pins down: `fhir()` validates every answer against R4B; one that doesn't conform is a 500 `OperationOutcome`.
Fails if a malformed resource reaches a client, or the check stops running.
"""
from webapi import create_app
from webapi.fhir.common import fhir
with create_app().test_request_context():
bad = fhir({"resourceType": "Observation", "id": "x"}) # no status, no code
good = fhir({"resourceType": "Observation", "id": "x", "status": "final", "code": {"text": "t"}})
assert (bad.status_code, json.loads(bad.data)["resourceType"]) == (500, "OperationOutcome")
assert (good.status_code, json.loads(good.data)["status"]) == (200, "final")
def test_an_unknown_patient_or_parameter_is_an_operation_outcome(client):
+29
View File
@@ -261,6 +261,35 @@ def test_ocr_run_extracts_results_and_flags_unreadable_reports(client):
assert again["skipped_already_done"] >= 1
def test_eeg_run_analyses_at_most_the_limit_with_the_configured_cluster(client, monkeypatch):
"""Pins down: `POST /governance/eeg/run` runs the EEG analysis in the request with the body's `limit` (5 by
default), `all` and the cluster `EEG_ANALYSIS_CLUSTER` names, and answers its summary.
Fails if the route stops bounding the batch (a request could then run for hours) or ignores the body.
"""
import models.eeg_analysis
from models.eeg_analysis import Summary
calls = []
monkeypatch.setattr(models.eeg_analysis, "analyze_pending",
lambda **kwargs: calls.append(kwargs) or Summary(pending=2, valid=1, not_valid=1, failed=0))
monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", "sync")
body = client.post("/governance/eeg/run", json={}).get_json()
assert body == {"pending": 2, "valid": 1, "not_valid": 1, "failed": 0}
client.post("/governance/eeg/run", json={"limit": 1, "all": True, "cluster": "local"})
assert calls == [{"everything": False, "limit": 5, "cluster": "sync"},
{"everything": True, "limit": 1, "cluster": "local"}]
@pytest.mark.parametrize("body", [{"limit": 0}, {"limit": "many"}, {"cluster": "everywhere"}])
def test_eeg_run_refuses_a_bad_limit_or_cluster(client, body):
"""Pins down: a limit that isn't a positive whole number, or an unknown cluster, is a 400 before anything runs.
Fails if the route starts an analysis on a body it can't honour.
"""
assert client.post("/governance/eeg/run", json=body).status_code == 400
def test_list_ocr_jobs(client):
body = client.get("/governance/ocr/jobs").get_json()
keys = {(j["domain"], j["entity"]) for j in body["jobs"]}
+5 -10
View File
@@ -78,22 +78,17 @@ def test_tea_children_keep_pointing_at_their_parents_source_ids(tea_client):
_json([{"ord_id": "ord-1", "ord_pac_id": 1, "ord_id_hospital": "O-1"}], "tea.OrdenesEstudio"),
_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"),
_json([{"neu_id": "neu-1", "neu_ord_id": "ord-1", "neu_pac_id": 1}], "tea.EvaluacionNeuropediatrica"),
]
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 (
ados2_repository,
eeg_metrica_electrodo_repository,
eeg_metrica_repository,
eeg_repository,
)
from persistance.tea import ados2_repository, eeg_repository, evaluacion_neuropediatrica_repository
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 eeg_repository.get("eeg-1").eeg_ord_id == "ord-1"
assert eeg_repository.get("eeg-1").eeg_id_registro_laboratorio == "L-1"
assert ados2_repository.get("ado-1").ado_ord_id == "ord-1"
assert evaluacion_neuropediatrica_repository.get("neu-1").neu_ord_id == "ord-1"
def test_tea_rows_without_a_source_id_get_one(tea_client):
+143
View File
@@ -0,0 +1,143 @@
"""What this module covers: what the EEG analysis writes to TEA's bronze, carried into silver
(`webapi.orchestration.silver.tea`) and into dbt's views of the EEG's quality checks, metrics and electrodes
(`tea_paciente_eeg_criterios`, `tea_paciente_eeg_metricas`, `tea_paciente_eeg_electrodos`).
Fixtures: `loaded`, a TEA database (`base_de`) loaded up to the event models, with one patient and one analysed EEG
`e-1`: valid, triage `completo`; three checks (95 % clean windows against a low limit of 60, the triage level as text,
and a dead channel at T3); its posterior rhythm 6.8 Hz with z 1.2, -1/0/+1 0 and p5/median/p95 5/6/7, and its N2
spindles' value 2.5 with z -0.4 at Fz.
"""
import os
from datetime import date
import pytest
from sqlalchemy import text
from sqlmodel import Session, select
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
def _rows(sesion):
from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, Mchat, Pacientes
sesion.add(Pacientes(pac_id=1, pac_id_hospital="H-1", pac_fecha_nacimiento=date(2023, 6, 1)))
sesion.add(Mchat(mch_id="m-1", mch_pac_id=1, mch_fecha=date(2025, 1, 10), mch_puntaje=12))
sesion.add(Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 5, 20), eeg_valido=1, eeg_nivel="completo",
eeg_fraccion_limpia=0.95, eeg_canales_malos=1, eeg_edad_meses=23.6, eeg_con_sueno=1))
sesion.add_all([
EegCriterio(cri_id="c-1", cri_eeg_id="e-1", cri_codigo="clean-windows", cri_valor=95.0, cri_unidad="%",
cri_bajo=60.0, cri_decisivo=1, cri_anormal=0),
EegCriterio(cri_id="c-2", cri_eeg_id="e-1", cri_codigo="triage-level", cri_valor_texto="completo",
cri_decisivo=1, cri_anormal=0),
EegCriterio(cri_id="c-3", cri_eeg_id="e-1", cri_codigo="dead-channel", cri_electrodo="T3",
cri_valor_texto="dead channel", cri_decisivo=0, cri_anormal=1),
])
sesion.add_all([
EegMetrica(met_id="r", met_eeg_id="e-1", met_codigo="RITMO_POSTERIOR", met_valor=6.8, met_z=1.2, met_fuera=0,
met_p5=5.0, met_mediana=6.0, met_p95=7.0),
EegMetrica(met_id="n2", met_eeg_id="e-1", met_codigo="HUSOS_SUENO_N2", met_valor=2.5),
EegMetricaElectrodo(mel_id="n2-fz", mel_met_id="n2", mel_electrodo="Fz", mel_valor=1.4, mel_z=-0.4),
])
@pytest.fixture(scope="module")
def loaded(tmp_path_factory):
"""The database after the cycle's load and event models, with dbt's views created."""
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("needs dbt's compiled manifest (DBT_MANIFEST)")
from conftest import base_de
base = base_de("tea", tmp_path_factory.mktemp("tea_eeg"), datos=_rows)
base.run(*UNTIL_MODELS, allow_undecided=True)
yield base
base.motor.dispose()
def _observations(base, clase: str) -> dict:
from core.tea.indicadores.models import Observacion, Procedimiento
with Session(base.motor) as sesion:
rows = sesion.exec(select(Procedimiento.codigo_fuente, Observacion).join(
Observacion, Observacion.procedimiento_id == Procedimiento.procedimiento_id).where(
Procedimiento.estudio_id == "eeg", Procedimiento.clase == clase)).all()
return {(fuente, o.resultado_id): o.valor_numerico if o.valor_texto is None else o.valor_texto
for fuente, o in rows}
def test_the_verdict_and_study_checks_are_results_of_the_recording(loaded):
"""Pins down: the EEG's verdict, triage level and each study-wide check (value, limit, out of range or not) are
observations of its recording, under `eeg.calidad_<check>` in snake case; a check without a limit of that side
gives none.
Fails if the silver mapping drops the verdict, stops turning check codes into catalog results, or the catalog
loses one of them (the load skips a result the catalog doesn't have).
"""
toma = _observations(loaded, "toma")
assert toma[None, "eeg.valido"] == 1 and toma[None, "eeg.nivel"] == "completo"
assert (toma[None, "eeg.calidad_clean_windows"], toma[None, "eeg.calidad_clean_windows_bajo"],
toma[None, "eeg.calidad_clean_windows_anormal"]) == (95.0, 60.0, 0)
assert toma[None, "eeg.calidad_triage_level"] == "completo"
assert (None, "eeg.calidad_clean_windows_alto") not in toma
def test_a_bad_channel_and_an_electrode_value_are_parts_of_the_eeg(loaded):
"""Pins down: a bad channel is a part of its EEG at its electrode with the analysis's reason; a metric's value at
an electrode is a part with the value and its z.
Fails if the channel checks stop being parts, or the electrode z stops reaching silver.
"""
partes = _observations(loaded, "parte")
assert partes["T3", "eeg.calidad_dead_channel"] == "dead channel"
assert (partes["Fz", "eeg.husos_sueno_n2"], partes["Fz", "eeg.husos_sueno_n2_z"]) == (1.4, -0.4)
def test_a_metric_carries_its_deviation_from_the_baseline(loaded):
"""Pins down: a metric's z, -1/0/+1 and the baseline's p5/median/p95 at the age are results of the recording.
Fails if the silver mapping or the catalog drops one of the deviation's results.
"""
toma = _observations(loaded, "toma")
assert [toma[None, f"eeg.ritmo_posterior{s}"] for s in ("", "_z", "_fuera", "_p5", "_mediana", "_p95")] == \
[6.8, 1.2, 0, 5.0, 6.0, 7.0]
def test_the_quality_view_lists_each_check_with_its_label(loaded):
"""Pins down: `tea_paciente_eeg_criterios` has one row per check of the EEG, study-wide ones without an electrode
and with their limit and decisive flag, the bad channel at its electrode as out of range and not decisive, each with the catalog's label; and the
electrodes view keeps only metric values, not channel checks.
Fails if the view stops pivoting a check's observations, misses the channel parts, or the electrodes view starts
reading the checks' parts as metrics.
"""
with loaded.motor.connect() as connection:
rows = connection.execute(text(
"select criterio, electrodo, valor, valor_texto, bajo, anormal, decisivo, etiqueta "
"from tea_paciente_eeg_criterios "
"order by criterio")).all()
electrodes = connection.execute(text("select metrica, electrodo from tea_paciente_eeg_electrodos")).all()
by_check = {r.criterio: r for r in rows}
assert set(by_check) == {"clean_windows", "triage_level", "dead_channel"}
assert (by_check["clean_windows"].valor, by_check["clean_windows"].bajo, by_check["clean_windows"].anormal,
by_check["clean_windows"].decisivo) == (95.0, 60.0, 0, 1)
assert (by_check["dead_channel"].electrodo, by_check["dead_channel"].anormal, by_check["dead_channel"].decisivo) == \
("T3", 1, 0)
assert by_check["clean_windows"].etiqueta == "Ventanas limpias"
assert [tuple(e) for e in electrodes] == [("husos_sueno_n2", "Fz")]
def test_a_metric_is_scored_by_the_analysis_s_deviation(loaded):
"""Pins down: `tea_paciente_eeg_metricas` takes the analysis's z, its -1/0/+1 as the state and the baseline's
p5/median/p95 as the reference; a metric without a z (no baseline in production) can't be evaluated. And the
electrodes view carries each electrode's z next to its value.
Fails if dbt goes back to scoring metrics against fixed ranges of its own, or drops the electrode z.
"""
with loaded.motor.connect() as connection:
metrics = {r.metrica: r for r in connection.execute(text(
"select metrica, valor, ref_min, ref_mediana, ref_max, valor_z, estado from tea_paciente_eeg_metricas"))}
(electrode,) = connection.execute(text("select valor, valor_z from tea_paciente_eeg_electrodos")).all()
rhythm = metrics["ritmo_posterior"]
assert (rhythm.valor, rhythm.ref_min, rhythm.ref_mediana, rhythm.ref_max, rhythm.valor_z, rhythm.estado) == \
(6.8, 5.0, 6.0, 7.0, 1.2, "normal")
assert (metrics["husos_sueno_n2"].valor_z, metrics["husos_sueno_n2"].estado) == (None, "no_evaluable")
assert tuple(electrode) == (1.4, -0.4)
+3 -4
View File
@@ -19,7 +19,7 @@ from sqlmodel import select
import staging.tea as fixture
from conftest import base_de
from core.tea.models import Ados2, Eeg, EegMetrica, Mchat
from core.tea.models import Ados2, Eeg, EegCriterio, 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
@@ -219,7 +219,7 @@ def test_a_knowledge_cut_off_leaves_out_a_step_loaded_later(tmp_path, manifest):
def without_the_good_eeg(session):
fixture.insertar(session)
session.flush()
for model, key in ((EegMetrica, "met_eeg_id"), (Eeg, "eeg_id")):
for model, key in ((EegMetrica, "met_eeg_id"), (EegCriterio, "cri_eeg_id"), (Eeg, "eeg_id")):
for row in session.exec(select(model).where(getattr(model, key) == "eeg-1b")):
session.delete(row)
@@ -231,8 +231,7 @@ def test_a_knowledge_cut_off_leaves_out_a_step_loaded_later(tmp_path, manifest):
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_canales=19, eeg_duracion_min=25.0, eeg_valido=1, eeg_nivel="completo",
eeg_ruido_linea_db=3.5))
session.commit()
base.run("load", allow_undecided=True)
Generated
+785 -145
View File
File diff suppressed because it is too large Load Diff
+23
View File
@@ -375,6 +375,29 @@ def correct_ocr_row(domain: str, entity: str, pk: int):
return jsonify(updated)
@governance_bp.post("/eeg/run")
def run_eeg_analysis():
"""Runs TEA's EEG analysis on the stored EDFs that need it (`models.eeg_analysis`), in this request: at most
`limit` EEGs (5 by default), or every EEG with an EDF again with `all`. Larger batches are the indicator cycle's
or `python -m models tea analyze`'s. Rows already analysed with the current plan, modules and baselines are
skipped, so repeated calls are safe (VAR-09)."""
from models.eeg_analysis import analyze_pending
from webapi.orchestration.eeg import CLUSTERS, cluster as configured_cluster
body = request.get_json(silent=True) or {}
try:
limit = int(body.get("limit", 5))
except (TypeError, ValueError):
return jsonify({"error": "limit must be a whole number"}), 400
if limit < 1:
return jsonify({"error": "limit must be at least 1"}), 400
cluster = body.get("cluster") or configured_cluster()
if cluster not in CLUSTERS:
return jsonify({"error": f"cluster must be one of {', '.join(CLUSTERS)}"}), 400
summary = analyze_pending(everything=bool(body.get("all")), limit=limit, cluster=cluster)
return jsonify(asdict(summary))
@governance_bp.post("/ocr/run")
def run_ocr():
"""Runs an OCR job over pending rows. Rows already `REALIZADO` are
+1 -1
View File
@@ -354,5 +354,5 @@ def _included(tea, queries, e, simulated: bool) -> list[dict]:
tea.care_plan(e, simulated)]
resources += [r for r in (tea.mchat_observation(e, simulated), ados2, tea.condition(e, simulated)) if r]
if (eeg := e.study_eeg()) is not None:
resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated)
resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated, e.checks)
return resources
+27 -3
View File
@@ -1,7 +1,9 @@
"""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."""
their paging links, the simulated-data tag and the project's canonical URLs. Every answer is validated against FHIR's
R4B models (`fhir.resources`, the models the EEG analysis validates its own report with) before it leaves."""
import json
import logging
import os
from urllib.parse import urlencode
@@ -17,10 +19,32 @@ SIMULATED = {"system": f"{CODE_SYSTEM}/etiqueta", "code": "simulado", "display":
MAX_COUNT = 200
DEFAULT_COUNT = 50
log = logging.getLogger(__name__)
def validated(resource: dict) -> dict:
"""The resource as FHIR's R4B models read it and write it back (R4B keeps R4's shape for these resources).
`ValueError` if it doesn't conform."""
from fhir.resources.R4B import get_fhir_model_class
try:
model = get_fhir_model_class(resource["resourceType"])
except KeyError as exc:
raise ValueError(f"no FHIR resource type {resource.get('resourceType')!r}") from exc
return model.model_validate(resource).model_dump(mode="json", exclude_none=True)
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)
"""A resource as the answer, in FHIR's JSON media type. One that doesn't conform to FHIR never leaves: the answer
is then a 500 `OperationOutcome`, and the reason goes to the log."""
try:
body = validated(resource)
except ValueError:
if resource.get("resourceType") == "OperationOutcome":
raise
log.exception("a %s answer doesn't conform to FHIR R4B", resource.get("resourceType"))
return outcome(500, "exception", "la respuesta no es un recurso FHIR válido")
return Response(json.dumps(body, ensure_ascii=False), status=status, mimetype=MEDIA_TYPE)
def outcome(status: int, code: str, diagnostics: str, severity: str = "error") -> Response:
+81 -44
View File
@@ -6,27 +6,22 @@ stage the furthest step reached by the cut-off (`type`, with its date as an exte
`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`):
Until the domain expert validates the age baselines, every alteration stays hidden (`alterations_validated`):
the alteration filter, the abnormal/normal split, and the metric and electrode observations.
"""
import hashlib
import os
from dataclasses import dataclass
from dataclasses import dataclass, field
from datetime import date
from sqlalchemy import column, select, table
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, concept, tagged
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, coding, concept, tagged
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"
@@ -40,12 +35,16 @@ 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")))))
"procedimiento_id", "pac_id", "fecha_eeg", "con_sueno", "canales", "duracion_min", "nivel", "fraccion_limpia",
"canales_malos", "ruido_linea_db", "calidad", "valido")))
CHECKS = table("tea_paciente_eeg_criterios", *map(column, (
"procedimiento_id", "pac_id", "criterio", "electrodo", "valor", "valor_texto", "bajo", "alto", "anormal",
"decisivo", "etiqueta", "unidad")))
METRICS = table("tea_paciente_eeg_metricas", *map(column, (
"procedimiento_id", "pac_id", "metrica", "valor", "grupo_edad_eeg", "ref_min", "ref_max", "valor_z", "estado")))
"procedimiento_id", "pac_id", "metrica", "valor", "grupo_edad_eeg", "ref_min", "ref_mediana", "ref_max", "valor_z",
"estado")))
ELECTRODES = table("tea_paciente_eeg_electrodos", *map(column, ("procedimiento_id", "pac_id", "metrica", "electrodo",
"valor")))
"valor", "valor_z")))
ADOS2 = table("tea_paciente_ados2", *map(column, (
"procedimiento_id", "pac_id", "fecha_ados2", "modulo", "algoritmo", "css", "clasificacion", "dominio", "reactivo",
"etiqueta", "puntaje", "puntaje_algoritmo")))
@@ -53,7 +52,7 @@ 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
"""Whether the domain expert validated the EEG analysis's age baselines and the effect texts
(`TEA_ALTERACIONES_VALIDADAS=1`): until then no alteration is shown."""
return os.environ.get("TEA_ALTERACIONES_VALIDADAS", "") in ("1", "true", "si")
@@ -87,6 +86,7 @@ class Episode:
cutoff: date
eegs: list[dict]
metrics: list[dict]
checks: list[dict] = field(default_factory=list)
@property
def pseudonym(self) -> str:
@@ -148,17 +148,16 @@ class Episode:
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))
eegs, metrics, checks = (_rows(queries, select(EEGS)), _rows(queries, select(METRICS)),
_rows(queries, select(CHECKS)))
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)
for rows, kind in ((eegs, "eegs"), (metrics, "metrics"), (checks, "checks")):
for row in rows:
if row["pac_id"] in by_child:
getattr(by_child[row["pac_id"]], kind).append(row)
return list(by_child.values())
@@ -229,26 +228,47 @@ def condition(e: Episode, simulated: bool) -> dict | None:
"recordedDate": _date(e.child["fecha_tea"]).isoformat()}, simulated)
def quality_observations(eeg: dict, pseudonym: str, simulated: bool) -> list[dict]:
def quality_observations(eeg: dict, checks: list[dict], pseudonym: str, simulated: bool) -> list[dict]:
"""One `Observation` per quality check the EEG analysis evaluated, as the analysis's own validation report writes
it (`tea.validation.fhir`): its code in the analysis's code system, its value (a quantity or a text), whether it
was abnormal (A/N), its limit as the reference range, and as components the bad channel's electrode and whether
the check alone can make the EEG not valid. Study-wide checks first, then the bad channels by electrode."""
from tea.validation.fhir import INTERP, SYSTEM
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),
mine = [c for c in checks if c["procedimiento_id"] == eeg["procedimiento_id"]]
for c in sorted(mine, key=lambda c: (c["electrodo"] is not None, c["electrodo"] or "", c["criterio"])):
code, unit = c["criterio"].replace("_", "-"), c["unidad"]
quantity = (lambda v: {"value": float(v), **({"unit": unit} if unit else {})})
resource = {
"resourceType": "Observation",
"id": "-".join(p for p in ("calidad", code, c["electrodo"], str(eeg["procedimiento_id"])) if p),
"status": "final", "code": {"coding": [coding(SYSTEM, code, c["etiqueta"] or code)],
"text": c["etiqueta"] or code},
"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))
"interpretation": [concept(INTERP, "A" if c["anormal"] else "N")],
}
if c["valor"] is not None:
resource["valueQuantity"] = quantity(c["valor"])
elif c["valor_texto"] is not None:
resource["valueString"] = c["valor_texto"]
limits = {k: quantity(c[v]) for k, v in (("low", "bajo"), ("high", "alto")) if c[v] is not None}
if limits:
resource["referenceRange"] = [limits]
resource["component"] = [
*([{"code": {"text": "electrode"}, "valueString": c["electrodo"]}] if c["electrodo"] else []),
{"code": {"text": "decisive"}, "valueBoolean": bool(c["decisivo"])},
]
observations.append(tagged(resource, 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."""
"""One `Observation` per metric and one per metric with each electrode's z-score as a component. A metric's
observation has its value, or `not-performed` without one; with a z, also its age baseline's p5-p95 at the EEG
as the reference, H/L/N, and the z and the baseline's median as components. A value without a z is a metric the
baseline couldn't score (none in production, or an age it doesn't cover): no interpretation."""
from webapi.fhir.terminology import TEA_EEG
observations = []
@@ -258,35 +278,42 @@ def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict],
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")
if m["valor"] is None:
resource["dataAbsentReason"] = concept(ABSENT, "not-performed")
else:
resource["valueQuantity"] = {"value": float(m["valor"]), "unit": spec["unidad"]}
if m["valor"] is not None and m["valor_z"] is not None:
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_mediana"] is not None:
resource["component"].append({
"code": concept(f"{CODE_SYSTEM}/puntaje", "mediana", "Mediana de la referencia a la edad"),
"valueQuantity": {"value": float(m["ref_mediana"]), "unit": spec["unidad"]}})
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"]]
at = [x for x in electrodes if x["procedimiento_id"] == eeg["procedimiento_id"] and x["metrica"] == m["metrica"]
and x["valor_z"] is not None]
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"])}}
"valueQuantity": {"value": round(float(x["valor_z"]), 2)}}
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]:
def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: list[dict], simulated: bool,
checks: list[dict] = ()) -> 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)
quality = quality_observations(eeg, list(checks), 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",
@@ -298,14 +325,21 @@ def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: li
"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["calidad"] != "SIN_ANALIZAR":
from tea.validation.fhir import SYSTEM
report["conclusionCode"].append(concept(SYSTEM, "valid" if eeg["valido"] == 1 else "not-valid"))
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."
if eeg["calidad"] == "SIN_ANALIZAR":
report["conclusion"] = "EEG sin analizar todavía: no es válido para el estudio."
elif eeg["valido"] != 1:
report["conclusion"] = "EEG de mala calidad: no es válido para el estudio" + (
f" (nivel de triaje: {eeg['nivel']})." if eeg["nivel"] else ".")
return [procedure, tagged(report, simulated), *quality, *altered]
@@ -341,7 +375,8 @@ def ados2_observation(rows: list[dict], pseudonym: str, simulated: bool) -> dict
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."""
"""The `$resumen-tea` collection: the patient, its screening episode (with its age group), 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)]
@@ -350,9 +385,11 @@ def patient_summary(queries, pac_id: int, today: date, simulated: bool) -> dict:
(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)))
_rows(queries, select(METRICS).where(METRICS.c.pac_id == pac_id)),
_rows(queries, select(CHECKS).where(CHECKS.c.pac_id == pac_id)))
resources.append(episode_of_care(e, simulated))
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)
resources += eeg_resources(eeg, pseudonym, e.metrics, electrodes, simulated, e.checks)
return {"resourceType": "Bundle", "type": "collection", "entry": [{"resource": r} for r in resources]}
+9 -4
View File
@@ -1,33 +1,38 @@
# 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`.
# TEA's EEG vocabulary for the FHIR answers: what each metric's state 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 age baselines they go with.
[metricas.ritmo_posterior]
etiqueta = "Ritmo posterior"
unidad = "Hz"
efectos.normal = ["Dentro de lo esperado para la edad."]
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.normal = ["Dentro de lo esperado para la edad."]
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.normal = ["Dentro de lo esperado para la edad."]
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.normal = ["Dentro de lo esperado para la edad."]
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"
unidad = "pendiente"
efectos.normal = ["Dentro de lo esperado para la edad."]
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."]
+17 -3
View File
@@ -1,6 +1,7 @@
"""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`)."""
results, TEA's EEG metrics with their effect texts (`tea_eeg.toml`), and the EEG analysis's quality checks, under
the analysis's own code system with the catalog's labels."""
import tomllib
from pathlib import Path
@@ -38,6 +39,18 @@ def catalog(domain: str) -> dict:
return _code_system(f"{domain}-catalogo", f"Catálogo de {domain.upper()}", concepts, hierarchy=True)
def eeg_checks() -> dict:
"""The EEG analysis's quality checks (`CriterioEeg`), under the code system its validation report uses, each with
the catalog's label of its `eeg.calidad_<check>` result."""
from core.tea.enums import CriterioEeg
from tea.validation.fhir import SYSTEM
results = tomllib.loads(ruta_de_catalogo("tea").read_text(encoding="utf-8"))["eeg"]["resultados"]
concepts = [{"code": c.value, "display": results[f"calidad_{c.value.replace('-', '_')}"]["etiqueta"]}
for c in CriterioEeg]
return {**_code_system("tea-eeg-criterio", "Reglas de calidad del EEG", concepts), "url": SYSTEM}
def tea_code_systems() -> dict[str, dict]:
metrics = [{"code": code, "display": spec["etiqueta"], "property": [
{"code": "unidad", "valueString": spec["unidad"]},
@@ -48,8 +61,9 @@ def tea_code_systems() -> dict[str, dict]:
_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"}]},
"property": [{"code": "unidad", "type": "string"}, {"code": "efecto-normal", "type": "string"},
{"code": "efecto-aumentado", "type": "string"}, {"code": "efecto-disminuido", "type": "string"}]},
eeg_checks(),
_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", [
-14
View File
@@ -25,8 +25,6 @@ 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 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
@@ -60,8 +58,6 @@ from webapi.imports.schemas.cama.ordenes_estudio import (
from webapi.imports.schemas.cama.paciente import PacienteImportSchema as CamaPacienteImportSchema
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 (
@@ -187,14 +183,4 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
# one row.
conflict_fields=("eeg_id_registro_laboratorio",),
),
"tea.EegMetrica": EntitySpec(
schema=EegMetricaImportSchema,
repository=tea_eeg_metrica_repository,
conflict_fields=("met_id",),
),
"tea.EegMetricaElectrodo": EntitySpec(
schema=EegMetricaElectrodoImportSchema,
repository=tea_eeg_metrica_electrodo_repository,
conflict_fields=("mel_id",),
),
}
+4 -9
View File
@@ -1,15 +1,14 @@
"""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)."""
"""Import schema for `core.tea.models.Eeg`: the study and its EDF, and the sleep, channels, duration and line noise
a report may state. The verdict, quality checks and metrics are the EEG analysis's, written from the EDF, never
imported."""
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.
# The source's own id, kept so the analysis rows that reference it still point at this record.
eeg_id: SourceId = None
eeg_pac_id: Optional[int] = None
eeg_ord_id: OptionalStr = None
@@ -18,9 +17,5 @@ class EegImportSchema(ImportSchema):
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
-16
View File
@@ -1,16 +0,0 @@
"""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
@@ -1,12 +0,0 @@
"""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
+2 -1
View File
@@ -13,6 +13,7 @@ from datetime import date
from pathlib import Path
from webapi.orchestration.context import Context
from webapi.orchestration.eeg import live_eeg_analysis
from webapi.orchestration.estimators import live_estimators
from webapi.orchestration.runner import run
@@ -44,7 +45,7 @@ def main(argv: list[str] | None = None) -> None:
return
logging.basicConfig(level=logging.INFO, format="%(message)s")
ctx = Context(args.project, args.year_from, args.year_to, args.cutoff, args.allow_undecided, args.parameters,
estimators=live_estimators(args.project))
estimators=live_estimators(args.project), eeg_analysis=live_eeg_analysis(args.project))
for paso in run(ctx, only=args.only):
print(f"{paso.name:20} {paso.seconds:6.1f} s")
+4 -1
View File
@@ -1,7 +1,7 @@
"""Lo que recibe cada paso del ciclo."""
import os
from collections.abc import Mapping
from collections.abc import Callable, Mapping
from dataclasses import dataclass, field
from datetime import date
from pathlib import Path
@@ -39,5 +39,8 @@ class Context:
# Los estimadores de riesgo por cohorte (`cohorte_url` -> objeto con `estimate(columnas, filas)`, `procedencia()`
# y `desenlace`; ADR-MD-008). Sin ellos, el paso `estimate` no hace nada.
estimators: Mapping[str, Any] = field(default_factory=dict, compare=False, repr=False)
# The domain's EEG analysis (`webapi.orchestration.eeg.live_eeg_analysis`): run by the `analyze_eeg` step before
# the silver load, it writes the analysis of each stored EDF to bronze. Without it, that step does nothing.
eeg_analysis: Callable[[], Any] | None = field(default=None, compare=False, repr=False)
# Los repositorios del proyecto (`repositorios.Repositorios`); el ejecutor los pone si faltan.
repos: Any = field(default=None, compare=False, repr=False)
+12 -2
View File
@@ -11,6 +11,7 @@ Bronce lo escribe la ingesta, fuera del ciclo.
"""
import logging
from dataclasses import asdict
from datetime import date, datetime
from functools import partial
from importlib import import_module
@@ -81,8 +82,17 @@ def catalogs(migrate: str, ctx: Context) -> dict[str, int]:
return counts
def load(catalogs: dict[str, int], ctx: Context) -> SQLModel:
"""`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c).
def analyze_eeg(migrate: str, ctx: Context) -> dict[str, int]:
"""The EEG analysis of each stored EDF that needs one (`ctx.eeg_analysis`), written to bronze before `load` reads
it: the verdict, quality checks and metrics in `eeg`, `eeg_criterio`, `eeg_metrica` and `eeg_metrica_electrodo`.
Returns how many EEGs were pending and how each ended; nothing without an analysis (every domain but TEA)."""
if ctx.eeg_analysis is None:
return {}
return asdict(ctx.eeg_analysis())
def load(catalogs: dict[str, int], analyze_eeg: dict[str, int], ctx: Context) -> SQLModel:
"""`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c), after the EEG analysis.
Incremental por la llave lógica de cada procedimiento (`save_load_in`): repetir no cambia nada.
"""
+29
View File
@@ -0,0 +1,29 @@
"""TEA's EEG analysis as the cycle runs it: the `tea` library over each stored EDF, before the silver load.
`EEG_ANALYSIS_CLUSTER` says where the batch runs: `auto` (the default: the scheduler in `DASK_SCHEDULER_ADDRESS` if
set, otherwise a local cluster), `local`, `remote`, `sync` (in the cycle's own process), or `off`, which leaves the
analysis out of the cycle (`python -m models tea analyze` and `POST /governance/eeg/run` still run it).
"""
import os
from collections.abc import Callable
from functools import partial
from typing import Any
CLUSTER_ENV = "EEG_ANALYSIS_CLUSTER"
CLUSTERS = ("auto", "local", "remote", "sync")
def cluster() -> str:
value = os.environ.get(CLUSTER_ENV, "auto")
if value not in (*CLUSTERS, "off"):
raise ValueError(f"{CLUSTER_ENV} must be one of {', '.join((*CLUSTERS, 'off'))}, not {value!r}")
return value
def live_eeg_analysis(domain: str) -> Callable[[], Any] | None:
"""The domain's EEG analysis for the cycle, or none: only TEA has one, and `off` leaves it out."""
if domain != "tea" or cluster() == "off":
return None
from models.eeg_analysis import analyze_pending
return partial(analyze_pending, cluster=cluster())
+41 -9
View File
@@ -3,8 +3,10 @@
- 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.
- what the EEG analysis writes: the EEG's verdict and study-wide quality checks (`eeg_criterio` without an
electrode) and each metric with its deviation from the age baseline are results of the EEG's recording, not
procedures; a bad channel (`eeg_criterio` with an electrode) and a metric's value at an electrode are `parte`s of
the EEG, `codigo_fuente` the electrode. The metric rows find their EEG through the metric.
"""
from core.tea.enums import (
@@ -18,6 +20,7 @@ from core.tea.models import (
ADOS2_ITEMS,
Ados2,
Eeg,
EegCriterio,
EegMetrica,
EegMetricaElectrodo,
EvaluacionNeuropediatrica,
@@ -50,7 +53,20 @@ def _metrica(f) -> str | None:
return None if codigo is None else codigo.lower()
def _criterio(f) -> str | None:
"""A quality check's results in the catalog: `calidad_` and its code in snake case (`clean-windows` ->
`calidad_clean_windows`)."""
codigo = texto_limpio(f.cri_codigo)
return None if codigo is None else "calidad_" + codigo.lower().replace("-", "_")
def _valor_de_criterio(f):
return f.cri_valor if f.cri_valor is not None else texto_limpio(f.cri_valor_texto)
SU_EEG = Padre(estudio_id="eeg", clase="toma", fuente_id="met_eeg_id", tabla=EEG)
EEG_DEL_CRITERIO = Padre(estudio_id="eeg", clase="toma", fuente_id="cri_eeg_id", tabla=EEG)
DEVIATION = ("z", "fuera", "p5", "mediana", "p95")
DESDE_STAGING = (
@@ -95,26 +111,42 @@ DESDE_STAGING = (
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_valido": "eeg.valido",
"eeg_nivel": "eeg.nivel",
"eeg_fraccion_limpia": "eeg.fraccion_limpia",
"eeg_canales_malos": "eeg.canales_malos",
"eeg_edad_meses": "eeg.edad_meses",
"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",
"eeg_ruido_linea_db": "eeg.ruido_linea",
},
),
DeStaging(
EegCriterio, "cri_id", "toma", estudio_id="eeg", paciente=None, observa_en=EEG_DEL_CRITERIO,
solo_si=lambda f: f.cri_electrodo is None,
derivadas={"criterio": _criterio, "valor": _valor_de_criterio},
resultados={"valor": "eeg.{criterio}", "cri_anormal": "eeg.{criterio}_anormal",
"cri_decisivo": "eeg.{criterio}_decisivo", "cri_bajo": "eeg.{criterio}_bajo",
"cri_alto": "eeg.{criterio}_alto"},
),
DeStaging(
EegCriterio, "cri_id", "parte", estudio_id="eeg", paciente=None, padres=(EEG_DEL_CRITERIO,),
solo_si=lambda f: f.cri_electrodo is not None,
derivadas={"criterio": _criterio, "valor": _valor_de_criterio},
columnas={"codigo_fuente": "cri_electrodo"},
resultados={"valor": "eeg.{criterio}"},
),
DeStaging(
EegMetrica, "met_id", "toma", estudio_id="eeg", paciente=None, observa_en=SU_EEG,
derivadas={"metrica": _metrica},
resultados={"met_valor": "eeg.{metrica}"},
resultados={"met_valor": "eeg.{metrica}", **{f"met_{d}": f"eeg.{{metrica}}_{d}" for d in DEVIATION}},
),
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}"},
resultados={"mel_valor": "eeg.{metrica}", "mel_z": "eeg.{metrica}_z"},
),
)
+3 -1
View File
@@ -106,6 +106,7 @@ class RecomputationQueue:
def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]:
"""Runs the domain's graph (without `migrate`: the API migrates on startup)."""
from webapi.orchestration import Context, run, steps_of
from webapi.orchestration.eeg import live_eeg_analysis
from webapi.orchestration.estimators import live_estimators
desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5))
@@ -115,7 +116,8 @@ class RecomputationQueue:
self._save_status(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]})
entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]}
try:
ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio))
ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio),
eeg_analysis=live_eeg_analysis(dominio))
pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"])
entrada.update(
estado="ok",