ba81ab811f
01a: fechas clínicas, disponibilidad en origen y referencia por campo; evidencia FHIR independiente. 01b (parcial): proyección de elegibilidad por instancia y lector con comprobación del esquema gold. Pendiente: las exclusiones propias de cada escenario conservan solo el motivo prioritario; fechas FHIR parciales o sin zona, estados de resultado y actualización desde instalaciones anteriores. Ver PLAN_CONTEXTO_CACU.md.
293 lines
12 KiB
Python
293 lines
12 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
|
|
import json
|
|
from collections.abc import Iterable
|
|
from datetime import UTC, date, datetime
|
|
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 FIELD_EVIDENCE, RECORD
|
|
from core.schema import IDENTIFIER_SYSTEMS
|
|
|
|
STUDY = CODES + "study"
|
|
FIELD = CODES + "catalog-field"
|
|
EVIDENCE = "cacu_eligibility_evidence"
|
|
FINAL_RESULTS = {"final", "amended", "corrected"}
|
|
|
|
|
|
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 combined(bundles: Iterable[dict]) -> dict:
|
|
"""Latest resources for one sender, with Bundle-local references made canonical."""
|
|
def reference(item: dict, named: dict) -> dict:
|
|
target = named.get(item.get("reference"))
|
|
if target is None:
|
|
return item
|
|
return {**item, "reference": f"{target['resourceType']}/{target['id']}"}
|
|
|
|
latest = {}
|
|
for bundle in bundles:
|
|
named = _entries(bundle)
|
|
for ref, resource in resources(bundle).items():
|
|
resource = resource.copy()
|
|
for field in ("subject", "encounter"):
|
|
if resource.get(field):
|
|
resource[field] = reference(resource[field], named)
|
|
if resource["resourceType"] == "DiagnosticReport" and resource.get("result"):
|
|
resource["result"] = [reference(item, named) for item in resource["result"]]
|
|
latest[ref] = resource
|
|
return {"entry": [{"resource": resource} for resource in latest.values()]}
|
|
|
|
|
|
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 _source_time(value: str | None) -> str | None:
|
|
"""Keep a full source date or normalize a timezone-qualified timestamp to UTC."""
|
|
if not value:
|
|
return None
|
|
try:
|
|
if len(value) == 10:
|
|
return date.fromisoformat(value).isoformat()
|
|
stamp = datetime.fromisoformat(value)
|
|
if stamp.tzinfo is not None:
|
|
return stamp.astimezone(UTC).isoformat(timespec="microseconds")
|
|
except ValueError:
|
|
pass
|
|
return None
|
|
|
|
|
|
def _clinical_day(value: str | None) -> str | None:
|
|
if value and _source_time(value):
|
|
return value[:10]
|
|
return None
|
|
|
|
|
|
def _evidence(ref: str, clinical: str | None, available: str | None) -> dict:
|
|
return {
|
|
"source_ref": ref,
|
|
"source_clinical_date": _clinical_day(clinical),
|
|
"source_available_at": _source_time(available),
|
|
}
|
|
|
|
|
|
def _report_observations(sent: dict, named: dict) -> set[str]:
|
|
return {
|
|
o["id"]
|
|
for r in sent.values() if r["resourceType"] == "DiagnosticReport"
|
|
for item in r.get("result", [])
|
|
if (o := named.get(item.get("reference", ""))) is not None
|
|
and o["resourceType"] == "Observation"
|
|
}
|
|
|
|
|
|
def _standalone_evidence(sent: dict, named: dict, sender: str, maps) -> list[dict]:
|
|
linked = _report_observations(sent, named)
|
|
exams = catalog.studies()["cervical_cytology"].fields["gynecologic_condition"]
|
|
icd10 = catalog.systems()["icd-10"].url
|
|
out = []
|
|
for ref, r in sent.items():
|
|
kind = r["resourceType"]
|
|
if kind == "Condition":
|
|
verification = _codings(r.get("verificationStatus"))
|
|
if verification and not any(c.get("code") == "confirmed" for c in verification):
|
|
continue
|
|
codes = (_translated(maps, c, icd10) for c in _codings(r.get("code")))
|
|
value = next((code for code in codes if code), None)
|
|
clinical = r.get("onsetDateTime") or (r.get("onsetPeriod") or {}).get("end")
|
|
available = r.get("recordedDate")
|
|
event = "condition"
|
|
elif kind == "Observation":
|
|
if (r["id"] in linked or r.get("encounter")
|
|
or r.get("status") not in FINAL_RESULTS):
|
|
continue
|
|
if not any(_translated(maps, c, FIELD) == "cervical_cytology.gynecologic_condition"
|
|
for c in _codings(r.get("code"))):
|
|
continue
|
|
value = _value(r, exams, maps)
|
|
if value not in exams.codes:
|
|
continue
|
|
clinical = (r.get("effectiveDateTime") or r.get("effectiveInstant")
|
|
or (r.get("effectivePeriod") or {}).get("end"))
|
|
available = r.get("issued")
|
|
event = "gynecologic_condition"
|
|
else:
|
|
continue
|
|
if value:
|
|
evidence = _evidence(f"{sender}|{ref}", clinical, available)
|
|
out.append({
|
|
RECORD: record(sender, ref),
|
|
"evidence_id": evidence["source_ref"],
|
|
"evidence_date": evidence["source_clinical_date"],
|
|
"evidence_type": event,
|
|
"evidence_code": value,
|
|
FIELD_EVIDENCE: json.dumps({"evidence_code": evidence}),
|
|
})
|
|
return out
|
|
|
|
|
|
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
|
|
linked = _report_observations(sent, named)
|
|
for ref, r in sent.items():
|
|
kind = r["resourceType"]
|
|
standalone = kind == "Observation" and r["id"] not in linked and not r.get("encounter")
|
|
if (standalone or kind in ("DiagnosticReport", "Encounter", "Condition")) 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
|
|
if entity == EVIDENCE:
|
|
return _standalone_evidence(sent, named, sender, maps)
|
|
|
|
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)}
|
|
if kind == "DiagnosticReport":
|
|
start = r.get("effectiveDateTime") or (r.get("effectivePeriod") or {}).get("start")
|
|
else:
|
|
start = (r.get("period") or {}).get("start")
|
|
if start:
|
|
row[root.date] = start[:10]
|
|
release = None
|
|
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 r.get("status") in FINAL_RESULTS | {"appended"}:
|
|
release = r.get("issued") or reported
|
|
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
|
|
evidence = {}
|
|
for o in filter(None, results):
|
|
if o.get("resourceType") != "Observation":
|
|
continue
|
|
if o.get("subject") and subject(o) is not subject(r):
|
|
continue
|
|
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)
|
|
clinical = (o.get("effectiveDateTime") or o.get("effectiveInstant")
|
|
or (o.get("effectivePeriod") or {}).get("end") or start)
|
|
available = (o.get("issued") or release
|
|
if o.get("status") in FINAL_RESULTS else None)
|
|
evidence[field] = _evidence(f"{sender}|Observation/{o['id']}", clinical,
|
|
available)
|
|
break
|
|
if evidence:
|
|
row[FIELD_EVIDENCE] = json.dumps(evidence)
|
|
out.append(row)
|
|
return out
|