158 lines
7.0 KiB
Python
158 lines
7.0 KiB
Python
"""FHIR in: what a standard hospital sends (R4 Bundles), as the rows a pipeline's link and
|
|
target nodes take, the same rows a site's map and extract nodes give. One silver,
|
|
two doors.
|
|
|
|
A record is one resource the hospital sent: a Patient, and each DiagnosticReport or
|
|
Encounter (one study instance). Every report also gives an identity row, its subject's, so
|
|
the link node joins it to its person the way it joins any document: by identifiers, name and
|
|
birth date. Codes in the platform's own systems pass as they are; any other code goes through
|
|
the sender's ConceptMaps (core.concept_map), and one no map knows is kept as sent, so the
|
|
target holds the row saying why.
|
|
"""
|
|
|
|
import hashlib
|
|
from collections.abc import Iterable
|
|
from typing import Any
|
|
|
|
from fhir.resources.R4B.conceptmap import ConceptMap
|
|
|
|
from core import catalog, concept_map
|
|
from core.fhir import CODES
|
|
from core.pipeline import RECORD
|
|
from core.schema import IDENTIFIER_SYSTEMS
|
|
|
|
STUDY = CODES + "study"
|
|
FIELD = CODES + "catalog-field"
|
|
|
|
|
|
def record(sender: str, reference: str) -> str:
|
|
"""A sent resource's record id: stable across resends of the same resource."""
|
|
return hashlib.sha256(f"{sender}|{reference}".encode()).hexdigest()
|
|
|
|
|
|
def resources(bundle: dict) -> dict[str, dict]:
|
|
"""The Bundle's resources by `Type/id`: what its references name, whether they use that
|
|
form or the entry's `fullUrl` (`urn:uuid:...`, as transaction Bundles do)."""
|
|
return {f"{r['resourceType']}/{r['id']}": r for r in _entries(bundle).values()}
|
|
|
|
|
|
def _entries(bundle: dict) -> dict[str, dict]:
|
|
"""Every resource under each name a reference may use: `Type/id` and its fullUrl."""
|
|
found = {}
|
|
for entry in bundle.get("entry", []):
|
|
r = entry.get("resource") or {}
|
|
if r.get("resourceType") and r.get("id"):
|
|
found[f"{r['resourceType']}/{r['id']}"] = r
|
|
if entry.get("fullUrl"):
|
|
found[entry["fullUrl"]] = r
|
|
return found
|
|
|
|
|
|
def _translated(maps: Iterable[ConceptMap], coding: dict, system: str) -> str | None:
|
|
"""A coding as a code of `system`: as it is when already there, else through the maps."""
|
|
if coding.get("system") == system:
|
|
return coding.get("code")
|
|
found = concept_map.translate(maps, coding.get("system", ""), coding.get("code", ""))
|
|
return found[1] if found and found[0] == system else None
|
|
|
|
|
|
def _codings(concept: dict | None) -> list[dict]:
|
|
return (concept or {}).get("coding", [])
|
|
|
|
|
|
def identity(patient: dict) -> dict[str, Any]:
|
|
"""What a Patient says about whom she is: identifiers by system, name, birth date, sex."""
|
|
found: dict[str, Any] = {}
|
|
by_system = {v: k for k, v in IDENTIFIER_SYSTEMS.items()}
|
|
for i in patient.get("identifier", []):
|
|
field = by_system.get(i.get("system"), "record_number")
|
|
found.setdefault(field, i.get("value"))
|
|
if names := patient.get("name"):
|
|
name = names[0]
|
|
found["full_name"] = name.get("text") or " ".join(
|
|
[*name.get("given", []), *([name["family"]] if name.get("family") else [])]
|
|
)
|
|
if patient.get("birthDate"):
|
|
found["birth_date"] = patient["birthDate"]
|
|
if patient.get("gender") in ("female", "male"):
|
|
found["sex"] = patient["gender"]
|
|
return found
|
|
|
|
|
|
def _value(observation: dict, f: catalog.FieldDef, maps) -> Any:
|
|
if "valueCodeableConcept" in observation:
|
|
codings = _codings(observation["valueCodeableConcept"])
|
|
url = catalog.systems()[f.system].url if f.system else None
|
|
for coding in codings:
|
|
if url and (code := _translated(maps, coding, url)) is not None:
|
|
return code
|
|
return codings[0].get("code") if codings else None # kept as sent: held, saying why
|
|
for key in ("valueBoolean", "valueString", "valueInteger"):
|
|
if key in observation:
|
|
return observation[key]
|
|
if "valueQuantity" in observation:
|
|
return observation["valueQuantity"].get("value")
|
|
if "valueDateTime" in observation:
|
|
return observation["valueDateTime"][:10]
|
|
return None
|
|
|
|
|
|
def rows(bundle: dict, entity: str, sender: str, maps: Iterable[ConceptMap] = ()) -> list[dict]:
|
|
"""The Bundle's rows of one entity: `identity` (each Patient, and each report's
|
|
subject), `death` (Patients who died), or a study of the catalog (each report or
|
|
encounter of it, with its results as fields)."""
|
|
maps = list(maps)
|
|
sent = resources(bundle)
|
|
named = _entries(bundle) # what a reference may name
|
|
|
|
def subject(r: dict) -> dict | None:
|
|
return named.get((r.get("subject") or {}).get("reference", ""))
|
|
|
|
if entity == "identity":
|
|
out = [{**identity(r), RECORD: record(sender, ref)}
|
|
for ref, r in sent.items() if r["resourceType"] == "Patient"] # fmt: skip
|
|
for ref, r in sent.items():
|
|
if r["resourceType"] in ("DiagnosticReport", "Encounter") and (p := subject(r)):
|
|
out.append({**identity(p), RECORD: record(sender, ref)})
|
|
return out
|
|
if entity == "death":
|
|
return [{"death_date": r["deceasedDateTime"][:10], RECORD: record(sender, ref)}
|
|
for ref, r in sent.items()
|
|
if r["resourceType"] == "Patient" and r.get("deceasedDateTime")] # fmt: skip
|
|
|
|
spec = catalog.studies()[entity]
|
|
kind = "DiagnosticReport" if "report" in spec.events else "Encounter"
|
|
root = next(e for e in spec.events.values() if e.parent is None)
|
|
out = []
|
|
for ref, r in sent.items():
|
|
if r["resourceType"] != kind:
|
|
continue
|
|
code = r.get("code") if kind == "DiagnosticReport" else (r.get("type") or [None])[0]
|
|
if not any(_translated(maps, c, STUDY) == entity for c in _codings(code)):
|
|
continue
|
|
row: dict[str, Any] = {RECORD: record(sender, ref)}
|
|
start = r.get("effectiveDateTime") if kind == "DiagnosticReport" else (
|
|
(r.get("period") or {}).get("start")) # fmt: skip
|
|
if start:
|
|
row[root.date] = start[:10]
|
|
if kind == "DiagnosticReport":
|
|
reported = next((x.get("valueDate") for x in r.get("extension", [])
|
|
if x.get("url", "").endswith("/report-date")), None) # fmt: skip
|
|
reported = reported or (r.get("issued") or "")[:10] or None
|
|
if reported:
|
|
row[spec.events["report"].date] = reported
|
|
results = [named.get(x.get("reference", "")) for x in r.get("result", [])]
|
|
else:
|
|
mine = {ref, *(k for k, v in named.items() if v is r)}
|
|
results = [o for o in sent.values() if o["resourceType"] == "Observation"
|
|
and (o.get("encounter") or {}).get("reference") in mine] # fmt: skip
|
|
for o in filter(None, results):
|
|
for coding in _codings(o.get("code")):
|
|
name = _translated(maps, coding, FIELD) or ""
|
|
study, _, field = name.partition(".")
|
|
if study == entity and field in spec.fields:
|
|
row[field] = _value(o, spec.fields[field], maps)
|
|
break
|
|
out.append(row)
|
|
return out
|