"""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)] == []