TEA: the cycle's relate_ados2 step between the EEG analysis and the load, and the ADOS-2 relation in FHIR

This commit is contained in:
ulises
2026-11-21 23:18:39 -06:00
parent 71557ecbd3
commit 74303aa1b9
15 changed files with 235 additions and 71 deletions
+4 -8
View File
@@ -379,24 +379,20 @@ def relacion_ados2(rows: list[dict], pseudonym: str, fecha: date | None, ados2_i
simulated: bool) -> dict | None:
"""The association model as one `RiskAssessment`: a prediction per association row that scored the study's EEG,
the clearest cohort association (lowest q) first. The model's version, expert validation, level and cohort size
sit on the resource; each prediction carries the outcome (the ADOS-2 item or domain) and the probability the
sit on the resource; each prediction carries the outcome (an ADOS-2 item meaning or the total CSS) and the probability the
model gives the patient, and as extensions the EEG metric and scalp zone, the patient's z, the cohort's odds
ratio with its confidence interval and q, the reference probability (z = 0) and the outcome observed in the
patient's ADOS-2. Zone and outcome labels come from the code systems, not from the row. Without rows there is
no resource."""
if not rows:
return None
from webapi.fhir.terminology import DOMINIOS_ADOS2, TEA_EEG, ados2_resultados
from webapi.fhir.terminology import TEA_EEG, ados2_resultados
resultados, metricas, zonas = ados2_resultados(), TEA_EEG["metricas"], TEA_EEG["zonas"]
def prediction(f: dict) -> dict:
if f["tipo"] == "item":
code = f"ados2.{f['resultado']}"
outcome = concept(CATALOG, code, resultados.get(code, f["resultado"]))
else:
outcome = concept(f"{CODE_SYSTEM}/ados2-dominio", f["resultado"],
DOMINIOS_ADOS2.get(f["resultado"], f["resultado"]))
outcome = concept(f"{CODE_SYSTEM}/tea-ados2-resultado", f["resultado"],
resultados.get(f["resultado"], f["resultado"]))
return {
"outcome": outcome,
"probabilityDecimal": float(f["probabilidad"]),
+5 -1
View File
@@ -58,12 +58,16 @@ O1 = [-0.25, -0.77]
O2 = [0.25, -0.77]
# The scalp zones the association model relates an EEG alteration in with an ADOS-2 outcome, as the `tea` library
# codes them: what each zone is called on screen. A code outside this list shows as written.
# codes them, plus `posterior` (the posterior rhythm) and `global` (the anteroposterior gradient): what each zone is
# called on screen. A code outside this list shows as written.
[zonas]
frontal_izq = "Frontal izquierda"
frontal_der = "Frontal derecha"
frontal_media = "Frontal media"
central = "Central"
temporal_izq = "Temporal izquierda"
temporal_der = "Temporal derecha"
parietal = "Parietal"
occipital = "Occipital"
posterior = "Posterior"
global = "Global"
+8 -5
View File
@@ -1,6 +1,6 @@
"""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, TEA's EEG metrics with their effect texts (`tea_eeg.toml`), and the EEG analysis's quality checks, under
results, the ADOS-2 association model's outcomes (`core.tea.models.ADOS2_ITEM_MEANINGS` and the CSS), 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
@@ -15,13 +15,14 @@ STAGES = (("SOLO_MCHAT", "Solo M-CHAT"), ("PSICOLOGIA", "Hasta evaluación psico
DIAGNOSES = (("EN_PROCESO", "En proceso"), ("SIN_TEA", "Nota sin F84.0"), ("CONFIRMADO", "Diagnóstico confirmado"))
QUALITY = (("BUENO", "Bueno"), ("MALO", "Malo"), ("SIN_ANALIZAR", "Sin analizar"))
DOMINIOS_ADOS2 = {"SA": "Afecto social", "RRB": "Comportamiento restringido y repetitivo"}
CSS_ETIQUETA = "Puntaje de severidad calibrado (CSS)"
def ados2_resultados() -> dict[str, str]:
"""The ADOS-2 results' labels from the domain catalog, by their catalog code (`ados2.sa_b9`): what an
association row's outcome shows as."""
results = tomllib.loads(ruta_de_catalogo("tea").read_text(encoding="utf-8"))["ados2"]["resultados"]
return {f"ados2.{name}": spec["etiqueta"] for name, spec in results.items()}
"""The association model's outcome labels by code: each item meaning (`ados2_item_11`) and the total CSS."""
from core.tea.models import ADOS2_CSS, ADOS2_ITEM_MEANINGS
return {**{code: label for code, (label, _, _) in ADOS2_ITEM_MEANINGS.items()}, ADOS2_CSS: CSS_ETIQUETA}
def _code_system(id_: str, title: str, concepts: list[dict], *, hierarchy: bool = False) -> dict:
@@ -76,6 +77,8 @@ def tea_code_systems() -> dict[str, dict]:
[{"code": e, "display": e} for e in TEA_EEG["electrodos"]]),
_code_system("tea-eeg-zona", "Zonas del cuero cabelludo",
[{"code": z, "display": e} for z, e in TEA_EEG["zonas"].items()]),
_code_system("tea-ados2-resultado", "Desenlaces del ADOS-2 del modelo de asociación",
[{"code": c, "display": e} for c, e in ados2_resultados().items()]),
_code_system("grupo-edad", "Grupo de edad al primer M-CHAT", [
{"code": "16_23", "display": "16 a 23 meses"}, {"code": "24_29", "display": "24 a 29 meses"},
{"code": "30_36", "display": "30 a 36 meses"}, {"code": "sin_dato", "display": "Sin dato"}]),
+7 -5
View File
@@ -1,18 +1,19 @@
"""Import schema for `core.tea.models.RelacionAdos2`: one association of an EEG alteration in a scalp zone with an
ADOS-2 item or domain outcome, per fitted model version. `rel_evento` is the outcome event as a threshold on its
score, machine-readable (`>=2`); it is shown as written, never parsed."""
ADOS-2 outcome, per fitted model version. An item outcome is an item meaning code (`ADOS2_ITEM_MEANINGS`), the same
in every module; a domain outcome is the total calibrated severity score (`ADOS2_CSS`). `rel_evento` is the outcome
event as a threshold on its score, machine-readable (`>=1`); it is shown as written, never parsed."""
from typing import Annotated, Optional
from pydantic import Field, model_validator
from core.tea.enums import MetricaEeg, NivelRelacionAdos2
from core.tea.models import ADOS2_ITEMS
from core.tea.models import ADOS2_CSS, ADOS2_ITEM_MEANINGS
from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import Bounded, Catalog, CatalogValue, OptionalStr, ShortKey, SourceId
_NIVEL_CATALOG = Catalog(NivelRelacionAdos2)
_BIOMARCADOR_CATALOG = Catalog(MetricaEeg)
_DOMINIOS_ADOS2 = {"SA", "RRB"}
_RESULTADOS_DOMINIO = {ADOS2_CSS}
class RelacionAdos2ImportSchema(ImportSchema):
@@ -37,7 +38,8 @@ class RelacionAdos2ImportSchema(ImportSchema):
if self.rel_ic_inf is not None and self.rel_ic_sup is not None and self.rel_ic_inf > self.rel_ic_sup:
raise ValueError("rel_ic_inf no puede ser mayor que rel_ic_sup")
if self.rel_tipo is not None and self.rel_resultado is not None:
validos = set(ADOS2_ITEMS) if self.rel_tipo == NivelRelacionAdos2.ITEM.value else _DOMINIOS_ADOS2
validos = (set(ADOS2_ITEM_MEANINGS) if self.rel_tipo == NivelRelacionAdos2.ITEM.value
else _RESULTADOS_DOMINIO)
if self.rel_resultado not in validos:
raise ValueError(f"'{self.rel_resultado}' no es un código de {self.rel_tipo} del ADOS-2")
return self
+3 -1
View File
@@ -6,7 +6,9 @@ Each step is a function of `cycle.py`. It takes the `Context` and, as parameters
Hamilton builds the graph from those names. Steps pass no data: everything goes through the database, by
Persistance's repositories (`ctx.repos`), so each one can run on its own.
migrate -> catalogs, registry, definitions
migrate -> catalogs, registry, definitions, analyze_eeg
analyze_eeg -> relate_ados2, load (TEA: the EEG analysis)
relate_ados2 -> load (TEA: the ADOS-2 association)
catalogs -> load, check_silver
load -> views, event_models, observe, check_silver
registry -> observe
+3 -2
View File
@@ -13,7 +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.eeg import live_ados2_relation, live_eeg_analysis
from webapi.orchestration.estimators import live_estimators
from webapi.orchestration.runner import run
@@ -45,7 +45,8 @@ 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), eeg_analysis=live_eeg_analysis(args.project))
estimators=live_estimators(args.project), eeg_analysis=live_eeg_analysis(args.project),
ados2_relation=live_ados2_relation(args.project))
for paso in run(ctx, only=args.only):
print(f"{paso.name:20} {paso.seconds:6.1f} s")
+3
View File
@@ -42,5 +42,8 @@ class Context:
# 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)
# The domain's ADOS-2 association (`webapi.orchestration.eeg.live_ados2_relation`): run by the `relate_ados2` step
# after the EEG analysis, it fits the model on the analysed EEGs. Without it, that step does nothing.
ados2_relation: 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)
+14 -3
View File
@@ -84,15 +84,26 @@ def catalogs(migrate: str, ctx: Context) -> dict[str, int]:
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`.
it: the verdict, quality checks and metrics in `eeg`, `eeg_criterio`, `eeg_metrica`, `eeg_metrica_electrodo`
and `eeg_metrica_zona`.
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.
def relate_ados2(analyze_eeg: dict[str, int], ctx: Context) -> dict:
"""The ADOS-2 association fitted on the EEGs the analysis left (`ctx.ados2_relation`), written to
`relacion_ados2` and `relacion_ados2_paciente` before `load`, so the same cycle's gold views show it. Returns
the version and its counts; nothing without an association (every domain but TEA)."""
if ctx.ados2_relation is None:
return {}
return asdict(ctx.ados2_relation())
def load(catalogs: dict[str, int], analyze_eeg: dict[str, int], relate_ados2: dict, ctx: Context) -> SQLModel:
"""`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c), after the EEG analysis and
the ADOS-2 association.
Incremental por la llave lógica de cada procedimiento (`save_load_in`): repetir no cambia nada.
"""
+16 -1
View File
@@ -1,8 +1,10 @@
"""TEA's EEG analysis as the cycle runs it: the `tea` library over each stored EDF, before the silver load.
"""TEA's EEG analysis as the cycle runs it: the `tea` library over each stored EDF, before the silver load, and the
ADOS-2 association fitted on what it left.
`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).
`ADOS2_RELATION=off` leaves the association out (`python -m models tea relate-ados2` still runs it).
"""
import os
from collections.abc import Callable
@@ -11,6 +13,7 @@ from typing import Any
CLUSTER_ENV = "EEG_ANALYSIS_CLUSTER"
CLUSTERS = ("auto", "local", "remote", "sync")
RELATION_ENV = "ADOS2_RELATION"
def cluster() -> str:
@@ -27,3 +30,15 @@ def live_eeg_analysis(domain: str) -> Callable[[], Any] | None:
from models.eeg_analysis import analyze_pending
return partial(analyze_pending, cluster=cluster())
def live_ados2_relation(domain: str) -> Callable[[], Any] | None:
"""The domain's ADOS-2 association for the cycle, or none: only TEA has one, and `off` leaves it out."""
value = os.environ.get(RELATION_ENV, "on")
if value not in ("on", "off"):
raise ValueError(f"{RELATION_ENV} must be on or off, not {value!r}")
if domain != "tea" or value == "off":
return None
from models.ados2_relation import relate
return relate
+2 -2
View File
@@ -106,7 +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.eeg import live_ados2_relation, live_eeg_analysis
from webapi.orchestration.estimators import live_estimators
desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5))
@@ -117,7 +117,7 @@ class RecomputationQueue:
entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]}
try:
ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio),
eeg_analysis=live_eeg_analysis(dominio))
eeg_analysis=live_eeg_analysis(dominio), ados2_relation=live_ados2_relation(dominio))
pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"])
entrada.update(
estado="ok",