feat(tea): import the ADOS-2 association model and serve it as a RiskAssessment in the patient summary

This commit is contained in:
2026-11-21 11:17:58 -06:00
parent 46473bb106
commit 31ab347347
10 changed files with 598 additions and 4 deletions
+95 -4
View File
@@ -6,7 +6,9 @@ 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. 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.
observations draw the baseline's full centile curve. The ADOS-2 association model reaches the summary as one
`RiskAssessment` per patient (a prediction per association row of `tea_paciente_relacion_ados2`), and stays out
while no model row scored the patient's study EEG.
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.
@@ -52,6 +54,10 @@ ELECTRODES = table("tea_paciente_eeg_electrodos", *map(column, ("procedimiento_i
ADOS2 = table("tea_paciente_ados2", *map(column, (
"procedimiento_id", "pac_id", "fecha_ados2", "modulo", "algoritmo", "css", "clasificacion", "dominio", "reactivo",
"etiqueta", "puntaje", "puntaje_algoritmo")))
RELACION = table("tea_paciente_relacion_ados2", *map(column, (
"pac_id", "procedimiento_id", "version", "validado", "nivel", "n_cohorte", "biomarcador", "zona", "tipo",
"resultado", "evento", "odds_ratio", "ic_inf", "ic_sup", "q", "valor_z", "probabilidad",
"probabilidad_referencia", "observado")))
PERSONS = table("persona", column("pac_id"), column("fecha_nacimiento"))
@@ -369,9 +375,85 @@ def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: li
return [procedure, tagged(report, simulated), *quality, *altered]
def relacion_ados2(rows: list[dict], pseudonym: str, fecha: date | None, ados2_id: int | None,
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
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
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"]))
return {
"outcome": outcome,
"probabilityDecimal": float(f["probabilidad"]),
"extension": [
{"url": f"{STRUCTURE}/biomarcador",
"valueCoding": coding(f"{CODE_SYSTEM}/tea-eeg-metrica", f["biomarcador"],
metricas.get((f["biomarcador"] or "").lower(), {}).get("etiqueta"))},
{"url": f"{STRUCTURE}/zona", "valueCoding": coding(f"{CODE_SYSTEM}/tea-eeg-zona", f["zona"],
zonas.get(f["zona"], f["zona"]))},
*([{"url": f"{STRUCTURE}/tipo", "valueString": f["tipo"]}] if f["tipo"] else []),
*([{"url": f"{STRUCTURE}/evento", "valueString": f["evento"]}] if f["evento"] else []),
*([{"url": f"{STRUCTURE}/valor-z", "valueDecimal": float(f["valor_z"])}]
if f["valor_z"] is not None else []),
*([{"url": f"{STRUCTURE}/odds-ratio", "valueDecimal": float(f["odds_ratio"])}]
if f["odds_ratio"] is not None else []),
*([{"url": f"{STRUCTURE}/ic-inf", "valueDecimal": float(f["ic_inf"])}]
if f["ic_inf"] is not None else []),
*([{"url": f"{STRUCTURE}/ic-sup", "valueDecimal": float(f["ic_sup"])}]
if f["ic_sup"] is not None else []),
*([{"url": f"{STRUCTURE}/q", "valueDecimal": float(f["q"])}] if f["q"] is not None else []),
*([{"url": f"{STRUCTURE}/probabilidad-referencia", "valueDecimal":
float(f["probabilidad_referencia"])}] if f["probabilidad_referencia"] is not None else []),
*([{"url": f"{STRUCTURE}/observado", "valueInteger": int(f["observado"])}]
if f["observado"] is not None else []),
],
}
primero = rows[0]
resource = {
"resourceType": "RiskAssessment", "id": f"relacion-ados2-{pseudonym}", "status": "final",
"subject": {"reference": f"Patient/{pseudonym}"},
"code": {"coding": [coding(f"{CODE_SYSTEM}/tea-relacion-ados2", "modelo",
"Modelo de asociación de alteraciones del EEG con el ADOS-2")],
"text": "Asociación de alteraciones del EEG con el ADOS-2"},
"extension": [
{"url": f"{STRUCTURE}/modelo-version", "valueString": primero["version"]},
{"url": f"{STRUCTURE}/modelo-validado", "valueBoolean": primero["validado"] == 1},
*([{"url": f"{STRUCTURE}/modelo-nivel", "valueString": primero["nivel"]}]
if primero["nivel"] else []),
*([{"url": f"{STRUCTURE}/modelo-n-cohorte", "valueInteger": int(primero["n_cohorte"])}]
if primero["n_cohorte"] is not None else []),
],
"prediction": [prediction(f) for f in sorted(
rows, key=lambda f: (f["q"] is None, f["q"] or 0, f["biomarcador"] or "", f["resultado"] or ""))],
"basis": [{"reference": f"DiagnosticReport/eeg-{primero['procedimiento_id']}"},
*([{"reference": f"Observation/ados2-{ados2_id}"}] if ados2_id is not None else [])],
}
if fecha is not None:
resource["occurrenceDateTime"] = _date(fecha).isoformat()
return tagged(resource, simulated)
def ados2_observation(rows: list[dict], pseudonym: str, simulated: bool) -> dict | None:
"""The first ADOS-2 as one `Observation`: module, algorithm, CSS, classification, the two domain totals and the
items, each item with its algorithm score."""
from webapi.fhir.terminology import DOMINIOS_ADOS2
if not rows:
return None
first = min(rows, key=lambda r: (_date(r["fecha_ados2"]) or date.max, r["procedimiento_id"]))
@@ -388,7 +470,7 @@ def ados2_observation(rows: list[dict], pseudonym: str, simulated: bool) -> dict
if first["clasificacion"]:
components.append({"code": concept(CATALOG, "ados2.clasificacion", "Clasificación"),
"valueCodeableConcept": concept(CATALOG, f"ados2.clasificacion.{first['clasificacion']}")})
for domain, label in (("SA", "Afecto social"), ("RRB", "Comportamiento restringido y repetitivo")):
for domain, label in DOMINIOS_ADOS2.items():
total = sum(int(r["puntaje_algoritmo"]) for r in items if r["dominio"] == domain)
components.append({"code": concept(f"{CODE_SYSTEM}/ados2-dominio", domain, label), "valueInteger": total})
components += [{"code": concept(CATALOG, r["reactivo"], r["etiqueta"]), "valueInteger": int(r["puntaje"]),
@@ -402,12 +484,16 @@ 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 screening episode (with its age group), its first ADOS-2 and
the EEG the study uses, as of today."""
the EEG the study uses, as of today, and the ADOS-2 association model as one `RiskAssessment` when model rows
scored the study's EEG."""
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)]
ados2 = ados2_observation(_rows(queries, select(ADOS2).where(ADOS2.c.pac_id == pac_id)), pseudonym, simulated)
ados2_rows = _rows(queries, select(ADOS2).where(ADOS2.c.pac_id == pac_id))
ados2 = ados2_observation(ados2_rows, pseudonym, simulated)
resources += [ados2] if ados2 else []
first_ados2 = min((r for r in ados2_rows if r["fecha_ados2"] is not None),
key=lambda r: (_date(r["fecha_ados2"]) or date.max, r["procedimiento_id"]), default=None)
(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)),
@@ -419,4 +505,9 @@ def patient_summary(queries, pac_id: int, today: date, simulated: bool) -> dict:
electrodes = _rows(queries, select(ELECTRODES).where(ELECTRODES.c.pac_id == pac_id))
resources += eeg_resources(eeg, pseudonym, e.metrics, electrodes, simulated, e.checks,
curves=baseline_curves())
riesgo = relacion_ados2(_rows(queries, select(RELACION).where(RELACION.c.pac_id == pac_id)), pseudonym,
eeg["fecha_eeg"] if eeg is not None else None,
first_ados2["procedimiento_id"] if first_ados2 is not None else None, simulated)
if riesgo:
resources.append(riesgo)
return {"resourceType": "Bundle", "type": "collection", "entry": [{"resource": r} for r in resources]}