|
|
|
@@ -4,7 +4,11 @@ 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. 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.
|
|
|
|
@@ -18,6 +22,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,25 +34,30 @@ 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, (
|
|
|
|
|
"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"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -263,12 +273,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 +319,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 +338,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 +359,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":
|
|
|
|
@@ -343,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"]))
|
|
|
|
@@ -362,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"]),
|
|
|
|
@@ -376,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)),
|
|
|
|
@@ -391,5 +503,11 @@ 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())
|
|
|
|
|
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]}
|
|
|
|
|