FHIR out from the catalog, the FHIR door, ConceptMap routes; round-trip, new-label and Synthea gates
This commit is contained in:
+12
-10
@@ -118,11 +118,11 @@ def follow_up(bundles: list[dict], start: str, cutoff: str) -> list[dict]:
|
||||
for x in report.get("result", []))} # fmt: skip
|
||||
|
||||
cytologies = sorted(
|
||||
(r for r in reports if _code(r["code"]) == "cervical-cytology"
|
||||
(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"
|
||||
hpv = [r for r in cytologies if "cervical_cytology.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"]
|
||||
@@ -132,20 +132,22 @@ def follow_up(bundles: list[dict], start: str, cutoff: str) -> list[dict]:
|
||||
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
|
||||
for k, c in (("result", "cervical_cytology.result"),
|
||||
("adequacy", "cervical_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]
|
||||
typed = ("cervical_cytology.hpv_16", "cervical_cytology.hpv_18")
|
||||
types = [found[k]["valueBoolean"] for k in typed if k in found]
|
||||
row["hpv"] = {"date": hpv[-1]["effectiveDateTime"],
|
||||
"positive": found["hpv"]["valueBoolean"],
|
||||
"positive": found["cervical_cytology.hpv"]["valueBoolean"],
|
||||
"types_16_18": any(types) if types else None} # fmt: skip
|
||||
if biopsies:
|
||||
last = biopsies[-1]
|
||||
last, found = biopsies[-1], results(biopsies[-1])
|
||||
grade = found.get("cervical_biopsy.histology")
|
||||
histology = grade and _code(grade["valueCodeableConcept"])
|
||||
row["biopsy"] = {"date": _ext(last, "report-date")["valueDate"],
|
||||
"histology": _code(last["conclusionCode"][0])
|
||||
if last.get("conclusionCode") else None} # fmt: skip
|
||||
"histology": histology} # fmt: skip
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
@@ -28,6 +28,8 @@ import pytest
|
||||
from fhir_checks import follow_up, 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" / "cacu"
|
||||
@@ -79,6 +81,7 @@ def _report(entry: dict, measure: str) -> tuple:
|
||||
|
||||
def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path):
|
||||
pipeline = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL)))
|
||||
put_concept_map(api, "hospital_cacu")
|
||||
ok(api.put("/ingest/pipelines/cacu", json=pipeline))
|
||||
wait_for(api, ok(api.post("/ingest/pipelines/cacu/runs", json={}))["run_id"])
|
||||
q = platform.query
|
||||
|
||||
+41
-6
@@ -54,8 +54,18 @@ def test_an_operator_connects_a_site_and_settles_its_review(api, platform, messy
|
||||
}
|
||||
assert len(ok(api.post("/ingest/sources/preview?limit=5", json=notes))) == 5
|
||||
|
||||
# Saving a drawing: broken ones are refused with the reason; good ones get versions.
|
||||
# The site's codes in platform terms: a ConceptMap, saved before the drawing that names
|
||||
# it. One that maps onto a code no field allows is refused, saying which.
|
||||
drawn = json.loads(messy_site.drawn)
|
||||
missing = api.put("/ingest/pipelines/site", json=drawn)
|
||||
assert missing.status_code == 422 and "messy_site" in missing.text
|
||||
codes = json.loads(messy_site.concept_map.read_text())
|
||||
wrong = json.loads(json.dumps(codes).replace('"code": "HSIL"', '"code": "BIRADS-7"'))
|
||||
refused = api.put("/ingest/concept-maps/messy_site", json=wrong)
|
||||
assert refused.status_code == 422 and "BIRADS-7 is not an allowed code" in refused.text
|
||||
assert ok(api.put("/ingest/concept-maps/messy_site", json=codes)) == {"version": 1}
|
||||
|
||||
# Saving a drawing: broken ones are refused with the reason; good ones get versions.
|
||||
broken = {
|
||||
"nodes": [
|
||||
*drawn["nodes"],
|
||||
@@ -88,7 +98,8 @@ def test_an_operator_connects_a_site_and_settles_its_review(api, platform, messy
|
||||
r["_record"]: f"pacientes_his:{r['num']}"
|
||||
for r in ok(api.get("/ingest/pipelines/site/nodes/his_patients/rows?limit=500"))
|
||||
}
|
||||
assert len(ok(api.get("/ingest/pipelines/site/nodes/cytology/rows?limit=500"))) == 53
|
||||
reports = sum(1 for r in truth if r["where"].startswith("ArchivosUni:"))
|
||||
assert len(ok(api.get("/ingest/pipelines/site/nodes/cytology/rows?limit=500"))) == reports
|
||||
|
||||
# Review: reports that contradict each other, rows held because their person is torn
|
||||
# (a record number shared by two patients), and persons that may be one patient.
|
||||
@@ -100,16 +111,21 @@ def test_an_operator_connects_a_site_and_settles_its_review(api, platform, messy
|
||||
|
||||
# The reviewer settles all of it, checking each case against the source documents.
|
||||
patient = messy_site.patients(platform.query)
|
||||
whose = {}
|
||||
whose, before = {}, {}
|
||||
for record, person in platform.query("select _record, person_id from bronze.n__site__persons"):
|
||||
whose.setdefault(person, set()).add(patient[record])
|
||||
before[record] = person
|
||||
# A queued person or candidate is one of its records (decisions are kept by record).
|
||||
whose |= {record: whose[person] for record, person in before.items()}
|
||||
for r in truth:
|
||||
if r.get("flipped"):
|
||||
decision = CYTOLOGY | {"record": record_of[r["where"]], "reason": "flipped HPV"}
|
||||
ok(api.post("/review/rejections", json=decision), status=201)
|
||||
merges = 0
|
||||
for entry in persons["to_settle"]:
|
||||
for c in entry["candidates"]:
|
||||
same = whose[entry["person"]] == whose[c["candidate"]]
|
||||
merges += same
|
||||
decision = {"person": entry["person"], "candidate": c["candidate"], "same": same}
|
||||
ok(api.post("/review/persons", json=decision), status=201)
|
||||
collision = {r["where"]: r for r in truth if r.get("collision")}
|
||||
@@ -121,6 +137,15 @@ def test_an_operator_connects_a_site_and_settles_its_review(api, platform, messy
|
||||
"value": collision[where]["true_record_number"],
|
||||
}
|
||||
ok(api.post("/review/corrections", json=fix), status=201)
|
||||
# A row a rule held because its value is wrong (a scan misread) is rejected after a look
|
||||
# at the document; rows of the torn person wait for the correction above.
|
||||
misread = [
|
||||
h for h in ok(api.get("/review/held", params=CYTOLOGY))
|
||||
if not any("disagree on birth date" in why for why in h["_held"])
|
||||
] # fmt: skip
|
||||
for h in misread:
|
||||
decision = CYTOLOGY | {"record": h["_record"], "reason": "misread in the scan"}
|
||||
ok(api.post("/review/rejections", json=decision), status=201)
|
||||
bad = {"record": "x", "field": "birth_date", "value": "not a date"}
|
||||
assert api.post("/review/corrections", json=bad).status_code == 422
|
||||
|
||||
@@ -136,7 +161,17 @@ def test_an_operator_connects_a_site_and_settles_its_review(api, platform, messy
|
||||
for record, person in platform.query("select _record, person_id from bronze.n__site__persons"):
|
||||
groups.setdefault(person, set()).add(patient[record])
|
||||
assert sorted(map(sorted, groups.values())) == sorted([p] for p in people)
|
||||
|
||||
# Person ids are stable: a person keeps an id her records had, and an id that went
|
||||
# away (merged by the review) resolves to the person that replaced it.
|
||||
after = dict(platform.query("select _record, person_id from bronze.n__site__persons"))
|
||||
gone = set(before.values()) - set(after.values())
|
||||
replaced = dict(platform.query("select person_id, replaced_by from silver.person_link"))
|
||||
assert merges and len(gone) == merges and set(replaced) == gone
|
||||
for old, new in replaced.items():
|
||||
assert new in set(after.values())
|
||||
assert any(before[r] == old and after[r] == new for r in before)
|
||||
assert set(after.values()) <= set(before.values()) # no person got a new id
|
||||
placed = platform.count("silver.cervical_cytology")
|
||||
assert placed == sum(
|
||||
1 for r in truth if r["entity"] == "cervical_cytology" and not r.get("flipped")
|
||||
)
|
||||
reports = sum(1 for r in truth if r["entity"] == "cervical_cytology" and not r.get("flipped"))
|
||||
assert placed == reports - len(misread)
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
"""Phase 3.5 gate: one silver, two doors. What one platform serves as FHIR, another takes
|
||||
through its FHIR door, as a standard hospital would send it, and places the same silver: the
|
||||
same values of the same studies of the same patients, and so the same indicators. The
|
||||
receiving side is configuration only: a pipeline whose fhir nodes read the sender's inbox."""
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
from fhir_checks import pages
|
||||
from test_conectar import ok, run, wait_for
|
||||
|
||||
from conftest import put_concept_map
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital"
|
||||
PIPELINES = ROOT / "tests" / "fixtures" / "pipelines"
|
||||
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
|
||||
SILVER = """
|
||||
select i.value, o.study, o.instance, o.field,
|
||||
o.value_text, o.value_num, o.value_bool, o.value_date
|
||||
from silver.observation as o
|
||||
join silver.person_identifier as i on i.person_id = o.person_id
|
||||
where i.system not like '%curp' and i.system not like '%nss'
|
||||
"""
|
||||
|
||||
|
||||
def _served(api) -> list[dict]:
|
||||
"""Everything the CaCu FHIR base serves about every patient."""
|
||||
patients = [e["resource"] for b in pages(api, "/cacu/fhir/Patient", {"_count": 200})
|
||||
for e in b.get("entry", [])] # fmt: skip
|
||||
found = list(patients)
|
||||
ids = [p["id"] for p in patients]
|
||||
for kind in ("DiagnosticReport", "Observation", "Encounter"):
|
||||
for i in range(0, len(ids), 50):
|
||||
subject = ",".join(f"Patient/{p}" for p in ids[i : i + 50])
|
||||
for b in pages(api, f"/cacu/fhir/{kind}", {"subject": subject, "_count": 200}):
|
||||
found += [e["resource"] for e in b.get("entry", [])]
|
||||
return found
|
||||
|
||||
|
||||
def _silver(platform) -> set[tuple]:
|
||||
"""Every value silver holds, by patient record number, as Python values (each engine
|
||||
returns booleans and dates its own way)."""
|
||||
|
||||
def plain(row) -> tuple:
|
||||
number, study, instance, field, text, num, flag, day = row
|
||||
num = None if num is None else float(num)
|
||||
flag = None if flag is None else bool(flag)
|
||||
return number, study, instance, field, text, num, flag, day and str(day)[:10]
|
||||
|
||||
return {plain(r) for r in platform.query(SILVER)}
|
||||
|
||||
|
||||
def test_what_one_platform_serves_another_places_through_the_fhir_door(
|
||||
api, platform, fresh_api, fresh_platform
|
||||
):
|
||||
# The sending side: the CaCu hospital, loaded through its drawn pipeline.
|
||||
put_concept_map(api, "hospital_cacu")
|
||||
drawn = (PIPELINES / "hospital_cacu.json").read_text().replace("{hospital}", str(HOSPITAL))
|
||||
ok(api.put("/ingest/pipelines/cacu", json=json.loads(drawn)))
|
||||
run(api, "cacu")
|
||||
sent = _served(api)
|
||||
bundle = {"resourceType": "Bundle", "type": "batch", "entry": [
|
||||
{"resource": r, "request": {"method": "PUT", "url": f"{r['resourceType']}/{r['id']}"}}
|
||||
for r in sent
|
||||
]} # fmt: skip
|
||||
|
||||
# The receiving side: what it sends goes nowhere without a pipeline to place it.
|
||||
door = "/cacu/fhir?sender=hospital"
|
||||
assert fresh_api.post(door, json=bundle).status_code == 404
|
||||
receiving = (PIPELINES / "fhir_door.json").read_text().replace("{sender}", "hospital")
|
||||
ok(fresh_api.put("/ingest/pipelines/hospital", json=json.loads(receiving)))
|
||||
assert (
|
||||
fresh_api.post(door, json={"resourceType": "Bundle", "type": "searchset"}).status_code
|
||||
== 422
|
||||
)
|
||||
answer = fresh_api.post(door, json=bundle)
|
||||
assert answer.status_code == 202, answer.text
|
||||
assert answer.headers["content-type"].startswith("application/fhir+json")
|
||||
assert len(answer.json()["entry"]) == len(sent)
|
||||
wait_for(fresh_api, answer.headers["location"].rsplit("/", 1)[1])
|
||||
|
||||
# One silver: every value of every study instance, by patient record number.
|
||||
placed = _silver(platform)
|
||||
assert len(placed) > 1000 and {r[1] for r in placed} >= {"cervical_cytology", "clinical_note"}
|
||||
assert _silver(fresh_platform) == placed
|
||||
assert fresh_platform.count("silver.person") == platform.count("silver.person")
|
||||
|
||||
# And so the same indicators, every measure, every semester.
|
||||
(measures,) = pages(api, "/cacu/fhir/Measure")
|
||||
for measure in [e["resource"]["id"] for e in measures["entry"]]:
|
||||
params = {"measure": measure, "reporting-period": ",".join(PERIODS),
|
||||
"event-cutoff": "2026-11-25"} # fmt: skip
|
||||
ours, theirs = (
|
||||
[e["resource"]["group"] for b in pages(a, "/cacu/fhir/MeasureReport", params)
|
||||
for e in b["entry"]]
|
||||
for a in (api, fresh_api)
|
||||
) # fmt: skip
|
||||
assert ours == theirs, measure
|
||||
|
||||
|
||||
# The same laboratory, a year later: it renamed its result column and writes its results in
|
||||
# words. Nothing in code changes: the drawing names the new column, the ConceptMap gets the
|
||||
# new spellings.
|
||||
RENAMED = {"NORMAL": "Negativo para lesión", "LIEBG": "Lesión de bajo grado",
|
||||
"LIEAG": "Lesión de alto grado"} # fmt: skip
|
||||
|
||||
|
||||
def test_a_new_label_is_a_concept_map_row_not_code(api, platform, fresh_api, fresh_platform,
|
||||
tmp_path): # fmt: skip
|
||||
put_concept_map(api, "hospital_cacu")
|
||||
drawn = (PIPELINES / "hospital_cacu.json").read_text()
|
||||
ok(
|
||||
api.put(
|
||||
"/ingest/pipelines/cacu", json=json.loads(drawn.replace("{hospital}", str(HOSPITAL)))
|
||||
)
|
||||
)
|
||||
run(api, "cacu")
|
||||
|
||||
(tmp_path / "lab").mkdir()
|
||||
for name in ("hospital_cacu.db",):
|
||||
(tmp_path / "lab" / name).write_bytes((HOSPITAL / name).read_bytes())
|
||||
with sqlite3.connect(tmp_path / "lab" / "hospital_cacu.db") as con:
|
||||
con.execute(
|
||||
"alter table citologiacervical rename column cit_celulas_escamosas to PAP_RESULT"
|
||||
)
|
||||
for old, new in RENAMED.items():
|
||||
con.execute(
|
||||
"update citologiacervical set PAP_RESULT = ? where PAP_RESULT = ?", (new, old)
|
||||
)
|
||||
codes = json.loads(
|
||||
(ROOT / "tests" / "fixtures" / "concept_maps" / "hospital_cacu.json").read_text()
|
||||
)
|
||||
bethesda = next(g for g in codes["group"] if g["target"].endswith("/bethesda"))
|
||||
bethesda["element"] += [{"code": new, "target": [{"code": {"NORMAL": "NILM", "LIEBG": "LSIL",
|
||||
"LIEAG": "HSIL"}[old], "equivalence": "equivalent"}]}
|
||||
for old, new in RENAMED.items()] # fmt: skip
|
||||
ok(fresh_api.put("/ingest/concept-maps/hospital_cacu", json=codes))
|
||||
# The source names the database's column; the map names it as bronze holds it (the
|
||||
# canvas preview shows dlt's normalised names: PAP_RESULT is pap_result).
|
||||
renamed = drawn.replace(
|
||||
'"cit_celulas_escamosas", "cit_vph_resultado"', '"PAP_RESULT", "cit_vph_resultado"'
|
||||
)
|
||||
renamed = renamed.replace('"result": "cit_celulas_escamosas"', '"result": "pap_result"')
|
||||
renamed = renamed.replace("{hospital}", str(tmp_path / "lab"))
|
||||
ok(fresh_api.put("/ingest/pipelines/cacu", json=json.loads(renamed)))
|
||||
run(fresh_api, "cacu")
|
||||
|
||||
placed = _silver(platform)
|
||||
assert any(r[3] == "result" and r[4] == "NILM" for r in placed)
|
||||
assert _silver(fresh_platform) == placed
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Phase 3.5 gate: Synthea through the FHIR door. A seeded synthetic population (Synthea,
|
||||
with the platform's cervical-screening module) arrives as a standard hospital would send it,
|
||||
and every report it holds reaches silver: nothing held, one person per patient."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from fhir_checks import pages
|
||||
from test_conectar import ok, wait_for
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
SYNTHEA = os.environ.get("SYNTHEA_JAR", "/opt/synthea/synthea.jar")
|
||||
MODULES = ROOT / "tests" / "fixtures" / "synthea" / "modules"
|
||||
DOOR = ROOT / "tests" / "fixtures" / "pipelines" / "fhir_door.json"
|
||||
STUDY = "https://isssteleon.org/fhir/CodeSystem/study"
|
||||
|
||||
|
||||
def _population(out: Path, people: int = 20) -> list[dict]:
|
||||
"""Synthea's FHIR R4 transaction Bundles, one per patient (fixed seeds)."""
|
||||
subprocess.run(
|
||||
["java", "-jar", SYNTHEA, "-p", str(people), "-s", "7", "-cs", "7", "-g", "F",
|
||||
"-a", "25-64", "-d", str(MODULES), "-m", "cervical_screening",
|
||||
"--exporter.baseDirectory", str(out), "--exporter.fhir.export", "true",
|
||||
"--exporter.hospital.fhir.export", "false",
|
||||
"--exporter.practitioner.fhir.export", "false"],
|
||||
check=True, capture_output=True, cwd=out.parent,
|
||||
) # fmt: skip
|
||||
return [json.loads(p.read_text()) for p in sorted((out / "fhir").glob("*.json"))]
|
||||
|
||||
|
||||
def _reports(bundles: list[dict], study: str) -> int:
|
||||
return sum(
|
||||
1 for b in bundles for e in b["entry"]
|
||||
if e["resource"]["resourceType"] == "DiagnosticReport"
|
||||
and any(c.get("system") == STUDY and c.get("code") == study
|
||||
for c in e["resource"].get("code", {}).get("coding", []))
|
||||
) # fmt: skip
|
||||
|
||||
|
||||
def test_a_synthea_population_comes_in_through_the_fhir_door(api, platform, tmp_path):
|
||||
bundles = _population(tmp_path / "synthea")
|
||||
patients = sum(1 for b in bundles for e in b["entry"]
|
||||
if e["resource"]["resourceType"] == "Patient") # fmt: skip
|
||||
assert patients == 20 and _reports(bundles, "cervical_cytology") > 40
|
||||
|
||||
receiving = DOOR.read_text().replace("{sender}", "synthea")
|
||||
ok(api.put("/ingest/pipelines/synthea", json=json.loads(receiving)))
|
||||
batch = {"resourceType": "Bundle", "type": "batch",
|
||||
"entry": [e for b in bundles for e in b["entry"]]} # fmt: skip
|
||||
answer = api.post("/cacu/fhir?sender=synthea", json=batch)
|
||||
assert answer.status_code == 202, answer.text[:500]
|
||||
wait_for(api, answer.headers["location"].rsplit("/", 1)[1])
|
||||
|
||||
# Nothing held, every report placed, one person per patient.
|
||||
for study in ("cervical_cytology", "cervical_biopsy"):
|
||||
assert ok(api.get("/review/held", params={"entity": study})) == [], study
|
||||
assert platform.count(f"silver.{study}") == _reports(bundles, study), study
|
||||
assert platform.count("silver.person") == patients
|
||||
(served,) = pages(api, "/cacu/fhir/Patient", {"_count": 200})
|
||||
assert served["total"] == patients
|
||||
@@ -10,6 +10,8 @@ from pathlib import Path
|
||||
import pytest
|
||||
from test_conectar import ok, run
|
||||
|
||||
from conftest import put_concept_map
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital"
|
||||
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_cacu.json"
|
||||
@@ -19,8 +21,10 @@ PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_cacu.json"
|
||||
@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)))
|
||||
put_concept_map(api, "hospital_cacu")
|
||||
ok(api.put("/ingest/pipelines/cacu", json=hospital))
|
||||
run(api, "cacu")
|
||||
put_concept_map(api, "messy_site")
|
||||
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,
|
||||
|
||||
Reference in New Issue
Block a user