diff --git a/tests/fhir_checks.py b/tests/fhir_checks.py new file mode 100644 index 0000000..bb5632e --- /dev/null +++ b/tests/fhir_checks.py @@ -0,0 +1,151 @@ +"""What the FHIR gate checks with: every resource the API serves, the HL7 validator over +them, and the follow-up list read the way the WebApp reads it.""" + +import json +import os +import subprocess +from pathlib import Path + +from core import fhir + +VALIDATOR = os.environ.get("FHIR_VALIDATOR_JAR", "/opt/fhir/validator_cli.jar") +PAGES = 100 # a search with more pages than this is a paging bug +E = fhir.EXTENSION + + +def pages(api, path: str, params=None) -> list[dict]: + """Every page of a search, following `next` to the end.""" + found, url = [], path + for _ in range(PAGES): + response = api.get(url, params=params) + assert response.status_code == 200, response.text + assert response.headers["content-type"].startswith("application/fhir+json") + found.append(bundle := response.json()) + url = next((x["url"] for x in bundle["link"] if x["relation"] == "next"), None) + params = None # the next link carries the query + if url is None: + return found + raise AssertionError(f"{path}: more than {PAGES} pages") + + +def served(api, base: str, periods: list[str], patients: list[str]) -> list[dict]: + """Every kind of resource the base serves, each search paged to the end: metadata, + the measures and their reports, the follow-up list with what it includes, a read of + each patient, and each clinical search for them.""" + found = [api.get(f"{base}/metadata").json()] + found += pages(api, f"{base}/Measure") + for measure in [e["resource"]["id"] for b in found[1:] for e in b["entry"]]: + found += pages(api, f"{base}/MeasureReport", + {"measure": measure, "reporting-period": ",".join(periods)}) # fmt: skip + found += pages(api, f"{base}/Patient", [ + ("follow-up-window", 12), ("_count", 25), ("_revinclude", "DiagnosticReport:subject"), + ("_revinclude", "RiskAssessment:subject"), ("_include:iterate", "DiagnosticReport:result"), + ]) # fmt: skip + found += [api.get(f"{base}/Patient/{p}").json() for p in patients] + for kind in ("DiagnosticReport", "Observation", "Condition", "Procedure", "RiskAssessment"): + found += pages(api, f"{base}/{kind}", {"subject": ",".join(patients), "_count": 40}) + return found + + +def validate(resources: list[dict], folder: Path) -> tuple[list[dict], list[dict]]: + """The HL7 validator (offline: no terminology server) over the resources, with our + conformance resources loaded: its errors and its warnings.""" + data, ig = folder / "served", folder / "ig" + data.mkdir() + ig.mkdir() + for i, resource in enumerate(resources): + (data / f"{i:05d}.json").write_text(json.dumps(resource)) + for resource in fhir.conformance(): + (ig / f"{resource.get_resource_type()}-{resource.id}.json").write_text( + resource.model_dump_json(exclude_none=True)) # fmt: skip + out = folder / "outcome.json" + subprocess.run(["java", "-jar", VALIDATOR, str(data), str(ig), "-version", fhir.FHIR_VERSION, + "-tx", "n/a", "-ig", str(ig), "-output", str(out)], + check=False, capture_output=True) # fmt: skip + outcome = json.loads(out.read_text()) + outcomes = [e["resource"] for e in outcome.get("entry", [])] or [outcome] + issues = [i for o in outcomes for i in o.get("issue", [])] + errors = [i for i in issues if i["severity"] in ("error", "fatal")] + return errors, [i for i in issues if i["severity"] == "warning"] + + +SCORE_REQUIRED = "A measureScore is required when the Measure.scoring=" + + +def unscored(issue: dict, resources: list[dict]) -> bool: + """The validator's one allowed error: a summary report of a period with nothing to + score (no denominator, nothing measured) has no score, since the rate or median is + undefined. FHIR's validator asks for one anyway.""" + text = issue.get("details", {}).get("text", "") + where = " ".join(issue.get("expression", [])) + if not text.startswith(SCORE_REQUIRED) or "/*MeasureReport/" not in where: + return False + report_id = where.split("/*MeasureReport/")[1].split("*/")[0] + everything = [r for b in resources for r in [b, *(e["resource"] for e in b.get("entry", []))]] + reports = [r for r in everything if r.get("id") == report_id + and r.get("resourceType") == "MeasureReport"] # fmt: skip + counts = {p["code"]["coding"][0]["code"]: p["count"] + for r in reports for p in r["group"][0]["population"]} # fmt: skip + nothing = counts.get("denominator", counts.get("measure-observation")) == 0 + scored = any("measureScore" in r["group"][0] for r in reports) + return bool(reports) and nothing and not scored + + +def _ext(resource: dict, name: str) -> dict | None: + return next((x for x in resource.get("extension", []) if x["url"] == E + name), None) + + +def _code(concept: dict) -> str: + return concept["coding"][0]["code"] + + +def follow_up(bundles: list[dict], start: str, cutoff: str) -> list[dict]: + """The follow-up list as the WebApp shows it, in order: per patient, her status, her + latest cytology and HPV sampled in the window, her days to diagnosis, and her latest + reported biopsy.""" + included = {(e["resource"]["resourceType"], e["resource"]["id"]): e["resource"] + for b in bundles for e in b.get("entry", [])} # fmt: skip + rows = [] + for b in bundles: + for patient in (e["resource"] for e in b.get("entry", []) + if e["search"]["mode"] == "match"): # fmt: skip + reports = [r for (kind, _), r in included.items() if kind == "DiagnosticReport" + and r["subject"]["reference"] == f"Patient/{patient['id']}"] # fmt: skip + + def results(report: dict) -> dict: + return {_code(o["code"]): o for o in ( + included[("Observation", x["reference"].split("/")[1])] + for x in report.get("result", []))} # fmt: skip + + cytologies = sorted( + (r for r in reports if _code(r["code"]) == "cervical-cytology" + and start <= r["effectiveDateTime"] <= cutoff), + key=lambda r: r["effectiveDateTime"]) # fmt: skip + hpv = [r for r in cytologies if "hpv" in results(r)] + biopsies = sorted((r for r in reports if _code(r["code"]) == "cervical-biopsy" + and _ext(r, "report-date")), + key=lambda r: _ext(r, "report-date")["valueDate"]) # fmt: skip + status = _ext(patient, "follow-up-status")["valueCoding"]["code"] + row = {"person": patient["id"], "status": status, "cytology": None, "hpv": None, + "days_to_diagnosis": None, "biopsy": None} # fmt: skip + if cytologies: + last, found = cytologies[-1], results(cytologies[-1]) + row["cytology"] = {"date": last["effectiveDateTime"], **{ + k: _code(found[c]["valueCodeableConcept"]) if c in found else None + for k, c in (("result", "cytology-result"), + ("adequacy", "cytology-adequacy"))}} # fmt: skip + days = _ext(last, "days-to-diagnosis") + row["days_to_diagnosis"] = days and days["valueInteger"] + if hpv: + found = results(hpv[-1]) + types = [found[k]["valueBoolean"] for k in ("hpv-16", "hpv-18") if k in found] + row["hpv"] = {"date": hpv[-1]["effectiveDateTime"], + "positive": found["hpv"]["valueBoolean"], + "types_16_18": any(types) if types else None} # fmt: skip + if biopsies: + last = biopsies[-1] + row["biopsy"] = {"date": _ext(last, "report-date")["valueDate"], + "histology": _code(last["conclusionCode"][0]) + if last.get("conclusionCode") else None} # fmt: skip + rows.append(row) + return rows diff --git a/tests/test_cacu.py b/tests/test_cacu.py index de463e7..1b25821 100644 --- a/tests/test_cacu.py +++ b/tests/test_cacu.py @@ -3,10 +3,19 @@ the current platform gives on the same hospital (the reference fixtures): its co indicators, and, trained by the platform's own jobs, its models' predictions. Promotion needs the three reports. Real API, Dagster and MLflow; nothing faked. +Phase 3 adds the FHIR gate: every resource the API serves passes the HL7 validator, and +the follow-up list is the current platform's. + Fixed on purpose, so compared differently: - cin2_pim_post_colposcopy scores each patient at her post-colposcopy index; the current one scores at her first event (its cohort's index), so only its members are compared. - cin2_logistic's index date is the index sample's, not 1970-01-01. +- One rule, one value: a diagnosis note assesses a sample within SAMPLE_TO_DIAGNOSIS_DAYS + (120). The current follow-up status reads the same rule as 180 days, so one patient + (198) is post-colposcopy there and pre-colposcopy here. +- FHIR asks every summary report for a score: a composition scores its count. A period + with nothing measured keeps its counts and has no score, the validator's one allowed + error (see fhir_checks.unscored). """ import json @@ -16,6 +25,7 @@ from pathlib import Path import numpy as np import pandas as pd import pytest +from fhir_checks import follow_up, pages, served, unscored, validate from test_conectar import ok, wait_for ROOT = Path(__file__).parents[2] @@ -34,7 +44,8 @@ CODES = { # platform code -> the current platform's "NILM": "NORMAL", "LSIL": "LIEBG", "HSIL": "LIEAG", "carcinoma": "CARCINOMA", "normal": "NORMAL", "no_data": "SIN_DATO", "no_biopsy": "SIN_BIOPSIA", "post_treatment": "POST_TRATAMIENTO", "post_colposcopy": "POST_COLPOSCOPIA", - "pre_colposcopy": "PRE_COLPOSCOPIA", + "pre_colposcopy": "PRE_COLPOSCOPIA", "case": "CASO", "satisfactory": "SATISFACTORIO", + "unsatisfactory": "INSATISFACTORIO", } # fmt: skip STRATA = {"age_group": "grupo_edad", "follow_up_status": "estatus_seguimiento", "result": "citologia_alto_grado"} # fmt: skip @@ -57,7 +68,8 @@ def _report(entry: dict, measure: str) -> tuple: extensions = {e["url"].rsplit("/", 1)[1]: e["valueDecimal"] for e in score.get("extension", [])} strata = {} for s in group.get("stratifier", []): - name = s["code"][0]["text"] + code = s["code"][0] + name = code["coding"][0]["code"] if "coding" in code else code["text"] name = CATEGORY.get(measure, "banda") if name == "category" else STRATA.get(name, name) strata[name] = {CODES.get(x["value"]["text"], x["value"]["text"]): { p["code"]["coding"][0]["code"]: p["count"] for p in x["population"]} @@ -65,7 +77,7 @@ def _report(entry: dict, measure: str) -> tuple: return populations, score.get("value"), extensions, {k: v for k, v in strata.items() if v} -def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform): +def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path): pipeline = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL))) ok(api.put("/ingest/pipelines/cacu", json=pipeline)) wait_for(api, ok(api.post("/ingest/pipelines/cacu/runs", json={}))["run_id"]) @@ -88,13 +100,20 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform): # Indicators: every measure, every semester, as the current platform answers them # (no risk batch yet, so the risk bands are empty as they were). reference = json.loads((REFERENCE / "indicators.json").read_text()) - for measure in ok(api.get("/cacu/measures")): - params = {"periods": ",".join(PERIODS), "event_cutoff": CAPTURED_ON} - found = ok(api.get(f"/cacu/measures/{measure['id']}", params=params))["entry"] - for ours, theirs in zip(found, reference[measure["id"]]["body"]["entry"], strict=True): - a, b = _report(ours, measure["id"]), _report(theirs, measure["id"]) - where = (measure["id"], ours["resource"]["period"]["start"]) + (measures,) = pages(api, "/cacu/fhir/Measure") + for measure in [e["resource"] for e in measures["entry"]]: + params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS), + "event-cutoff": CAPTURED_ON} # fmt: skip + found = [e for b in pages(api, "/cacu/fhir/MeasureReport", params) for e in b["entry"]] + cohort = measure["scoring"]["coding"][0]["code"] == "cohort" + name = measure["name"] + for ours, theirs in zip(found, reference[name]["body"]["entry"], strict=True): + a, b = _report(ours, name), _report(theirs, name) + where = (name, ours["resource"]["period"]["start"]) assert a[0] == b[0] and a[3] == b[3], where + if cohort: # scores its count; the current platform gave none + assert b[1] is None and a[1] == a[0]["initial-population"], where + continue assert (a[1] is None) == (b[1] is None), where assert b[1] is None or a[1] == pytest.approx(b[1], rel=1e-9), where assert a[2] == pytest.approx(b[2]), where @@ -140,5 +159,49 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform): np.testing.assert_allclose(both[ours].astype(float), both[theirs], rtol=1e-6) # The risk band now has the surveillance cohort's scored members. - bands = ok(api.get("/cacu/measures/CACU_RIESGO_BANDA", params={"periods": "2025-S1"})) + params = {"measure": "cacu-riesgo-banda", "reporting-period": "2025-S1"} + (bands,) = pages(api, "/cacu/fhir/MeasureReport", params) assert bands["entry"][0]["resource"]["group"][0]["population"][0]["count"] > 0 + + # The follow-up list: the current platform's, at its cut-off, with the same window. + page = json.loads((REFERENCE / "pages.json").read_text()) + theirs = page["/cacu/seguimiento?page_size=200"]["body"] + window, cutoff = theirs["ventana"], theirs["corte"] + params = [("follow-up-window", window["meses"]), ("follow-up-cutoff", cutoff), + ("_count", 20), ("_revinclude", "DiagnosticReport:subject"), + ("_include:iterate", "DiagnosticReport:result")] # fmt: skip + ours = follow_up(pages(api, "/cacu/fhir/Patient", params), window["desde"], cutoff) + assert [r["cytology"]["date"] for r in ours] == [ + i["ultima_citologia"]["fecha"] for i in theirs["items"] + ] # same order (ties aside) + expected = {int(i["pac_id"]): i for i in theirs["items"]} + assert {patient[r["person"]] for r in ours} == set(expected) + for row in ours: + cytology, hpv, biopsy = row["cytology"], row["hpv"], row["biopsy"] + shown = { + "estatus": CODES[row["status"]], + "ultima_citologia": {"fecha": cytology["date"], + "bethesda": CODES.get(cytology["result"], cytology["result"]), + "calidad": CODES.get(cytology["adequacy"])}, + "ultimo_vph": hpv and {"fecha": hpv["date"], "genotipo_16_18": hpv["types_16_18"], + "resultado": "POSITIVO" if hpv["positive"] else "NEGATIVO"}, + "dias_toma_diagnostico": row["days_to_diagnosis"], + "ultima_biopsia": biopsy and { + "fecha": biopsy["date"], + "grado": CODES.get(biopsy["histology"], biopsy["histology"]), + }, + } # fmt: skip + item = expected[patient[row["person"]]] + if patient[row["person"]] == 198: # fixed: one horizon (120 days), not 180 + assert (shown["estatus"], item["estatus"]["codigo"]) == ( + "PRE_COLPOSCOPIA", "POST_COLPOSCOPIA") # fmt: skip + shown["estatus"] = "POST_COLPOSCOPIA" + assert shown == {**{k: item[k] for k in shown}, "estatus": item["estatus"]["codigo"]} + + # Every resource the API serves, every search paged to the end, passes the HL7 + # validator (offline: structure, cardinality, profiles; no terminology server). + people = [r["person"] for r in ours[:10]] + resources = served(api, "/cacu/fhir", PERIODS, people) + errors, warnings = validate(resources, tmp_path) + print(f"HL7 validator: {len(warnings)} warnings") + assert [e for e in errors if not unscored(e, resources)] == [] diff --git a/tests/test_webapp.py b/tests/test_webapp.py new file mode 100644 index 0000000..0971138 --- /dev/null +++ b/tests/test_webapp.py @@ -0,0 +1,27 @@ +"""Phase 3 gate, the WebApp: every page loads from the new API. The platform runs as in +production (API, Dagster), loaded with the synthetic CaCu hospital and the messy site; +Playwright drives the real pages against it (WebApp/e2e).""" + +import json +import os +import subprocess +from pathlib import Path + +import pytest +from test_conectar import ok, run + +ROOT = Path(__file__).parents[2] +HOSPITAL = ROOT / "tests" / "fixtures" / "hospital" +PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_cacu.json" + + +@pytest.mark.webapp +@pytest.mark.parametrize("platform", ["sqlite"], indirect=True) # pages read one API either way +def test_every_page_loads_from_the_api(api, platform, messy_site): + hospital = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL))) + ok(api.put("/ingest/pipelines/cacu", json=hospital)) + run(api, "cacu") + ok(api.put("/ingest/pipelines/site", json=json.loads(messy_site.drawn))) + run(api, "site") + subprocess.run(["npx", "playwright", "test"], cwd=ROOT / "WebApp", check=True, + env={**os.environ, "API_URL": str(api.base_url).rstrip("/")}) # fmt: skip diff --git a/webapi/fhir.py b/webapi/fhir.py new file mode 100644 index 0000000..f8d60e6 --- /dev/null +++ b/webapi/fhir.py @@ -0,0 +1,376 @@ +"""The FHIR R4B API, one base per domain (`/{domain}/fhir`): read, the searches the WebApp +uses, paging, and a CapabilityStatement built from these routes themselves. Resources are +built by Core's mappers from the rows Persistance reads; nothing is computed here beyond +counting a few thousand rows (measures) and ordering the follow-up list.""" + +from datetime import date, datetime + +from fastapi import APIRouter, 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 fhir as f +from core import follow_up as fu +from core import measures as m +from core.domains import Domain +from persistance import fhir as reads +from persistance import measures as measure_reads + +FHIR_JSON = "application/fhir+json" +MEASURES = {Domain.CACU: m.MEASURES} +CLINICAL = {Domain.CACU} # domains whose clinical resources are served +PAGE, MAX_PAGE = 50, 200 +REVINCLUDES = ("DiagnosticReport:subject", "RiskAssessment:subject", "Observation:subject") + +router = APIRouter(prefix="/{domain}/fhir", tags=["fhir"]) +_OK = {200: {"content": {FHIR_JSON: {"schema": {"type": "object"}}}, "description": "FHIR"}} + + +def fhir(resource: Resource) -> Response: + return Response(resource.model_dump_json(exclude_none=True), media_type=FHIR_JSON) + + +def outcome(status: int, text: str) -> Response: + issue = {"severity": "error", "code": "not-found" if status == 404 else "invalid", + "diagnostics": text} # fmt: skip + return Response(OperationOutcome(issue=[issue]).model_dump_json(exclude_none=True), + status_code=status, media_type=FHIR_JSON) # fmt: skip + + +def _clinical(domain: Domain) -> None: + if domain not in CLINICAL: + raise HTTPException(404, f"no clinical resources for {domain.value} yet") + + +def _cutoff(asked: date | None) -> date: + last = reads.last_data_day() + if asked is None: + return last or date.today() + return asked if last is None else min(asked, last) + + +def _page(count: int | None, offset: int) -> tuple[int, int]: + count = PAGE if count is None else count + if not 0 <= count <= MAX_PAGE or offset < 0: + raise HTTPException(422, f"_count goes from 0 to {MAX_PAGE}; _offset from 0") + return count, offset + + +def bundle(request: Request, matches: list[Resource], total: int, count: int, offset: int, + included: list[Resource] = (), applied: dict | None = None) -> Response: # fmt: skip + """A searchset page of `matches`, with links to its neighbours. The links carry the + parameters as applied (`applied`: defaults the server chose).""" + base = str(request.base_url).rstrip("/") + request.url.path.rsplit("/", 1)[0] + + def link(relation: str, at: int) -> dict: + url = request.url.include_query_params(**(applied or {}), _offset=at, _count=count) + return {"relation": relation, "url": str(url)} + + links = [link("self", offset)] + if offset + count < total: + links.append(link("next", offset + count)) + if offset > 0: + links.append(link("previous", max(offset - count, 0))) + groups = (("match", matches), ("include", included)) + entries = [{"fullUrl": f"{base}/{r.get_resource_type()}/{r.id}", "resource": r, + "search": {"mode": mode}} for mode, group in groups for r in group] # fmt: skip + found = Bundle(type="searchset", total=total, link=links, entry=entries or None) + return fhir(found) + + +def _sliced(found: list, count: int, offset: int) -> list: + return found[offset:offset + count] # fmt: skip + + +# --- Patient --------------------------------------------------------------------------------- + + +@router.get("/Patient/{id}", responses=_OK, response_class=Response) +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))})) + + +@router.get("/Patient", responses=_OK, response_class=Response) +def search_patient( + request: Request, + domain: Domain, + _id: str | None = Query(None, alias="_id"), + window: int | None = Query( + None, + alias="follow-up-window", + description="months: whoever had a cytology sampled within them up to the cut-off", + ), + cutoff: date | None = Query( + None, alias="follow-up-cutoff", description="default: the last day with data" + ), + status: str | None = Query(None, alias="follow-up-status"), + sort: str = Query("-recent", alias="_sort", description=f"one of {fu.SORTS}; the list only"), + horizon: float = Query(fu.DEFAULT_HORIZON, alias="risk-horizon", description="years"), + revinclude: list[str] = Query([], alias="_revinclude", description=f"any of {REVINCLUDES}"), + include: list[str] = Query([], alias="_include:iterate", description="DiagnosticReport:result"), + _count: int | None = Query(None), + _offset: int = Query(0), +) -> Response: + """Patients; with `follow-up-window`, CaCu's follow-up list at the cut-off, filtered by + status and in reading order, with what the list shows of each patient included.""" + _clinical(domain) + count, offset = _page(_count, _offset) + at = _cutoff(cutoff) + if window is None: + rows = reads.rows("persons") + if _id: + rows = [r for r in rows if r["person_id"] in _id.split(",")] + else: + if window not in cacu.FOLLOW_UP_WINDOWS: + raise HTTPException(422, f"follow-up-window is one of {cacu.FOLLOW_UP_WINDOWS}") + if sort not in fu.SORTS: + raise HTTPException(422, f"_sort is one of {fu.SORTS}") + params = {"start": fu.window_start(at, window).isoformat(), "cutoff": at.isoformat()} + rows = reads.rows("follow_up", **params) + for row in rows: + row["status"] = fu.status(row, at) + if status: + rows = [r for r in rows if r["status"] in status.split(",")] + persons = [r["person_id"] for r in rows] + risks: dict[str, list[dict]] = {} + if window is not None and sort != "-recent" or "RiskAssessment:subject" in revinclude: + for r in reads.rows("risk", persons=persons): + risks.setdefault(r["person_id"], []).append(r) + if window is not None: + 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, + {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, + 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 + unknown = set(revinclude) - set(REVINCLUDES) | set(include) - {"DiagnosticReport:result"} + if unknown: + raise HTTPException(422, f"cannot include {sorted(unknown)}") + found: list[Resource] = [] + reports = "DiagnosticReport:subject" in revinclude + observations = "Observation:subject" in revinclude or ( + 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 + if "RiskAssessment:subject" in revinclude: + found += _risk_assessments([r for p in persons for r in risks.get(p, [])]) + return found + + +# --- clinical searches: by subject ---------------------------------------------------------- + + +def _subjects(subject: str | None) -> list[str]: + if not subject: + raise HTTPException(422, "subject is required (Patient/, comma-separated)") + return [s.removeprefix("Patient/") for s in subject.split(",")] + + +def _risk_assessments(rows: list[dict]) -> list[Resource]: + groups: dict[tuple, list[dict]] = {} + for r in rows: + groups.setdefault((r["model"], r["version"], r["person_id"], str(r["index_date"])), + []).append(r) # fmt: skip + return [f.risk_assessment(g[0], g) for g in groups.values()] + + +def _clinical_search(kind: str, build, request, domain, subject, count, offset): + _clinical(domain) + count, offset = _page(count, offset) + params = {"persons": _subjects(subject)} + if kind != "risk": + params["cutoff"] = _cutoff(None).isoformat() + found = build(reads.rows(kind, **params)) + return bundle(request, _sliced(found, count, offset), len(found), count, offset) + + +SUBJECT = "Patient/, comma-separated" + + +@router.get("/DiagnosticReport", responses=_OK, response_class=Response) +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.""" + _clinical(domain) + 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)) + return bundle(request, _sliced(found, count, offset), len(found), 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) + + +@router.get("/Condition", responses=_OK, response_class=Response) +def search_condition(request: Request, domain: Domain, + subject: str | None = Query(None, description=SUBJECT), + _count: int | None = Query(None), + _offset: int = Query(0)) -> Response: # fmt: skip + """What clinical notes diagnosed.""" + + def build(rows): + return [f.condition(r) for r in rows] + + return _clinical_search("condition", build, request, domain, subject, _count, _offset) + + +@router.get("/Procedure", responses=_OK, response_class=Response) +def search_procedure(request: Request, domain: Domain, + subject: str | None = Query(None, description=SUBJECT), + _count: int | None = Query(None), + _offset: int = Query(0)) -> Response: # fmt: skip + """Colposcopies and treatments, as the timeline infers them.""" + + def build(rows): + return [f.procedure(r) for r in rows] + + return _clinical_search("procedure", build, request, domain, subject, _count, _offset) + + +@router.get("/RiskAssessment", responses=_OK, response_class=Response) +def search_risk_assessment(request: Request, domain: Domain, + subject: str | None = Query(None, description=SUBJECT), + _count: int | None = Query(None), + _offset: int = Query(0)) -> Response: # fmt: skip + """The champion models' risks, one per model and index date.""" + return _clinical_search("risk", _risk_assessments, request, domain, subject, _count, _offset) + + +# --- Measure and MeasureReport ---------------------------------------------------------------- + + +def _measure(domain: Domain, key: str) -> m.Measure: + found = MEASURES.get(domain, {}) + for code, measure in found.items(): + if key in (code, f.measure_id(code), f.measure_url(code)): + return measure + raise HTTPException(404, f"no {domain.value} Measure {key}") + + +@router.get("/Measure/{id}", responses=_OK, response_class=Response) +def read_measure(domain: Domain, id: str) -> Response: + return fhir(f.measure(_measure(domain, id))) + + +@router.get("/Measure", responses=_OK, response_class=Response) +def search_measure(request: Request, domain: Domain, _count: int | None = Query(None), + _offset: int = Query(0)) -> Response: # fmt: skip + """Every measure of the domain (none for a domain without them yet).""" + count, offset = _page(_count, _offset) + found = [f.measure(x) for x in MEASURES.get(domain, {}).values()] + return bundle(request, _sliced(found, count, offset), len(found), count, offset) + + +@router.get("/MeasureReport", responses=_OK, response_class=Response) +def search_measure_report( + request: Request, + domain: Domain, + measure: str = Query(alias="measure", description="the Measure's id or canonical URL"), + periods: str = Query( + alias="reporting-period", + description="semesters (2025-S1) or months (2025-03), comma-separated", + ), + as_of: datetime | None = Query( + None, alias="as-of", description="count only what was known by then" + ), + event_cutoff: date | None = Query( + None, alias="event-cutoff", description="durations count to this day" + ), + _count: int | None = Query(None), + _offset: int = Query(0), +) -> Response: + """The measure's summary report for each period asked for, evaluated over gold.""" + found = _measure(domain, measure.split("|")[0]) + count, offset = _page(_count, _offset) + try: + asked = [(p.strip(), m.Period.parse(p.strip())) for p in periods.split(",") if p.strip()] + except ValueError as e: + raise HTTPException(422, f"reporting-period: {e}") from e + params = {"model": cacu.RISK_BAND_MODEL} if found.rows == "risk" else {} + rows = measure_reads.rows(found.rows, **params) + reports = [] + for text, period in _sliced(asked, count, offset): + result = m.evaluate(found, rows, period, as_of, event_cutoff) + report = m.report(found, period, result, as_of) + report.id = f"{f.measure_id(found.id)}-{text.lower()}" + reports.append(report) + return bundle(request, reports, len(asked), count, offset) + + +# --- CapabilityStatement ---------------------------------------------------------------------- + + +@router.get("/metadata", responses=_OK, response_class=Response) +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] = {} + for route in router.routes: + _, kind, *rest = route.path.removeprefix(router.prefix).split("/") + if kind == "metadata" or (kind != "Measure" and kind != "MeasureReport" + and domain not in CLINICAL): # fmt: skip + continue + entry = resources.setdefault(kind, {"type": kind, "interaction": [], "searchParam": []}) + if kind == "Patient" and not rest: + entry |= {"searchInclude": ["DiagnosticReport:result"], + "searchRevInclude": list(REVINCLUDES)} # fmt: skip + entry["interaction"].append({"code": "read" if rest else "search-type"}) + for param in route.dependant.query_params: + name = param.alias + if name.startswith("_") and name != "_id": + continue + declared = f.SEARCH_PARAMETERS.get(name) + entry["searchParam"].append({ + "name": name, + "type": declared[1] if declared else _STANDARD[name], + **({"definition": f"{f.BASE}/SearchParameter/{name}"} if declared else {}), + }) # fmt: skip + statement = CapabilityStatement.model_validate({ + "resourceType": "CapabilityStatement", + "status": "active", + "date": date.today().isoformat(), + "kind": "instance", + "fhirVersion": f.FHIR_VERSION, + "format": ["json"], + "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()]}], + }) # fmt: skip + return fhir(statement) + + +_STANDARD = {"_id": "token", "subject": "reference", "measure": "reference"} diff --git a/webapi/main.py b/webapi/main.py index 21e74a8..d1c8390 100644 --- a/webapi/main.py +++ b/webapi/main.py @@ -1,7 +1,9 @@ -from fastapi import Depends, FastAPI +from fastapi import Depends, FastAPI, Request +from fastapi.exception_handlers import http_exception_handler +from starlette.exceptions import HTTPException from core.domains import Domain -from webapi import ingest, measures, models, review, runs +from webapi import fhir, ingest, models, review, runs from webapi.auth import caller app = FastAPI( @@ -14,7 +16,15 @@ app.include_router(ingest.router) app.include_router(review.router) app.include_router(runs.router) app.include_router(models.router) -app.include_router(measures.router) +app.include_router(fhir.router) + + +@app.exception_handler(HTTPException) +async def errors(request: Request, error: HTTPException): + """FHIR routes answer errors as an OperationOutcome.""" + if "/fhir/" in request.url.path or request.url.path.endswith("/fhir"): + return fhir.outcome(error.status_code, str(error.detail)) + return await http_exception_handler(request, error) @app.get("/health") diff --git a/webapi/measures.py b/webapi/measures.py deleted file mode 100644 index eae3f6f..0000000 --- a/webapi/measures.py +++ /dev/null @@ -1,48 +0,0 @@ -"""CaCu's measures, evaluated on request over gold and served as FHIR R4B MeasureReports: -one Bundle per measure, one report per period asked for. Counting a few thousand rows is all -the request does; everything heavy was done by dbt.""" - -from datetime import date, datetime - -from fastapi import APIRouter, HTTPException, Query -from fhir.resources.R4B.bundle import Bundle - -from core import cacu -from core import measures as m -from core.domains import Domain -from persistance import measures as reads - -router = APIRouter(tags=["measures"]) -DOMAINS = {Domain.CACU: m.MEASURES} - - -@router.get("/{domain}/measures") -def measures(domain: Domain) -> list[dict[str, str]]: - found = DOMAINS.get(domain, {}) - return [{"id": x.id, "title": x.title, "scoring": x.rule.kind} for x in found.values()] - - -@router.get("/{domain}/measures/{measure_id}") -def measure( - domain: Domain, - measure_id: str, - periods: str = Query(description="comma-separated semesters (2025-S1) or months (2025-03)"), - as_of: datetime | None = Query(None, description="count only what was known by then"), - event_cutoff: date | None = Query(None, description="durations count to this day"), -) -> dict: - """A Bundle (searchset) with the measure's MeasureReport for each period.""" - if (found := DOMAINS.get(domain, {}).get(measure_id)) is None: - raise HTTPException(404, detail=f"no {domain.value} measure {measure_id}") - try: - asked = [m.Period.parse(p.strip()) for p in periods.split(",") if p.strip()] - except ValueError as e: - raise HTTPException(422, detail=f"periods: {e}") from e - params = {"model": cacu.RISK_BAND_MODEL} if found.rows == "risk" else {} - rows = reads.rows(found.rows, **params) - reports = [ - m.report(found, p, m.evaluate(found, rows, p, as_of, event_cutoff), as_of, domain.value) - for p in asked - ] - bundle = Bundle(type="searchset", total=len(reports), - entry=[{"resource": r} for r in reports]) # fmt: skip - return bundle.model_dump(mode="json", exclude_none=True)