FHIR, follow-up lists and model jobs by domain; CaMa gate; report download for governance

This commit is contained in:
Roberto Treviño
2026-11-25 23:20:52 -06:00
parent 806302ee5d
commit 26cf994d1a
5 changed files with 311 additions and 74 deletions
+4 -1
View File
@@ -10,6 +10,9 @@ Fixed on purpose, so compared differently:
- cin2_pim_post_colposcopy scores each patient at her post-colposcopy index; the current - 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. 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. - cin2_logistic's index date is the index sample's, not 1970-01-01.
- survival indexes at the first biopsy reported as carcinoma or carcinoma in situ; the current
index read only invasive carcinoma and indexed nobody (its reference was captured with that
one rule fixed).
- One rule, one value: a diagnosis note assesses a sample within SAMPLE_TO_DIAGNOSIS_DAYS - 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 (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. (198) is post-colposcopy there and pre-colposcopy here.
@@ -125,7 +128,7 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path)
# none is promoted without the clinical validation. # none is promoted without the clinical validation.
wait_for(api, ok(api.post("/models/cacu/train", json={"as_of": REFERENCE_CUTOFF}))["run_id"]) wait_for(api, ok(api.post("/models/cacu/train", json={"as_of": REFERENCE_CUTOFF}))["run_id"])
names = ok(api.get("/models/cacu")) names = ok(api.get("/models/cacu"))
assert set(names) == set(current) - {"survival"} assert set(names) == set(current)
for name in names: for name in names:
(version,) = ok(api.get(f"/models/cacu/{name}/versions")) (version,) = ok(api.get(f"/models/cacu/{name}/versions"))
assert version["reports"] == ["interpretability", "technical_validation"] assert version["reports"] == ["interpretability", "technical_validation"]
+207
View File
@@ -0,0 +1,207 @@
"""Phase 4 gate, CaMa: the synthetic hospital, loaded through one drawn pipeline, gives what
the current platform gives on the same hospital (the reference fixtures, captured at the last
load): its indicators, its follow-up list and, trained by the platform's own jobs, its
models' predictions. Real API, Dagster and MLflow; nothing faked.
Fixed on purpose, so compared differently:
- Survival follows each patient up to the day it is trained (`as_of`), not to the day the
job happens to run: the reference was trained on 2026-11-24.
- BI-RADS 4A, 4B and 4C are kept as reported. The current platform folds them into 4 when it
loads them, so here they are summed into its B4, and only here.
"""
import json
import sqlite3
from collections import defaultdict
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from fhir_checks import pages, served, unscored, validate
from test_conectar import ok, wait_for
from conftest import put_concept_map
ROOT = Path(__file__).parents[2]
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital"
REFERENCE = ROOT / "tests" / "fixtures" / "reference" / "cama"
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_cama.json"
CAPTURED_ON = "2026-11-26" # the day of the capture's load: durations counted to it
TRAINED_ON = "2026-11-24" # survival's follow-up ended the day the reference was trained
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
CODES = { # platform code -> the current platform's
**{c: f"B{c}" for c in ("0", "1", "2", "3", "4", "5", "6")},
"4A": "B4", "4B": "B4", "4C": "B4",
"benign": "BENIGNO", "in_situ": "CARCINOMA_IN_SITU", "invasive": "CARCINOMA_INVASOR",
"no_data": "SIN_DATO", "no_biopsy": "SIN_BIOPSIA",
} # fmt: skip
CATEGORY = {"CAMA_BIOPSIAS": "grado", "CAMA_HISTOPATOLOGIA_BIRADS": "biopsia_grado"}
STATUS = {"cancer": "Diagnóstico confirmado, sin tratamiento registrado",
"pending_biopsy": "Pendiente de biopsia", "biopsy_no_result": "Biopsia sin resultado",
"benign_biopsy": "Biopsia benigna"} # fmt: skip
PRIORITY = {"high": "Alta", "medium": "Media", "low": "Baja"}
E = "https://isssteleon.org/fhir/StructureDefinition/"
def _patients(q) -> dict[str, str]:
"""Each person's patient id in the hospital (for comparing only)."""
with sqlite3.connect(HOSPITAL / "hospital_cama.db") as con:
number = {n.replace("-", ""): str(p) for p, n in con.execute(
"select pac_id, pac_id_hospital from paciente")} # fmt: skip
rows = q("select distinct person_id, record_number from bronze.staged__identity")
return {person: number[record] for person, record in rows}
def _ext(resource: dict, name: str):
found = next((x for x in resource.get("extension", []) if x["url"] == E + name), None)
return found and next(v for k, v in found.items() if k.startswith("value"))
def _follow_up(bundles: list[dict], cutoff: str, patient: dict[str, str]) -> list[dict]:
"""The follow-up list as the WebApp shows it: per patient, her status and priority, her
latest mammogram reported by the cut-off, and the latest reported biopsy it led to."""
resources = [e["resource"] for b in bundles for e in b.get("entry", [])]
observations = {r["id"]: r for r in resources if r["resourceType"] == "Observation"}
def values(report: dict) -> dict:
found = {}
for x in report.get("result", []):
o = observations[x["reference"].split("/")[1]]
value = o.get("valueDateTime") or o.get("valueCodeableConcept", {})
found[o["code"]["coding"][0]["code"].split(".")[1]] = (
value if isinstance(value, str) else value["coding"][0]["code"]
)
return found # fmt: skip
rows = []
for p in (r for r in resources if r["resourceType"] == "Patient"):
mine = [r for r in resources if r["resourceType"] == "DiagnosticReport"
and r["subject"]["reference"] == f"Patient/{p['id']}"] # fmt: skip
mammograms = [(r["effectiveDateTime"], values(r)) for r in mine
if r["code"]["coding"][0]["code"] == "mammography"
and (_ext(r, "report-date") or "9") <= cutoff] # fmt: skip
exam, mammogram = max(mammograms, key=lambda m: m[0])
biopsies = sorted((_ext(r, "report-date"), values(r)) for r in mine
if r["code"]["coding"][0]["code"] == "breast_biopsy"
and _ext(r, "report-date")
and exam <= _ext(r, "report-date") <= cutoff) # fmt: skip
biopsies = [b for b in biopsies if b[1].get("mammogram_exam_date") == exam]
last = biopsies[-1] if biopsies else (None, {})
rows.append({
"pac_id": patient[p["id"]], "mastografia_fecha": exam,
"birads": "BIRADS_" + mammogram["birads"][:1],
"estatus": STATUS[_ext(p, "follow-up-status")["code"]],
"prioridad": PRIORITY[_ext(p, "follow-up-priority")["code"]],
"biopsia": CODES.get(last[1].get("histology")), "biopsia_fecha": last[0],
}) # fmt: skip
return rows
def _report(entry: dict, measure: str) -> tuple:
group = entry["resource"]["group"][0]
populations = {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]}
score = group.get("measureScore", {})
extensions = {e["url"].rsplit("/", 1)[1]: e["valueDecimal"] for e in score.get("extension", [])}
strata = {}
for s in group.get("stratifier", []):
code = s["code"][0]
name = code["coding"][0]["code"] if "coding" in code else code["text"]
name = CATEGORY.get(measure, "birads") if name == "category" else name
cells: dict = defaultdict(lambda: defaultdict(int))
for x in s.get("stratum", []):
for p in x["population"]:
cells[CODES.get(x["value"]["text"], x["value"]["text"])][
p["code"]["coding"][0]["code"]] += p["count"] # fmt: skip
strata[name] = {k: dict(v) for k, v in cells.items()}
return populations, score.get("value"), extensions, {k: v for k, v in strata.items() if v}
def test_cama_from_the_hospital_to_indicators(api, platform, tmp_path):
pipeline = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL)))
put_concept_map(api, "hospital_cama")
ok(api.put("/ingest/pipelines/cama", json=pipeline))
wait_for(api, ok(api.post("/ingest/pipelines/cama/runs", json={}))["run_id"])
# Indicators: every measure, every semester, as the current platform answers them.
reference = json.loads((REFERENCE / "indicators.json").read_text())
(measures,) = pages(api, "/cama/fhir/Measure")
assert {m["resource"]["name"] for m in measures["entry"]} == set(reference)
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, "/cama/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, a, b)
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
# The follow-up list: who, in which order, where her biopsy stands and how soon.
theirs = json.loads((REFERENCE / "pages.json").read_text())["/cama/seguimiento"]["body"]
window = theirs["ventana"]
params = {"follow-up-window": window["meses"], "follow-up-cutoff": window["hasta"],
"_revinclude": "DiagnosticReport:subject",
"_include:iterate": "DiagnosticReport:result", "_count": 200} # fmt: skip
ours = _follow_up(pages(api, "/cama/fhir/Patient", params), window["hasta"],
_patients(platform.query)) # fmt: skip
keys = ("pac_id", "mastografia_fecha", "birads", "estatus", "prioridad", "biopsia",
"biopsia_fecha") # fmt: skip
order = lambda r: (r["mastografia_fecha"], -int(r["pac_id"])) # noqa: E731
expected = [{k: r[k] for k in keys} for r in theirs["items"]]
assert sorted(ours, key=order, reverse=True) == sorted(expected, key=order, reverse=True)
assert [r["mastografia_fecha"] for r in ours] == [r["mastografia_fecha"] for r in expected]
# Models: one training run gives a version of each, with its two generated reports;
# none is promoted without the clinical validation.
current = json.loads((REFERENCE / "models.json").read_text())
wait_for(api, ok(api.post("/models/cama/train", json={"as_of": TRAINED_ON}))["run_id"])
names = ok(api.get("/models/cama"))
assert set(names) == {n for n, m in current.items() if m["status"] == "ok"}
for name in names:
(version,) = ok(api.get(f"/models/cama/{name}/versions"))
assert version["reports"] == ["interpretability", "technical_validation"]
for metric in ("n_train", "n_test"):
assert version["metrics"][metric] == current[name]["version"]["metrics"][metric]
assert api.post(f"/models/cama/{name}/versions/1/promote").status_code == 409
files = {"file": ("validacion.pdf", b"%PDF-1.4 clinical validation", "application/pdf")}
ok(api.post(f"/models/cama/{name}/versions/1/reports/clinical_validation", files=files))
assert ok(api.post(f"/models/cama/{name}/versions/1/promote")) == {"champion": 1}
report = api.get(f"/models/cama/{name}/versions/1/reports/interpretability")
assert report.headers["content-type"] == "application/json"
assert [c["name"] for c in report.json()["curves"]][0].startswith("Kaplan-Meier")
pdf = api.get(f"/models/cama/{name}/versions/1/reports/clinical_validation")
assert pdf.headers["content-type"] == "application/pdf" and pdf.content.startswith(b"%PDF")
# Risks: the champions score their cohorts with the current models' predictions.
wait_for(api, ok(api.post("/models/cama/score"))["run_id"])
patient = _patients(platform.query)
for name in names:
risks = pd.DataFrame(platform.query(
"select person_id, index_date, horizon_years, probability "
f"from gold.cama_risk where model = 'cama.{name}'"
), columns=["person_id", "index_date", "horizon_years", "probability"]) # fmt: skip
risks["pac_id"] = risks["person_id"].map(patient).astype(int)
expected = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet")
both = risks.merge(expected, left_on=["pac_id", "horizon_years"],
right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip
assert len(both) == len(expected) == len(risks), name
assert (both["index_date"].astype(str) == both["fecha_indice"].astype(str)).all()
np.testing.assert_allclose(both["probability"].astype(float), both["probabilidad"],
rtol=1e-6) # fmt: skip
# Every resource the API serves, every search paged to the end, passes the HL7
# validator (offline: structure, cardinality, profiles; no terminology server).
people = [r["id"] for b in pages(api, "/cama/fhir/Patient", {"follow-up-window": 12})
for r in (e["resource"] for e in b["entry"])][:10] # fmt: skip
resources = served(api, "/cama/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)] == []
+14 -9
View File
@@ -1,6 +1,7 @@
"""Phase 3 gate, the WebApp: every page loads from the new API. The platform runs as in """Phase 3 and 4 gate, the WebApp: every page loads from the new API. The platform runs as
production (API, Dagster), loaded with the synthetic CaCu hospital and the messy site; in production (API, Dagster), loaded with the synthetic CaCu and CaMa hospitals (CaMa's
Playwright drives the real pages against it (WebApp/e2e).""" models trained, none promoted) and the messy site; Playwright drives the real pages against
it (WebApp/e2e)."""
import json import json
import os import os
@@ -8,22 +9,26 @@ import subprocess
from pathlib import Path from pathlib import Path
import pytest import pytest
from test_conectar import ok, run from test_conectar import ok, run, wait_for
from conftest import put_concept_map from conftest import put_concept_map
ROOT = Path(__file__).parents[2] ROOT = Path(__file__).parents[2]
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital" HOSPITAL = ROOT / "tests" / "fixtures" / "hospital"
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_cacu.json" PIPELINES = ROOT / "tests" / "fixtures" / "pipelines"
@pytest.mark.webapp @pytest.mark.webapp
@pytest.mark.parametrize("platform", ["sqlite"], indirect=True) # pages read one API either way @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): def test_every_page_loads_from_the_api(api, platform, messy_site):
hospital = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL))) for domain in ("cacu", "cama"):
put_concept_map(api, "hospital_cacu") drawn = (PIPELINES / f"hospital_{domain}.json").read_text()
ok(api.put("/ingest/pipelines/cacu", json=hospital)) put_concept_map(api, f"hospital_{domain}")
run(api, "cacu") ok(api.put(f"/ingest/pipelines/{domain}", json=json.loads(
drawn.replace("{hospital}", str(HOSPITAL))))) # fmt: skip
run(api, domain)
# A trained CaMa version, unpromoted: what the governance page shows and refuses.
wait_for(api, ok(api.post("/models/cama/train", json={"as_of": "2026-11-24"}))["run_id"])
put_concept_map(api, "messy_site") put_concept_map(api, "messy_site")
ok(api.put("/ingest/pipelines/site", json=json.loads(messy_site.drawn))) ok(api.put("/ingest/pipelines/site", json=json.loads(messy_site.drawn)))
run(api, "site") run(api, "site")
+63 -56
View File
@@ -14,11 +14,11 @@ from fhir.resources.R4B.capabilitystatement import CapabilityStatement
from fhir.resources.R4B.operationoutcome import OperationOutcome from fhir.resources.R4B.operationoutcome import OperationOutcome
from fhir.resources.R4B.resource import Resource 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 fhir as f
from core import follow_up as fu
from core import measures as m 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 core.pipeline import ID_PATTERN
from persistance import config_log, readers from persistance import config_log, readers
from persistance import fhir as reads from persistance import fhir as reads
@@ -27,8 +27,6 @@ from webapi.ingest import submit
from webapi.runs import dagster from webapi.runs import dagster
FHIR_JSON = "application/fhir+json" FHIR_JSON = "application/fhir+json"
MEASURES = {Domain.CACU: m.MEASURES}
CLINICAL = {Domain.CACU} # domains whose clinical resources are served
PAGE, MAX_PAGE = 50, 200 PAGE, MAX_PAGE = 50, 200
REVINCLUDES = ("DiagnosticReport:subject", "RiskAssessment:subject", "Observation:subject") 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 status_code=status, media_type=FHIR_JSON) # fmt: skip
def _clinical(domain: Domain) -> None: def _clinical(domain: Domain):
if domain not in CLINICAL: """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") raise HTTPException(404, f"no clinical resources for {domain.value} yet")
return found
def _cutoff(asked: date | None) -> date: def _cutoff(domain: Domain, asked: date | None) -> date:
last = reads.last_data_day() """The day asked for, or by default the last day with data in the domain (up to today)."""
if asked is None: if asked is not None:
return last or date.today() return asked
return asked if last is None else min(asked, last) return reads.last_data_day(domain.value) or date.today()
def _page(count: int | None, offset: int) -> tuple[int, int]: 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) @router.get("/Patient/{id}", responses=_OK, response_class=Response)
def read_patient(domain: Domain, id: str) -> Response: def read_patient(domain: Domain, id: str) -> Response:
_clinical(domain) fu = _clinical(domain)
(row,) = reads.rows("person", id=id) or [None] (row,) = reads.rows(domain.value, "person", id=id) or [None]
if row is 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: if link is None:
raise HTTPException(404, f"no Patient/{id}") raise HTTPException(404, f"no Patient/{id}")
return fhir(f.replaced_patient(id, link["replaced_by"])) return fhir(f.replaced_patient(id, link["replaced_by"]))
(found,) = _with_identity([{**row, "status": fu.status(row, _cutoff(None))}]) status = fu.status(row, _cutoff(domain, None))
return fhir(f.patient(found)) (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 with their names, identifiers and the ids they replaced."""
persons = [r["person_id"] for r in rows] persons = [r["person_id"] for r in rows]
names, ids, replaces = {}, {}, {} 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"]) 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"])) 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"]) replaces.setdefault(r["replaced_by"], []).append(r["person_id"])
return [ return [
{**r, "names": names.get(p, []), "identifiers": ids.get(p, []), {**r, "names": names.get(p, []), "identifiers": ids.get(p, []),
@@ -133,43 +134,49 @@ def search_patient(
window: int | None = Query( window: int | None = Query(
None, None,
alias="follow-up-window", 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( cutoff: date | None = Query(
None, alias="follow-up-cutoff", description="default: the last day with data" None, alias="follow-up-cutoff", description="default: the last day with data"
), ),
status: str | None = Query(None, alias="follow-up-status"), status: str | None = Query(None, alias="follow-up-status"),
sort: str = Query("-recent", alias="_sort", description=f"one of {fu.SORTS}; the list only"), sort: str = Query("-recent", alias="_sort", description="-recent or -risk-<outcome>"),
horizon: float = Query(fu.DEFAULT_HORIZON, alias="risk-horizon", description="years"), horizon: float | None = Query(None, alias="risk-horizon", description="years"),
revinclude: list[str] = Query([], alias="_revinclude", description=f"any of {REVINCLUDES}"), revinclude: list[str] = Query([], alias="_revinclude", description=f"any of {REVINCLUDES}"),
include: list[str] = Query([], alias="_include:iterate", description="DiagnosticReport:result"), include: list[str] = Query([], alias="_include:iterate", description="DiagnosticReport:result"),
_count: int | None = Query(None), _count: int | None = Query(None),
_offset: int = Query(0), _offset: int = Query(0),
) -> Response: ) -> Response:
"""Patients; with `follow-up-window`, CaCu's follow-up list at the cut-off, filtered by """Patients; with `follow-up-window`, the domain's follow-up list at the cut-off,
status and in reading order, with what the list shows of each patient included.""" filtered by status and in reading order, with what the list shows of each patient
_clinical(domain) included."""
fu = _clinical(domain)
count, offset = _page(_count, _offset) 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: if window is None:
rows = reads.rows("persons") rows = [{**r, "status": fu.status(r, at)} for r in persons_rows]
if _id: if _id:
rows = [r for r in rows if r["person_id"] in _id.split(",")] rows = [r for r in rows if r["person_id"] in _id.split(",")]
else: else:
if window not in cacu.FOLLOW_UP_WINDOWS: if window not in fu.WINDOWS:
raise HTTPException(422, f"follow-up-window is one of {cacu.FOLLOW_UP_WINDOWS}") raise HTTPException(422, f"follow-up-window is one of {fu.WINDOWS}")
if sort not in fu.SORTS: if sort not in fu.SORTS:
raise HTTPException(422, f"_sort is one of {fu.SORTS}") raise HTTPException(422, f"_sort is one of {fu.SORTS}")
params = {"start": fu.window_start(at, window).isoformat(), "cutoff": at.isoformat()} start = window_start(at, window)
rows = reads.rows("follow_up", **params) params = {"start": start.isoformat(), "cutoff": at.isoformat()}
for row in rows: person = {r["person_id"]: r for r in persons_rows}
row["status"] = fu.status(row, at) rows = [
{**person[r["person_id"]], **r}
for r in fu.listed(reads.rows(domain.value, "follow_up", **params), start, at)
]
if status: if status:
rows = [r for r in rows if r["status"] in status.split(",")] rows = [r for r in rows if r["status"] in status.split(",")]
persons = [r["person_id"] for r in rows] persons = [r["person_id"] for r in rows]
risks: dict[str, list[dict]] = {} risks: dict[str, list[dict]] = {}
if window is not None and sort != "-recent" or "RiskAssessment:subject" in revinclude: 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) risks.setdefault(r["person_id"], []).append(r)
if window is not None: if window is not None:
rows = fu.ordered(rows, sort, risks, horizon) rows = fu.ordered(rows, sort, risks, horizon)
@@ -178,7 +185,7 @@ def search_patient(
included = _included(domain, 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 {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 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, return bundle(request, patients, len(rows), count, offset, included,
applied) # fmt: skip applied) # fmt: skip
@@ -212,20 +219,18 @@ def _subjects(subject: str | None) -> list[str]:
return [s.removeprefix("Patient/") for s in subject.split(",")] 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]: 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 """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.""" by `at`: its DiagnosticReport (or Encounter) and Observations, in date order."""
found: list[Resource] = [] found: list[Resource] = []
report_facts = _clinical(domain).REPORT_FACTS
for study in catalog.of_domain(domain.value): for study in catalog.of_domain(domain.value):
spec = catalog.studies()[study] spec = catalog.studies()[study]
facts = {} 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"] 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) first = next(e.date for e in spec.events.values() if e.parent is None)
for row in reads.instances(study, persons, at): for row in reads.instances(study, persons, at):
days = facts.get((row["person_id"], str(row[first])[:10])) 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): def _clinical_search(kind: str, build, request, domain, subject, count, offset):
_clinical(domain) fu = _clinical(domain)
count, offset = _page(count, offset) count, offset = _page(count, offset)
params = {"persons": _subjects(subject)} params: dict = {"persons": _subjects(subject)}
if kind != "risk": if kind != "risk":
params["cutoff"] = _cutoff(None).isoformat() params["cutoff"] = _cutoff(domain, None).isoformat()
found = build(reads.rows(kind, **params)) 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) 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: def _study_search(kind: str, request, domain, subject, count, offset) -> Response:
_clinical(domain) _clinical(domain)
count, offset = _page(count, offset) 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] 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) 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), subject: str | None = Query(None, description=SUBJECT),
_count: int | None = Query(None), _count: int | None = Query(None),
_offset: int = Query(0)) -> Response: # fmt: skip _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): def build(rows):
return [f.procedure(r) for r in 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: def _measure(domain: Domain, key: str) -> m.Measure:
found = MEASURES.get(domain, {}) found = measures(domain)
for code, measure in found.items(): for code, measure in found.items():
if key in (code, f.measure_id(code), f.measure_url(code)): if key in (code, f.measure_id(code), f.measure_url(code)):
return measure return measure
@@ -339,7 +346,7 @@ def _measure(domain: Domain, key: str) -> m.Measure:
@router.get("/Measure/{id}", responses=_OK, response_class=Response) @router.get("/Measure/{id}", responses=_OK, response_class=Response)
def read_measure(domain: Domain, id: str) -> 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) @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 _offset: int = Query(0)) -> Response: # fmt: skip
"""Every measure of the domain (none for a domain without them yet).""" """Every measure of the domain (none for a domain without them yet)."""
count, offset = _page(_count, _offset) 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) 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()] asked = [(p.strip(), m.Period.parse(p.strip())) for p in periods.split(",") if p.strip()]
except ValueError as e: except ValueError as e:
raise HTTPException(422, f"reporting-period: {e}") from 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(domain.value, found.rows, **found.params)
rows = measure_reads.rows(found.rows, **params)
reports = [] reports = []
for text, period in _sliced(asked, count, offset): for text, period in _sliced(asked, count, offset):
result = m.evaluate(found, rows, period, as_of, event_cutoff) 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.""" """What this base serves: built from the routes above, so it cannot drift from them."""
resources: dict[str, dict] = {} resources: dict[str, dict] = {}
system: list[dict] = [] system: list[dict] = []
clinical = part(domain, "follow_up") is not None
for route in router.routes: for route in router.routes:
path = route.path.removeprefix(router.prefix) path = route.path.removeprefix(router.prefix)
if not path: # the base itself: the FHIR door if not path: # the base itself: the FHIR door
if domain in CLINICAL: if clinical:
system = [{"code": "batch"}, {"code": "transaction"}] system = [{"code": "batch"}, {"code": "transaction"}]
continue continue
_, kind, *rest = path.split("/") _, kind, *rest = path.split("/")
if kind == "metadata" or (kind != "Measure" and kind != "MeasureReport" if kind == "metadata" or (kind != "Measure" and kind != "MeasureReport"
and domain not in CLINICAL): # fmt: skip and not clinical): # fmt: skip
continue continue
entry = resources.setdefault(kind, {"type": kind, "interaction": [], "searchParam": []}) entry = resources.setdefault(kind, {"type": kind, "interaction": [], "searchParam": []})
if kind == "Patient" and not rest: if kind == "Patient" and not rest:
+23 -8
View File
@@ -1,10 +1,12 @@
"""Model governance: versions and their reports (MLflow), promotion, and the training and """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.""" scoring runs (Dagster). The API starts runs and reads the registry; it never trains."""
import mimetypes
from datetime import date from datetime import date
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
from fastapi import APIRouter, Depends, HTTPException, UploadFile from fastapi import APIRouter, Depends, HTTPException, UploadFile
from fastapi.responses import Response
from pydantic import BaseModel from pydantic import BaseModel
from core.domains import Domain from core.domains import Domain
@@ -12,7 +14,6 @@ from persistance import registry
from webapi.runs import dagster from webapi.runs import dagster
router = APIRouter(prefix="/models", tags=["models"]) router = APIRouter(prefix="/models", tags=["models"])
JOBS = {Domain.CACU: ("train_cacu", "score_cacu")}
class Version(BaseModel): class Version(BaseModel):
@@ -37,6 +38,22 @@ def versions(domain: Domain, name: str) -> list[Version]:
return [Version(**v) for v in found] 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") @router.post("/{domain}/{name}/versions/{version}/reports/clinical_validation")
def add_clinical_validation(domain: Domain, name: str, version: int, file: UploadFile) -> dict: 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.""" """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, def train(domain: Domain, request: Training,
client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: # fmt: skip client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: # fmt: skip
"""Starts training a new version of every model of the domain; follow it at /runs.""" """Starts training a new version of every model of the domain; follow it at /runs."""
if domain not in JOBS: config = {"domain": domain.value}
raise HTTPException(404, detail=f"{domain.value} has no models yet") if request.as_of:
config = {"as_of": request.as_of.isoformat()} if request.as_of else {} config["as_of"] = request.as_of.isoformat()
return _submit(client, JOBS[domain][0], "train_models", config) return _submit(client, "train", "train_models", config)
@router.post("/{domain}/score") @router.post("/{domain}/score")
def score(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: def score(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
"""Starts a risk batch from each model's champion; follow it at /runs.""" """Starts a risk batch from each model's champion; follow it at /runs."""
if domain not in JOBS: return _submit(client, "score", "score_models", {"domain": domain.value})
raise HTTPException(404, detail=f"{domain.value} has no models yet")
return _submit(client, JOBS[domain][1], "score_models", {})