FHIR out from the catalog, the FHIR door, ConceptMap routes; round-trip, new-label and Synthea gates

This commit is contained in:
Roberto Treviño
2026-11-25 16:17:23 -06:00
parent 0dd5c035bc
commit 806302ee5d
8 changed files with 441 additions and 47 deletions
+126 -27
View File
@@ -4,21 +4,27 @@ built by Core's mappers from the rows Persistance reads; nothing is computed her
counting a few thousand rows (measures) and ordering the follow-up list."""
from datetime import date, datetime
from typing import Annotated, Any
from fastapi import APIRouter, HTTPException, Query, Request
from dagster_graphql import DagsterGraphQLClient
from fastapi import APIRouter, Body, Depends, HTTPException, Query, Request
from fastapi.responses import Response
from fhir.resources.R4B.bundle import Bundle
from fhir.resources.R4B.capabilitystatement import CapabilityStatement
from fhir.resources.R4B.operationoutcome import OperationOutcome
from fhir.resources.R4B.resource import Resource
from core import cacu
from core import cacu, catalog
from core import fhir as f
from core import follow_up as fu
from core import measures as m
from core.domains import Domain
from core.pipeline import ID_PATTERN
from persistance import config_log, readers
from persistance import fhir as reads
from persistance import measures as measure_reads
from webapi.ingest import submit
from webapi.runs import dagster
FHIR_JSON = "application/fhir+json"
MEASURES = {Domain.CACU: m.MEASURES}
@@ -94,8 +100,29 @@ def read_patient(domain: Domain, id: str) -> Response:
_clinical(domain)
(row,) = reads.rows("person", id=id) or [None]
if row is None:
raise HTTPException(404, f"no Patient/{id}")
return fhir(f.patient({**row, "status": fu.status(row, _cutoff(None))}))
(link,) = reads.rows("replaced", id=id) or [None]
if link is None:
raise HTTPException(404, f"no Patient/{id}")
return fhir(f.replaced_patient(id, link["replaced_by"]))
(found,) = _with_identity([{**row, "status": fu.status(row, _cutoff(None))}])
return fhir(f.patient(found))
def _with_identity(rows: list[dict]) -> list[dict]:
"""Persons with their names, identifiers and the ids they replaced."""
persons = [r["person_id"] for r in rows]
names, ids, replaces = {}, {}, {}
for r in reads.rows("names", persons=persons):
names.setdefault(r["person_id"], []).append(r["text"])
for r in reads.rows("identifiers", persons=persons):
ids.setdefault(r["person_id"], []).append((r["system"], r["value"]))
for r in reads.rows("replaces", persons=persons):
replaces.setdefault(r["replaced_by"], []).append(r["person_id"])
return [
{**r, "names": names.get(p, []), "identifiers": ids.get(p, []),
"replaces": replaces.get(p, [])}
for r in rows if (p := r["person_id"])
] # fmt: skip
@router.get("/Patient", responses=_OK, response_class=Response)
@@ -148,15 +175,16 @@ def search_patient(
rows = fu.ordered(rows, sort, risks, horizon)
page = _sliced(rows, count, offset)
mine = {r["person_id"] for r in page}
included = _included(revinclude, include, sorted(mine), at,
included = _included(domain, revinclude, include, sorted(mine), at,
{p: v for p, v in risks.items() if p in mine}) # fmt: skip
applied = {"follow-up-cutoff": at.isoformat()} if window is not None else None
return bundle(request, [f.patient(r) for r in page], len(rows), count, offset, included,
patients = [f.patient(r) for r in _with_identity(page)]
return bundle(request, patients, len(rows), count, offset, included,
applied) # fmt: skip
def _included(revinclude: list[str], include: list[str], persons: list[str], at: date,
risks: dict[str, list[dict]]) -> list[Resource]: # fmt: skip
def _included(domain: Domain, revinclude: list[str], include: list[str], persons: list[str],
at: date, risks: dict[str, list[dict]]) -> list[Resource]: # fmt: skip
unknown = set(revinclude) - set(REVINCLUDES) | set(include) - {"DiagnosticReport:result"}
if unknown:
raise HTTPException(422, f"cannot include {sorted(unknown)}")
@@ -166,12 +194,10 @@ def _included(revinclude: list[str], include: list[str], persons: list[str], at:
reports and "DiagnosticReport:result" in include
)
if reports or observations:
for row in reads.rows("cytology", persons=persons, cutoff=at.isoformat()):
report, *results = f.cytology(row)
found += ([report] if reports else []) + (results if observations else [])
if reports:
found += [f.biopsy(r) for r in reads.rows("biopsy", persons=persons,
cutoff=at.isoformat())] # fmt: skip
for r in _studies(domain, persons, at.isoformat()):
kind = r.get_resource_type()
if (kind == "DiagnosticReport" and reports) or (kind == "Observation" and observations):
found.append(r)
if "RiskAssessment:subject" in revinclude:
found += _risk_assessments([r for p in persons for r in risks.get(p, [])])
return found
@@ -186,6 +212,28 @@ def _subjects(subject: str | None) -> list[str]:
return [s.removeprefix("Patient/") for s in subject.split(",")]
# Facts gold adds to a study's report (CaCu: days from the sample to its diagnosis).
REPORT_FACTS = {"cervical_cytology": "diagnosis_days"}
def _studies(domain: Domain, persons: list[str], at: str) -> list[Resource]:
"""Every instance of the domain's studies (the catalog's) for these persons, as known
by `at`: its DiagnosticReport (or Encounter) and Observations, in date order."""
found: list[Resource] = []
for study in catalog.of_domain(domain.value):
spec = catalog.studies()[study]
facts = {}
if kind := REPORT_FACTS.get(study):
facts = {(r["person_id"], str(r["sample_date"])[:10]): r["days"]
for r in reads.rows(kind, persons=persons, cutoff=at)} # fmt: skip
first = next(e.date for e in spec.events.values() if e.parent is None)
for row in reads.instances(study, persons, at):
days = facts.get((row["person_id"], str(row[first])[:10]))
extra = [] if days is None else [f.ext("days-to-diagnosis", "integer", int(days))]
found += f.instance(study, f.known(study, row, at), extra)
return found
def _risk_assessments(rows: list[dict]) -> list[Resource]:
groups: dict[tuple, list[dict]] = {}
for r in rows:
@@ -212,27 +260,35 @@ def search_diagnostic_report(request: Request, domain: Domain,
subject: str | None = Query(None, description=SUBJECT),
_count: int | None = Query(None),
_offset: int = Query(0)) -> Response: # fmt: skip
"""Cervical cytologies and biopsies, as known by the last day with data."""
"""The domain's reports (each study of the catalog with a report), as known by the last
day with data."""
return _study_search("DiagnosticReport", request, domain, subject, _count, _offset)
def _study_search(kind: str, request, domain, subject, count, offset) -> Response:
_clinical(domain)
count, offset = _page(_count, _offset)
count, offset = _page(count, offset)
persons, at = _subjects(subject), _cutoff(None).isoformat()
found = [f.cytology(r)[0] for r in reads.rows("cytology", persons=persons, cutoff=at)]
found += [f.biopsy(r) for r in reads.rows("biopsy", persons=persons, cutoff=at)]
found.sort(key=lambda r: (str(r.effectiveDateTime), r.code.coding[0].code))
found = [r for r in _studies(domain, persons, at) if r.get_resource_type() == kind]
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
@router.get("/Encounter", responses=_OK, response_class=Response)
def search_encounter(request: Request, domain: Domain,
subject: str | None = Query(None, description=SUBJECT),
_count: int | None = Query(None),
_offset: int = Query(0)) -> Response: # fmt: skip
"""Consultations: each study of the catalog without a report, as an encounter."""
return _study_search("Encounter", request, domain, subject, _count, _offset)
@router.get("/Observation", responses=_OK, response_class=Response)
def search_observation(request: Request, domain: Domain,
subject: str | None = Query(None, description=SUBJECT),
_count: int | None = Query(None),
_offset: int = Query(0)) -> Response: # fmt: skip
"""The results of cervical cytologies (Bethesda, adequacy, HPV)."""
def build(rows):
return [o for r in rows for o in f.cytology(r)[1:]]
return _clinical_search("cytology", build, request, domain, subject, _count, _offset)
"""Every result of the domain's reports, one per field of the catalog."""
return _study_search("Observation", request, domain, subject, _count, _offset)
@router.get("/Condition", responses=_OK, response_class=Response)
@@ -331,6 +387,42 @@ def search_measure_report(
return bundle(request, reports, len(asked), count, offset)
# --- the FHIR door: what a standard hospital sends -----------------------------------------
@router.post("", responses=_OK, response_class=Response, status_code=202)
def post_bundle(
domain: Domain,
bundle: Annotated[dict[str, Any], Body(description="a FHIR R4 batch or transaction Bundle")],
sender: str = Query(
pattern=ID_PATTERN,
max_length=40,
description="the sender's pipeline (its fhir nodes read this inbox)",
),
client: DagsterGraphQLClient = Depends(dagster),
) -> Response:
"""A standard hospital's Bundle: checked as FHIR, kept as sent in the sender's inbox,
and placed by the sender's pipeline (a run starts; follow it at the Location)."""
try:
parsed = Bundle.model_validate(bundle)
except ValueError as e:
raise HTTPException(422, f"not a valid R4 Bundle: {e}") from e
if parsed.type not in ("batch", "transaction", "collection"):
raise HTTPException(422, "send a batch, transaction or collection Bundle")
if not config_log.latest_version(sender):
raise HTTPException(404, f"no pipeline {sender} to place what it sends")
readers.receive(sender, bundle)
run_id = submit(client, sender)
entries = [{"response": {"status": "202 Accepted", "location":
f"{e.resource.get_resource_type()}/{e.resource.id}"}}
for e in parsed.entry or [] if e.resource is not None] # fmt: skip
answer = Bundle(type="batch-response", entry=entries or None)
found = fhir(answer)
found.status_code = 202
found.headers["Location"] = f"/runs/{run_id}"
return found
# --- CapabilityStatement ----------------------------------------------------------------------
@@ -338,8 +430,14 @@ def search_measure_report(
def metadata(request: Request, domain: Domain) -> Response:
"""What this base serves: built from the routes above, so it cannot drift from them."""
resources: dict[str, dict] = {}
system: list[dict] = []
for route in router.routes:
_, kind, *rest = route.path.removeprefix(router.prefix).split("/")
path = route.path.removeprefix(router.prefix)
if not path: # the base itself: the FHIR door
if domain in CLINICAL:
system = [{"code": "batch"}, {"code": "transaction"}]
continue
_, kind, *rest = path.split("/")
if kind == "metadata" or (kind != "Measure" and kind != "MeasureReport"
and domain not in CLINICAL): # fmt: skip
continue
@@ -368,7 +466,8 @@ def metadata(request: Request, domain: Domain) -> Response:
"implementation": {"description": f"ISSSTELEON {domain.value}",
"url": str(request.base_url).rstrip("/") + f"/{domain.value}/fhir"},
"rest": [{"mode": "server",
"resource": [{k: v for k, v in r.items() if v} for r in resources.values()]}],
"resource": [{k: v for k, v in r.items() if v} for r in resources.values()],
**({"interaction": system} if system else {})}],
}) # fmt: skip
return fhir(statement)