feat(tea): EEG analysis before the silver load, and its verdict, quality checks and baselines through silver and FHIR
This commit is contained in:
@@ -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")
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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.
|
||||
"""
|
||||
|
||||
@@ -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())
|
||||
@@ -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"},
|
||||
),
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user