feat(tea): EEG analysis before the silver load, and its verdict, quality checks and baselines through silver and FHIR

This commit is contained in:
AlbertoPMDM
2026-11-19 15:43:27 -06:00
parent b1bbbc25b4
commit d35e8bbae9
26 changed files with 1486 additions and 312 deletions
+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",