"""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 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 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" 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"))) 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"))) 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"))) 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 metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict], pseudonym: str, simulated: bool) -> 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.""" 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']}"}] 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] = ()) -> 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, list(checks), 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["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["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["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 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 screening episode (with its age group), 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)), _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) return {"resourceType": "Bundle", "type": "collection", "entry": [{"resource": r} for r in resources]}