FHIR, follow-up lists and model jobs by domain; CaMa gate; report download for governance
This commit is contained in:
+63
-56
@@ -14,11 +14,11 @@ 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, catalog
|
||||
from core import 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.domains import Domain, measures, part
|
||||
from core.follow_up import window_start
|
||||
from core.pipeline import ID_PATTERN
|
||||
from persistance import config_log, readers
|
||||
from persistance import fhir as reads
|
||||
@@ -27,8 +27,6 @@ from webapi.ingest import submit
|
||||
from webapi.runs import dagster
|
||||
|
||||
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")
|
||||
|
||||
@@ -47,16 +45,18 @@ def outcome(status: int, text: str) -> Response:
|
||||
status_code=status, media_type=FHIR_JSON) # fmt: skip
|
||||
|
||||
|
||||
def _clinical(domain: Domain) -> None:
|
||||
if domain not in CLINICAL:
|
||||
def _clinical(domain: Domain):
|
||||
"""The domain's follow-up module: a domain serves clinical resources once it has one."""
|
||||
if (found := part(domain, "follow_up")) is None:
|
||||
raise HTTPException(404, f"no clinical resources for {domain.value} yet")
|
||||
return found
|
||||
|
||||
|
||||
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 _cutoff(domain: Domain, asked: date | None) -> date:
|
||||
"""The day asked for, or by default the last day with data in the domain (up to today)."""
|
||||
if asked is not None:
|
||||
return asked
|
||||
return reads.last_data_day(domain.value) or date.today()
|
||||
|
||||
|
||||
def _page(count: int | None, offset: int) -> tuple[int, int]:
|
||||
@@ -97,26 +97,27 @@ def _sliced(found: list, count: int, offset: int) -> list:
|
||||
|
||||
@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]
|
||||
fu = _clinical(domain)
|
||||
(row,) = reads.rows(domain.value, "person", id=id) or [None]
|
||||
if row is None:
|
||||
(link,) = reads.rows("replaced", id=id) or [None]
|
||||
(link,) = reads.rows(domain.value, "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))
|
||||
status = fu.status(row, _cutoff(domain, None))
|
||||
(found,) = _with_identity(domain, [{**row, "status": status}])
|
||||
return fhir(f.patient(found, fu.STATUS_SYSTEM))
|
||||
|
||||
|
||||
def _with_identity(rows: list[dict]) -> list[dict]:
|
||||
def _with_identity(domain: Domain, 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):
|
||||
for r in reads.rows(domain.value, "names", persons=persons):
|
||||
names.setdefault(r["person_id"], []).append(r["text"])
|
||||
for r in reads.rows("identifiers", persons=persons):
|
||||
for r in reads.rows(domain.value, "identifiers", persons=persons):
|
||||
ids.setdefault(r["person_id"], []).append((r["system"], r["value"]))
|
||||
for r in reads.rows("replaces", persons=persons):
|
||||
for r in reads.rows(domain.value, "replaces", persons=persons):
|
||||
replaces.setdefault(r["replaced_by"], []).append(r["person_id"])
|
||||
return [
|
||||
{**r, "names": names.get(p, []), "identifiers": ids.get(p, []),
|
||||
@@ -133,43 +134,49 @@ def search_patient(
|
||||
window: int | None = Query(
|
||||
None,
|
||||
alias="follow-up-window",
|
||||
description="months: whoever had a cytology sampled within them up to the cut-off",
|
||||
description="months: the domain's follow-up list over that window 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"),
|
||||
sort: str = Query("-recent", alias="_sort", description="-recent or -risk-<outcome>"),
|
||||
horizon: float | None = Query(None, 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)
|
||||
"""Patients; with `follow-up-window`, the domain's follow-up list at the cut-off,
|
||||
filtered by status and in reading order, with what the list shows of each patient
|
||||
included."""
|
||||
fu = _clinical(domain)
|
||||
count, offset = _page(_count, _offset)
|
||||
at = _cutoff(cutoff)
|
||||
at = _cutoff(domain, cutoff)
|
||||
horizon = fu.DEFAULT_HORIZON if horizon is None else horizon
|
||||
persons_rows = reads.rows(domain.value, "persons")
|
||||
if window is None:
|
||||
rows = reads.rows("persons")
|
||||
rows = [{**r, "status": fu.status(r, at)} for r in persons_rows]
|
||||
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 window not in fu.WINDOWS:
|
||||
raise HTTPException(422, f"follow-up-window is one of {fu.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)
|
||||
start = window_start(at, window)
|
||||
params = {"start": start.isoformat(), "cutoff": at.isoformat()}
|
||||
person = {r["person_id"]: r for r in persons_rows}
|
||||
rows = [
|
||||
{**person[r["person_id"]], **r}
|
||||
for r in fu.listed(reads.rows(domain.value, "follow_up", **params), start, 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):
|
||||
for r in reads.rows(domain.value, "risk", persons=persons):
|
||||
risks.setdefault(r["person_id"], []).append(r)
|
||||
if window is not None:
|
||||
rows = fu.ordered(rows, sort, risks, horizon)
|
||||
@@ -178,7 +185,7 @@ def search_patient(
|
||||
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
|
||||
patients = [f.patient(r) for r in _with_identity(page)]
|
||||
patients = [f.patient(r, fu.STATUS_SYSTEM) for r in _with_identity(domain, page)]
|
||||
return bundle(request, patients, len(rows), count, offset, included,
|
||||
applied) # fmt: skip
|
||||
|
||||
@@ -212,20 +219,18 @@ 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] = []
|
||||
report_facts = _clinical(domain).REPORT_FACTS
|
||||
for study in catalog.of_domain(domain.value):
|
||||
spec = catalog.studies()[study]
|
||||
facts = {}
|
||||
if kind := REPORT_FACTS.get(study):
|
||||
if kind := report_facts.get(study):
|
||||
found_facts = reads.rows(domain.value, kind, persons=persons, cutoff=at)
|
||||
facts = {(r["person_id"], str(r["sample_date"])[:10]): r["days"]
|
||||
for r in reads.rows(kind, persons=persons, cutoff=at)} # fmt: skip
|
||||
for r in found_facts} # 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]))
|
||||
@@ -243,12 +248,14 @@ def _risk_assessments(rows: list[dict]) -> list[Resource]:
|
||||
|
||||
|
||||
def _clinical_search(kind: str, build, request, domain, subject, count, offset):
|
||||
_clinical(domain)
|
||||
fu = _clinical(domain)
|
||||
count, offset = _page(count, offset)
|
||||
params = {"persons": _subjects(subject)}
|
||||
params: dict = {"persons": _subjects(subject)}
|
||||
if kind != "risk":
|
||||
params["cutoff"] = _cutoff(None).isoformat()
|
||||
found = build(reads.rows(kind, **params))
|
||||
params["cutoff"] = _cutoff(domain, None).isoformat()
|
||||
if kind == "procedure":
|
||||
params["types"] = list(fu.PROCEDURES)
|
||||
found = build(reads.rows(domain.value, kind, **params))
|
||||
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
|
||||
|
||||
|
||||
@@ -268,7 +275,7 @@ def search_diagnostic_report(request: Request, domain: Domain,
|
||||
def _study_search(kind: str, request, domain, subject, count, offset) -> Response:
|
||||
_clinical(domain)
|
||||
count, offset = _page(count, offset)
|
||||
persons, at = _subjects(subject), _cutoff(None).isoformat()
|
||||
persons, at = _subjects(subject), _cutoff(domain, None).isoformat()
|
||||
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)
|
||||
|
||||
@@ -309,7 +316,7 @@ 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."""
|
||||
"""The procedures the domain's timeline infers (CaCu: colposcopies and treatments)."""
|
||||
|
||||
def build(rows):
|
||||
return [f.procedure(r) for r in rows]
|
||||
@@ -330,7 +337,7 @@ def search_risk_assessment(request: Request, domain: Domain,
|
||||
|
||||
|
||||
def _measure(domain: Domain, key: str) -> m.Measure:
|
||||
found = MEASURES.get(domain, {})
|
||||
found = measures(domain)
|
||||
for code, measure in found.items():
|
||||
if key in (code, f.measure_id(code), f.measure_url(code)):
|
||||
return measure
|
||||
@@ -339,7 +346,7 @@ def _measure(domain: Domain, key: str) -> m.Measure:
|
||||
|
||||
@router.get("/Measure/{id}", responses=_OK, response_class=Response)
|
||||
def read_measure(domain: Domain, id: str) -> Response:
|
||||
return fhir(f.measure(_measure(domain, id)))
|
||||
return fhir(f.measure(_measure(domain, id), domain.value))
|
||||
|
||||
|
||||
@router.get("/Measure", responses=_OK, response_class=Response)
|
||||
@@ -347,7 +354,7 @@ def search_measure(request: Request, domain: Domain, _count: int | None = Query(
|
||||
_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()]
|
||||
found = [f.measure(x, domain.value) for x in measures(domain).values()]
|
||||
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
|
||||
|
||||
|
||||
@@ -376,8 +383,7 @@ def search_measure_report(
|
||||
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)
|
||||
rows = measure_reads.rows(domain.value, found.rows, **found.params)
|
||||
reports = []
|
||||
for text, period in _sliced(asked, count, offset):
|
||||
result = m.evaluate(found, rows, period, as_of, event_cutoff)
|
||||
@@ -431,15 +437,16 @@ 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] = []
|
||||
clinical = part(domain, "follow_up") is not None
|
||||
for route in router.routes:
|
||||
path = route.path.removeprefix(router.prefix)
|
||||
if not path: # the base itself: the FHIR door
|
||||
if domain in CLINICAL:
|
||||
if 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
|
||||
and not clinical): # fmt: skip
|
||||
continue
|
||||
entry = resources.setdefault(kind, {"type": kind, "interaction": [], "searchParam": []})
|
||||
if kind == "Patient" and not rest:
|
||||
|
||||
+23
-8
@@ -1,10 +1,12 @@
|
||||
"""Model governance: versions and their reports (MLflow), promotion, and the training and
|
||||
scoring runs (Dagster). The API starts runs and reads the registry; it never trains."""
|
||||
|
||||
import mimetypes
|
||||
from datetime import date
|
||||
|
||||
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
||||
from fastapi import APIRouter, Depends, HTTPException, UploadFile
|
||||
from fastapi.responses import Response
|
||||
from pydantic import BaseModel
|
||||
|
||||
from core.domains import Domain
|
||||
@@ -12,7 +14,6 @@ from persistance import registry
|
||||
from webapi.runs import dagster
|
||||
|
||||
router = APIRouter(prefix="/models", tags=["models"])
|
||||
JOBS = {Domain.CACU: ("train_cacu", "score_cacu")}
|
||||
|
||||
|
||||
class Version(BaseModel):
|
||||
@@ -37,6 +38,22 @@ def versions(domain: Domain, name: str) -> list[Version]:
|
||||
return [Version(**v) for v in found]
|
||||
|
||||
|
||||
@router.get("/{domain}/{name}/versions/{version}/reports/{report}",
|
||||
responses={200: {"content": {"application/json": {}, "application/octet-stream": {}},
|
||||
"description": "the report as stored"}},
|
||||
response_class=Response) # fmt: skip
|
||||
def read_report(domain: Domain, name: str, version: int, report: str) -> Response:
|
||||
"""A version's report: the generated ones as JSON (what the governance page draws), the
|
||||
clinical validation as the file the clinical team uploaded."""
|
||||
found = registry.report(f"{domain.value}.{name}", version, report)
|
||||
if found is None:
|
||||
raise HTTPException(404, detail=f"{domain.value}.{name} v{version} has no {report}")
|
||||
filename, content = found
|
||||
kind = mimetypes.guess_type(filename)[0] or "application/octet-stream"
|
||||
return Response(content, media_type=kind,
|
||||
headers={"Content-Disposition": f'inline; filename="{filename}"'}) # fmt: skip
|
||||
|
||||
|
||||
@router.post("/{domain}/{name}/versions/{version}/reports/clinical_validation")
|
||||
def add_clinical_validation(domain: Domain, name: str, version: int, file: UploadFile) -> dict:
|
||||
"""The clinical team's validation of a version: the third report promotion needs."""
|
||||
@@ -72,15 +89,13 @@ def _submit(client: DagsterGraphQLClient, job: str, op: str, config: dict) -> di
|
||||
def train(domain: Domain, request: Training,
|
||||
client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: # fmt: skip
|
||||
"""Starts training a new version of every model of the domain; follow it at /runs."""
|
||||
if domain not in JOBS:
|
||||
raise HTTPException(404, detail=f"{domain.value} has no models yet")
|
||||
config = {"as_of": request.as_of.isoformat()} if request.as_of else {}
|
||||
return _submit(client, JOBS[domain][0], "train_models", config)
|
||||
config = {"domain": domain.value}
|
||||
if request.as_of:
|
||||
config["as_of"] = request.as_of.isoformat()
|
||||
return _submit(client, "train", "train_models", config)
|
||||
|
||||
|
||||
@router.post("/{domain}/score")
|
||||
def score(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
|
||||
"""Starts a risk batch from each model's champion; follow it at /runs."""
|
||||
if domain not in JOBS:
|
||||
raise HTTPException(404, detail=f"{domain.value} has no models yet")
|
||||
return _submit(client, JOBS[domain][1], "score_models", {})
|
||||
return _submit(client, "score", "score_models", {"domain": domain.value})
|
||||
|
||||
Reference in New Issue
Block a user