feat(tea): each EEG metric's age-norm curve and the age at the EEG in the patient summary

This commit is contained in:
2026-11-21 11:17:48 -06:00
parent 6b8af821a3
commit 46473bb106
7 changed files with 465 additions and 33 deletions
+2 -1
View File
@@ -354,5 +354,6 @@ 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, e.checks)
resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated, e.checks,
curves=tea.baseline_curves())
return resources
+107
View File
@@ -0,0 +1,107 @@
"""The age-norm curves behind the EEG metrics' reference ranges, for the FHIR answers.
Each metric row names the baseline its analysis compared it against: its `modelo` (from `eeg_metrica.met_modelo`,
carried by `tea_paciente_eeg_metricas`) is the registered model's label, `tea-<scenario>/<version>`, pinned to the
version the analysis used (which may no longer be the one in production). The full centile curve of that exact
version is its registered artifact, loaded the way the analysis loads it (`models.tea.eeg.baselines`). A label that
can't be resolved, or a module that can't be loaded, gives no curve: the answer keeps the reference range it already
had.
"""
PERCENTILES = ("p5", "p25", "mediana", "p75", "p95")
class BaselineCurves:
"""Loads and caches the centile curves of the registered baselines the EEG analysis pinned.
`curve(label, metric)` is the curve the named version draws for the metric — `{"edad_meses": [...],
"p5": [...], "p25": [...], "mediana": [...], "p75": [...], "p95": [...]}` with the ages increasing and each
row's percentiles non-crossing — or None when the label doesn't name the metric's baseline or any step of the
resolution fails (unknown metric, unknown scenario, unreachable registry, unloadable artifact). Modules are
loaded once per label. `registry` and `loader` are injectable so tests run without a model registry.
"""
def __init__(self, registry=None, loader=None):
self._registry = registry
self._loader = loader
self._modules: dict[str, dict[str, object | None]] = {}
self._curves: dict[tuple[str, str], dict | None] = {}
def curve(self, label: str, metric: str) -> dict | None:
key = (label, metric)
if key not in self._curves:
self._curves[key] = self._extract(label, metric)
return self._curves[key]
def _extract(self, label: str, metric: str) -> dict | None:
spec = self._spec_of(metric)
module = self._module(label, spec.scenario) if spec is not None else None
if module is None:
return None
from models.tea.eeg.baselines import _feature_baseline
baseline = _feature_baseline(module, spec.feature)
curve = getattr(baseline, "curva", None) # a baseline without a curve (age blocks) draws none
if curve is None:
return None
rows = curve.dropna(subset=list(PERCENTILES))
if len(rows) < 2:
return None
return {"edad_meses": [float(v) for v in rows["edad_meses"]],
**{p: [float(v) for v in rows[p]] for p in PERCENTILES}}
@staticmethod
def _spec_of(metric: str):
"""The analysis's own mapping of the stored metric code to its library feature and baseline scenario."""
from models.tea.eeg.settings import settings
return next((m for m in settings().metrics if m.code.lower() == metric), None)
def _module(self, label: str, scenario: str):
modules = self._modules.setdefault(label, {})
if scenario not in modules:
modules[scenario] = self._load(label, scenario)
return modules[scenario]
def _load(self, label: str, scenario: str):
version = self._version(label, scenario)
if version is None:
return None
try:
registry = self._registry if self._registry is not None else _default_registry()
loader = self._loader if self._loader is not None else _default_loader()
return loader(registry.resolve("tea", scenario, version).model_uri)
except Exception: # the registry may be unreachable or the artifact unloadable; the curve is omitted
return None
@staticmethod
def _version(label: str, scenario: str) -> str | None:
"""The version the label pins for the scenario, looked up among its `;`-joined baseline names."""
for name_version in label.split(";"):
name, _, version = name_version.rpartition("/")
if name.removeprefix("tea-") == scenario and version:
return version
return None
def _default_registry():
from models.io.registry import registry
return registry
def _default_loader():
from models.tea.eeg.baselines import _load
return _load
_shared: BaselineCurves | None = None
def baseline_curves() -> BaselineCurves:
"""The process-wide loader: each label's module is loaded once per deployment."""
global _shared
if _shared is None:
_shared = BaselineCurves()
return _shared
+40 -13
View File
@@ -4,7 +4,9 @@ Read from dbt's views (`tea_seguimiento`, `tea_paciente_*`), which hold dates, n
at a date, the cut-off. A child's screening is an `EpisodeOfCare` from its first M-CHAT to its first good EEG, its
stage the furthest step reached by the cut-off (`type`, with its date as an extension), its pending steps a
`CarePlan`. The EEG the study uses is the child's first good EEG by the cut-off; without one, the latest, as not
valid. `Patient.id` is the salted pseudonym: `pac_id` never leaves.
valid. `Patient.id` is the salted pseudonym: `pac_id` never leaves. The views carry the age the analysis compared
the references at and, per metric, the registered label of the baseline that comparison used, from which the metric
observations draw the baseline's full centile curve.
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.
@@ -18,6 +20,7 @@ from datetime import date
from sqlalchemy import column, select, table
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, coding, concept, tagged
from webapi.fhir.eeg_curves import PERCENTILES, baseline_curves
STEPS = (("SOLO_MCHAT", "fecha_mchat", "M-CHAT"), ("PSICOLOGIA", "fecha_psicologia", "Evaluación psicológica"),
("NEUROPEDIATRIA", "fecha_neuropediatria", "Evaluación neuropediátrica"),
@@ -29,20 +32,21 @@ ICD10 = "http://hl7.org/fhir/sid/icd-10"
CATALOG = f"{CODE_SYSTEM}/tea-catalogo"
STAGE_DATE = f"{STRUCTURE}/fecha-etapa"
AGE_GROUP = f"{STRUCTURE}/grupo-edad"
CURVE = f"{STRUCTURE}/curva-referencia"
DEFAULT_SALT = "dev-simulado"
FOLLOW_UP = table("tea_seguimiento", *map(column, (
"pac_id", "grupo_edad", "fecha_mchat", "mchat", "fecha_psicologia", "css_ados2", "modulo_ados2",
"fecha_neuropediatria", "fecha_tea", "fecha_sin_tea", "fecha_eeg")))
EEGS = table("tea_paciente_eegs", *map(column, (
"procedimiento_id", "pac_id", "fecha_eeg", "con_sueno", "canales", "duracion_min", "nivel", "fraccion_limpia",
"canales_malos", "ruido_linea_db", "calidad", "valido")))
"procedimiento_id", "pac_id", "fecha_eeg", "con_sueno", "canales", "duracion_min", "edad_meses", "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_mediana", "ref_max", "valor_z",
"estado")))
"procedimiento_id", "pac_id", "metrica", "valor", "grupo_edad_eeg", "ref_min", "ref_mediana", "ref_max", "modelo",
"valor_z", "estado")))
ELECTRODES = table("tea_paciente_eeg_electrodos", *map(column, ("procedimiento_id", "pac_id", "metrica", "electrodo",
"valor", "valor_z")))
ADOS2 = table("tea_paciente_ados2", *map(column, (
@@ -263,12 +267,26 @@ def quality_observations(eeg: dict, checks: list[dict], pseudonym: str, simulate
return observations
def curve_extension(label: str, curve: dict) -> dict:
"""The reference curve as one nested extension on the metric observation. `fuente` is the baseline's registered
label and `estado` the alterations validation gate (`TEA_ALTERACIONES_VALIDADAS`); each series is a run of
sub-extensions, one per point, read back in order (`edad-meses`, then the five percentiles), because a FHIR
extension holds scalars, not arrays."""
series = (("edad-meses", curve["edad_meses"]), *((p, curve[p]) for p in PERCENTILES))
return {"url": CURVE, "extension": [
{"url": f"{CURVE}/fuente", "valueString": label},
{"url": f"{CURVE}/estado", "valueString": "validada" if alterations_validated() else "pendiente"},
*({"url": f"{CURVE}/{name}", "valueDecimal": float(value)} for name, values in series for value in values)]}
def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict], pseudonym: str,
simulated: bool) -> list[dict]:
simulated: bool, curves=None) -> list[dict]:
"""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."""
as the reference, H/L/N, and the z and the baseline's median as components. With the baseline's label
(`modelo`) and a loader, the observation also carries the baseline's full centile curve as an extension. 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 = []
@@ -295,6 +313,10 @@ def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict],
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']}"}]
if curves is not None and m.get("modelo"):
curve = curves.curve(m["modelo"], m["metrica"])
if curve is not None:
resource.setdefault("extension", []).append(curve_extension(m["modelo"], curve))
observations.append(tagged(resource, simulated))
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]
@@ -310,11 +332,13 @@ def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict],
def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: list[dict], simulated: bool,
checks: list[dict] = ()) -> list[dict]:
checks: list[dict] = (), curves=None) -> 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."""
no result beyond its quality, and the alterations stay out until validated. The report carries the recording's
duration, channel count and the age the analysis compared the references at as extensions, and each metric
observation the baseline's full centile curve when its label resolves (`curves`)."""
quality = quality_observations(eeg, list(checks), pseudonym, simulated)
altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated)
altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated, curves)
if eeg["valido"] == 1 and alterations_validated() else [])
procedure = tagged({"resourceType": "Procedure", "id": f"eeg-{eeg['procedimiento_id']}", "status": "completed",
"code": concept(CATALOG, "eeg", "Electroencefalograma"),
@@ -329,10 +353,12 @@ def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: li
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:
if eeg["duracion_min"] is not None or eeg["edad_meses"] 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}/edad-meses", "valueDecimal": float(eeg["edad_meses"])}
if eeg["edad_meses"] 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["calidad"] == "SIN_ANALIZAR":
@@ -391,5 +417,6 @@ def patient_summary(queries, pac_id: int, today: date, simulated: bool) -> dict:
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, e.checks)
resources += eeg_resources(eeg, pseudonym, e.metrics, electrodes, simulated, e.checks,
curves=baseline_curves())
return {"resourceType": "Bundle", "type": "collection", "entry": [{"resource": r} for r in resources]}
+5 -4
View File
@@ -4,9 +4,9 @@
- 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;
- 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.
electrode) and each metric with its deviation from the age baseline and the baseline's registered label 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 (
@@ -140,7 +140,8 @@ DESDE_STAGING = (
DeStaging(
EegMetrica, "met_id", "toma", estudio_id="eeg", paciente=None, observa_en=SU_EEG,
derivadas={"metrica": _metrica},
resultados={"met_valor": "eeg.{metrica}", **{f"met_{d}": f"eeg.{{metrica}}_{d}" for d in DEVIATION}},
resultados={"met_valor": "eeg.{metrica}", **{f"met_{d}": f"eeg.{{metrica}}_{d}" for d in DEVIATION},
"met_modelo": "eeg.{metrica}_modelo"},
),
DeStaging(
EegMetricaElectrodo, "mel_id", "parte", estudio_id="eeg", paciente=None,