Files
WebApi/webapi/fhir/tea.py
T

359 lines
20 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.
Until the domain expert validates the reference ranges, 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
from datetime import date
from sqlalchemy import column, select, table
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, concept, tagged
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"))
CRITERIA = (("calidad_amplitud", "Canales con amplitud extrema", "canales"),
("calidad_alta_frecuencia", "Ruido de alta frecuencia", "canales"),
("calidad_correlacion", "Baja correlación entre canales", "canales"),
("calidad_sin_senal", "Canales planos o sin señal", "canales"),
("calidad_linea", "Ruido de la línea eléctrica", "dB"))
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"
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", "calidad", "valido",
*(c for name, _, _ in CRITERIA for c in (name, f"{name}_bueno")))))
METRICS = table("tea_paciente_eeg_metricas", *map(column, (
"procedimiento_id", "pac_id", "metrica", "valor", "grupo_edad_eeg", "ref_min", "ref_max", "valor_z", "estado")))
ELECTRODES = table("tea_paciente_eeg_electrodos", *map(column, ("procedimiento_id", "pac_id", "metrica", "electrodo",
"valor")))
ADOS2 = table("tea_paciente_ados2", *map(column, (
"procedimiento_id", "pac_id", "fecha_ados2", "modulo", "algoritmo", "css", "clasificacion", "dominio", "reactivo",
"etiqueta", "puntaje", "puntaje_algoritmo")))
PERSONS = table("persona", column("pac_id"), column("fecha_nacimiento"))
def alterations_validated() -> bool:
"""Whether the domain expert validated the reference ranges, effect texts and quality thresholds
(`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]
@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 = _rows(queries, select(EEGS)), _rows(queries, select(METRICS))
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 eeg in eegs:
if eeg["pac_id"] in by_child:
by_child[eeg["pac_id"]].eegs.append(eeg)
for metric in metrics:
if metric["pac_id"] in by_child:
by_child[metric["pac_id"]].metrics.append(metric)
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, pseudonym: str, simulated: bool) -> list[dict]:
observations = []
for name, label, unit in CRITERIA:
if eeg[name] is None:
continue
value = ({"valueInteger": int(eeg[name])} if unit == "canales"
else {"valueQuantity": {"value": float(eeg[name]), "unit": unit}})
observations.append(tagged({
"resourceType": "Observation", "id": f"{name.replace('_', '-')}-{eeg['procedimiento_id']}",
"status": "final", "code": concept(CATALOG, f"eeg.{name}", label),
"subject": {"reference": f"Patient/{pseudonym}"}, "effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
**value, "interpretation": [concept(f"{CODE_SYSTEM}/calidad", "BUENO" if eeg[f"{name}_bueno"] else "MALO")],
}, simulated))
return observations
def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict], pseudonym: str,
simulated: bool) -> list[dict]:
"""One `Observation` per metric (value, reference for the age at the EEG, H/L/N, the z-score as a component, or
why it couldn't be evaluated) and one per metric with a component per electrode."""
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 or m["valor_z"] is None:
resource["dataAbsentReason"] = concept(ABSENT, "not-performed" if m["valor"] is None else "unknown")
else:
resource["valueQuantity"] = {"value": float(m["valor"]), "unit": spec["unidad"]}
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_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']}"}]
observations.append(tagged(resource, simulated))
at = [x for x in electrodes if x["procedimiento_id"] == eeg["procedimiento_id"] and x["metrica"] == m["metrica"]]
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": float(x["valor"])}}
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) -> 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."""
quality = quality_observations(eeg, pseudonym, simulated)
altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated)
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["duracion_min"] 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}/canales", "valueInteger": int(eeg["canales"])} if eeg["canales"] is not None else None,
) if e]
if eeg["valido"] != 1:
report["conclusion"] = "EEG de mala calidad: no es válido para el estudio."
return [procedure, tagged(report, simulated), *quality, *altered]
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."""
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 (("SA", "Afecto social"), ("RRB", "Comportamiento restringido y repetitivo")):
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 first ADOS-2 and the EEG the study uses, as of today."""
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)
resources += [ados2] if ados2 else []
(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)))
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)
return {"resourceType": "Bundle", "type": "collection", "entry": [{"resource": r} for r in resources]}