Files
WebApi/webapi/fhir/tea.py

514 lines
30 KiB
Python

"""TEA's patients as FHIR R4 resources: the follow-up list as `EpisodeOfCare`s and the patient summary.
Read from dbt's views (`tea_seguimiento`, `tea_paciente_*`), which hold dates, not states: every state here is taken
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. 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.
"""
import hashlib
import os
from dataclasses import dataclass, field
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"),
("EEG", "fecha_eeg", "EEG de buena calidad"))
ALTERED = ("aumentado", "disminuido")
INTERPRETATION = "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation"
ABSENT = "http://terminology.hl7.org/CodeSystem/data-absent-reason"
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", "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", "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"))
def alterations_validated() -> bool:
"""Whether the domain expert validated the EEG analysis's age baselines and the effect texts
(`TEA_ALTERACIONES_VALIDADAS=1`): until then no alteration is shown."""
return os.environ.get("TEA_ALTERACIONES_VALIDADAS", "") in ("1", "true", "si")
def salt() -> str:
return os.environ.get("SEGUIMIENTO_SAL", DEFAULT_SALT)
def seudonimo(pac_id: int, sal: str) -> str:
"""TEA's patient and episode ids: stable for a salt, without saying the `pac_id`. CaCu's follow-up list moved
to the platform's `pac_id`; TEA keeps the pseudonym until its patient resources get their own identity."""
return "P-" + hashlib.sha256(f"{sal}:{pac_id}".encode()).hexdigest()[:10].upper()
def _date(value) -> date | None:
if value is None or isinstance(value, date):
return value
return date.fromisoformat(str(value)[:10])
def _rows(queries, query) -> list[dict]:
columns, rows = queries.rows(query)
return [dict(zip(columns, row)) for row in rows]
@dataclass
class Episode:
"""A child's screening at the cut-off: its follow-up row, the steps reached, the study's EEG and its metrics."""
child: dict
cutoff: date
eegs: list[dict]
metrics: list[dict]
checks: list[dict] = field(default_factory=list)
@property
def pseudonym(self) -> str:
return seudonimo(self.child["pac_id"], salt())
def reached(self) -> list[tuple[str, date, str]]:
steps = []
for code, field, label in STEPS:
when = _date(self.child[field])
if when is None or when > self.cutoff:
break
steps.append((code, when, label))
return steps
@property
def stage(self) -> tuple[str, date] | None:
steps = self.reached()
return (steps[-1][0], steps[-1][1]) if steps else None
@property
def finished(self) -> bool:
return any(code == "EEG" for code, _, _ in self.reached())
@property
def pending(self) -> list[str]:
done = {code for code, _, _ in self.reached()}
return [label for code, _, label in STEPS if code not in done]
@property
def diagnosis(self) -> bool | None:
"""True with a F84.0 note by the cut-off, False with only notes without it, None without a note."""
if (_date(self.child["fecha_tea"]) or date.max) <= self.cutoff:
return True
if (_date(self.child["fecha_sin_tea"]) or date.max) <= self.cutoff:
return False
return None
def study_eeg(self) -> dict | None:
"""The first good EEG by the cut-off; without one, the latest by then (not valid)."""
known = sorted((e for e in self.eegs if (_date(e["fecha_eeg"]) or date.max) <= self.cutoff),
key=lambda e: (_date(e["fecha_eeg"]), e["procedimiento_id"]))
good = [e for e in known if e["valido"] == 1]
return good[0] if good else (known[-1] if known else None)
def alterations(self) -> list[str]:
eeg = self.study_eeg()
if eeg is None or eeg["valido"] != 1:
return []
return sorted(m["metrica"] for m in self.metrics
if m["procedimiento_id"] == eeg["procedimiento_id"] and m["estado"] in ALTERED)
@property
def eeg_result(self) -> str:
eeg = self.study_eeg()
if eeg is None or eeg["valido"] != 1:
return "sin-eeg-valido"
return "anormal" if self.alterations() else "normal"
def episodes(queries, cutoff: date) -> list[Episode]:
"""Every child of the cohort who entered the screening by the cut-off, with its EEGs and their metrics."""
eegs, metrics, checks = (_rows(queries, select(EEGS)), _rows(queries, select(METRICS)),
_rows(queries, select(CHECKS)))
by_child = {}
for child in _rows(queries, select(FOLLOW_UP)):
if (_date(child["fecha_mchat"]) or date.max) <= cutoff:
by_child[child["pac_id"]] = Episode(child, cutoff, [], [])
for rows, kind in ((eegs, "eegs"), (metrics, "metrics"), (checks, "checks")):
for row in rows:
if row["pac_id"] in by_child:
getattr(by_child[row["pac_id"]], kind).append(row)
return list(by_child.values())
def patient_of(queries, pseudonym: str) -> int | None:
"""The `pac_id` behind a pseudonym, among the cohort's children."""
for child in _rows(queries, select(FOLLOW_UP.c.pac_id)):
if seudonimo(child["pac_id"], salt()) == pseudonym:
return child["pac_id"]
return None
# --- resources -------------------------------------------------------------------------------------------------------
def patient(pac_id: int, birth: date | None, simulated: bool) -> dict:
resource = {"resourceType": "Patient", "id": seudonimo(pac_id, salt())}
if birth is not None:
resource["birthDate"] = _date(birth).strftime("%Y-%m")
return tagged(resource, simulated)
def episode_of_care(e: Episode, simulated: bool) -> dict:
stage = e.stage
resource = {
"resourceType": "EpisodeOfCare", "id": e.pseudonym, "status": "finished" if e.finished else "active",
"patient": {"reference": f"Patient/{e.pseudonym}"},
"period": {"start": _date(e.child["fecha_mchat"]).isoformat(),
**({"end": stage[1].isoformat()} if e.finished else {})},
"extension": [{"url": AGE_GROUP, "valueCoding": {"system": f"{CODE_SYSTEM}/grupo-edad",
"code": e.child["grupo_edad"]}}],
}
if stage is not None:
resource["type"] = [concept(f"{CODE_SYSTEM}/paso", stage[0])]
resource["extension"].append({"url": STAGE_DATE, "valueDate": stage[1].isoformat()})
return tagged(resource, simulated)
def care_plan(e: Episode, simulated: bool) -> dict:
"""The episode's steps, each `completed` with its date or `not-started`."""
done = {code: when for code, when, _ in e.reached()}
activities = [{"detail": {
"code": concept(f"{CODE_SYSTEM}/paso", code, text=label),
"status": "completed" if code in done else "not-started",
**({"scheduledString": done[code].isoformat()} if code in done else {})}} for code, _, label in STEPS]
return tagged({"resourceType": "CarePlan", "id": f"pasos-{e.pseudonym}", "status": "active" if not e.finished
else "completed", "intent": "plan", "subject": {"reference": f"Patient/{e.pseudonym}"},
"extension": [{"url": f"{STRUCTURE}/episodio", "valueReference": {
"reference": f"EpisodeOfCare/{e.pseudonym}"}}],
"activity": activities}, simulated)
def mchat_observation(e: Episode, simulated: bool) -> dict | None:
if e.child["mchat"] is None:
return None
return tagged({"resourceType": "Observation", "id": f"mchat-{e.pseudonym}", "status": "final",
"code": concept(CATALOG, "mchat.puntaje", "M-CHAT-R/F: puntaje total"),
"subject": {"reference": f"Patient/{e.pseudonym}"},
"effectiveDateTime": _date(e.child["fecha_mchat"]).isoformat(),
"valueInteger": int(e.child["mchat"])}, simulated)
def condition(e: Episode, simulated: bool) -> dict | None:
if not e.diagnosis:
return None
return tagged({"resourceType": "Condition", "id": f"tea-{e.pseudonym}",
"code": concept(ICD10, "F84.0", "Autismo en la niñez"),
"subject": {"reference": f"Patient/{e.pseudonym}"},
"recordedDate": _date(e.child["fecha_tea"]).isoformat()}, simulated)
def quality_observations(eeg: dict, checks: list[dict], pseudonym: str, simulated: bool) -> list[dict]:
"""One `Observation` per quality check the EEG analysis evaluated, as the analysis's own validation report writes
it (`tea.validation.fhir`): its code in the analysis's code system, its value (a quantity or a text), whether it
was abnormal (A/N), its limit as the reference range, and as components the bad channel's electrode and whether
the check alone can make the EEG not valid. Study-wide checks first, then the bad channels by electrode."""
from tea.validation.fhir import INTERP, SYSTEM
observations = []
mine = [c for c in checks if c["procedimiento_id"] == eeg["procedimiento_id"]]
for c in sorted(mine, key=lambda c: (c["electrodo"] is not None, c["electrodo"] or "", c["criterio"])):
code, unit = c["criterio"].replace("_", "-"), c["unidad"]
quantity = (lambda v: {"value": float(v), **({"unit": unit} if unit else {})})
resource = {
"resourceType": "Observation",
"id": "-".join(p for p in ("calidad", code, c["electrodo"], str(eeg["procedimiento_id"])) if p),
"status": "final", "code": {"coding": [coding(SYSTEM, code, c["etiqueta"] or code)],
"text": c["etiqueta"] or code},
"subject": {"reference": f"Patient/{pseudonym}"}, "effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
"interpretation": [concept(INTERP, "A" if c["anormal"] else "N")],
}
if c["valor"] is not None:
resource["valueQuantity"] = quantity(c["valor"])
elif c["valor_texto"] is not None:
resource["valueString"] = c["valor_texto"]
limits = {k: quantity(c[v]) for k, v in (("low", "bajo"), ("high", "alto")) if c[v] is not None}
if limits:
resource["referenceRange"] = [limits]
resource["component"] = [
*([{"code": {"text": "electrode"}, "valueString": c["electrodo"]}] if c["electrodo"] else []),
{"code": {"text": "decisive"}, "valueBoolean": bool(c["decisivo"])},
]
observations.append(tagged(resource, simulated))
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, 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. 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 = []
for m in sorted((m for m in metrics if m["procedimiento_id"] == eeg["procedimiento_id"]), key=lambda m: m["metrica"]):
spec = TEA_EEG["metricas"].get(m["metrica"], {"etiqueta": m["metrica"], "unidad": ""})
code = concept(f"{CODE_SYSTEM}/tea-eeg-metrica", m["metrica"], spec["etiqueta"])
resource = {"resourceType": "Observation", "id": f"{m['metrica'].replace('_', '-')}-{eeg['procedimiento_id']}",
"status": "final", "code": code, "subject": {"reference": f"Patient/{pseudonym}"},
"effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat()}
if m["valor"] is None:
resource["dataAbsentReason"] = concept(ABSENT, "not-performed")
else:
resource["valueQuantity"] = {"value": float(m["valor"]), "unit": spec["unidad"]}
if m["valor"] is not None and m["valor_z"] is not None:
resource["interpretation"] = [concept(INTERPRETATION, {"aumentado": "H", "disminuido": "L"}.get(
m["estado"], "N"))]
resource["component"] = [{"code": concept(f"{CODE_SYSTEM}/puntaje", "z", "Puntaje z"),
"valueQuantity": {"value": round(float(m["valor_z"]), 2)}}]
if m["ref_mediana"] is not None:
resource["component"].append({
"code": concept(f"{CODE_SYSTEM}/puntaje", "mediana", "Mediana de la referencia a la edad"),
"valueQuantity": {"value": float(m["ref_mediana"]), "unit": spec["unidad"]}})
if m["ref_min"] is not None:
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]
if at:
observations.append(tagged({
"resourceType": "Observation", "id": f"electrodos-{m['metrica'].replace('_', '-')}-{eeg['procedimiento_id']}",
"status": "final", "code": code, "subject": {"reference": f"Patient/{pseudonym}"},
"effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
"component": [{"code": concept(f"{CODE_SYSTEM}/electrodo-10-20", x["electrodo"]),
"valueQuantity": {"value": round(float(x["valor_z"]), 2)}}
for x in sorted(at, key=lambda x: x["electrodo"])]}, simulated))
return observations
def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: list[dict], simulated: bool,
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. 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, 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"),
"subject": {"reference": f"Patient/{pseudonym}"},
"performedDateTime": _date(eeg["fecha_eeg"]).isoformat()}, simulated)
report = {"resourceType": "DiagnosticReport", "id": f"eeg-{eeg['procedimiento_id']}", "status": "final",
"code": concept(CATALOG, "eeg", "Electroencefalograma"), "subject": {"reference": f"Patient/{pseudonym}"},
"effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
"result": [{"reference": f"Observation/{o['id']}"} for o in quality + altered],
"conclusionCode": [concept(f"{CODE_SYSTEM}/calidad", eeg["calidad"])]}
if eeg["calidad"] != "SIN_ANALIZAR":
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["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":
report["conclusion"] = "EEG sin analizar todavía: no es válido para el estudio."
elif eeg["valido"] != 1:
report["conclusion"] = "EEG de mala calidad: no es válido para el estudio" + (
f" (nivel de triaje: {eeg['nivel']})." if eeg["nivel"] else ".")
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"]))
items = [r for r in rows if r["procedimiento_id"] == first["procedimiento_id"] and r["reactivo"]]
components = []
if first["modulo"]:
components.append({"code": concept(CATALOG, "ados2.modulo", "Módulo"),
"valueCodeableConcept": concept(CATALOG, f"ados2.modulo.{first['modulo']}")})
if first["algoritmo"]:
components.append({"code": concept(CATALOG, "ados2.algoritmo", "Algoritmo"), "valueString": first["algoritmo"]})
if first["css"] is not None:
components.append({"code": concept(CATALOG, "ados2.css", "Puntaje de severidad (CSS)"),
"valueInteger": int(first["css"])})
if first["clasificacion"]:
components.append({"code": concept(CATALOG, "ados2.clasificacion", "Clasificación"),
"valueCodeableConcept": concept(CATALOG, f"ados2.clasificacion.{first['clasificacion']}")})
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"]),
"extension": [{"url": f"{STRUCTURE}/puntaje-algoritmo", "valueInteger": int(r["puntaje_algoritmo"])},
{"url": f"{STRUCTURE}/dominio", "valueCode": r["dominio"]}]}
for r in sorted(items, key=lambda r: r["reactivo"])]
return tagged({"resourceType": "Observation", "id": f"ados2-{first['procedimiento_id']}", "status": "final",
"code": concept(CATALOG, "ados2", "ADOS-2"), "subject": {"reference": f"Patient/{pseudonym}"},
"effectiveDateTime": _date(first["fecha_ados2"]).isoformat(), "component": components}, simulated)
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, 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_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)),
_rows(queries, select(METRICS).where(METRICS.c.pac_id == pac_id)),
_rows(queries, select(CHECKS).where(CHECKS.c.pac_id == pac_id)))
resources.append(episode_of_care(e, simulated))
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,
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]}