"""Phase 2 gate, CaCu: the synthetic hospital, loaded through one drawn pipeline, gives what the current platform gives on the same hospital (the reference fixtures): its cohorts, its 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. - 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 (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 import sqlite3 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 from conftest import put_concept_map ROOT = Path(__file__).parents[2] HOSPITAL = ROOT / "tests" / "fixtures" / "hospital" REFERENCE = ROOT / "tests" / "fixtures" / "reference" / "cacu" PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_cacu.json" REFERENCE_CUTOFF = "2026-11-23" # the current platform's cohort cut-off (follow-up ends) CAPTURED_ON = "2026-11-25" # the day the indicators were captured: durations counted to it PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)] COHORTS = { "cacu_cohort_total": "cohorte_total", "cacu_cohort_surveillance": "cohorte_vigilancia", "cacu_cohort_post_treatment": "cohorte_post_tratamiento", } 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", "case": "CASO", "satisfactory": "SATISFACTORIO", "unsatisfactory": "INSATISFACTORIO", } STRATA = { "age_group": "grupo_edad", "follow_up_status": "estatus_seguimiento", "result": "citologia_alto_grado", } NEW_STRATA = {"round", "subsequent_history"} # CACU_EU7: Phase 6 and the declared history # Declared difference: the follow-up status is now what preceded each sample, not what preceded # the period's start, so these two split the same patients differently. RESTATED_STATUS = {"CACU_EU13", "CACU_EU7"} # Declared difference: the mixture models no longer read a missing HPV as negative, and the # post-colposcopy referral is stricter, so they learn from and score fewer patients. Their # numbers are held to the current platform's in models/tests, which stands the old reading in. HPV_GATED = {"cin2_pim", "cancer_pim", "cin2_pim_post_colposcopy", "cin2_pim_post_treatment"} CATEGORY = {"CACU_EU7": "resultado", "CACU_CONFIRMACION_CITOLOGIA": "biopsia_grado"} def _patients(q) -> dict[str, int]: """Each person's patient id in the hospital (for comparing only).""" with sqlite3.connect(HOSPITAL / "hospital_cacu.db") as con: number = { n.replace("-", ""): p for p, n in con.execute("select pac_id, pac_id_hospital from paciente") } rows = q("select distinct person_id, record_number from bronze.staged__identity") return {person: number[record] for person, record in 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", []): if len(s["code"]) > 1: # crossed with the category: not in the reference continue 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"] } for x in s.get("stratum", []) } 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, 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 patient = _patients(q) # Cohorts: the same patients, indexed on the same day. for ours, theirs in COHORTS.items(): sql = f"select person_id, index_date from gold.{ours} where excluded_by is null" found = {(patient[p], str(d)) for p, d in q(sql)} frame = pd.read_parquet(REFERENCE / "cohorts" / "cacu" / theirs / "dbt" / "1.parquet") frame["fecha_indice"] = frame["fecha_indice"].astype(str) assert found == set( frame[["pac_id", "fecha_indice"]].drop_duplicates().itertuples(index=False, name=None) ), ours current = json.loads((REFERENCE / "models.json").read_text()) post_colposcopy = current["cin2_pim_post_colposcopy"]["version"]["metrics"] members = q("select count(*) from gold.cacu_cohort_post_colposcopy where excluded_by is null") # Declared difference: here the referral is the cytology linked to the colposcopy, and a # low grade one counts only with a positive HPV; the current platform took any result of # the year before. Whoever leaves for that reason is the whole difference. ungraded = q( "select count(*) from gold.cacu_cohort_post_colposcopy " "where excluded_by = 'referral_not_graded'" )[0][0] theirs = post_colposcopy["n_train"] + post_colposcopy["n_test"] print("post-colposcopy members", members[0][0], "ungraded", ungraded, "current", theirs) assert members[0][0] <= theirs <= members[0][0] + ungraded # 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()) (measures,) = pages(api, "/cacu/fhir/Measure") for measure in [e["resource"] for e in measures["entry"]]: if measure["name"] not in reference: # Phase 6's (tests/test_cacu_new_measures.py) continue params = { "measure": measure["id"], "reporting-period": ",".join(PERIODS), "event-cutoff": CAPTURED_ON, } 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"]) old = {k: v for k, v in a[3].items() if k not in NEW_STRATA} if name == "CACU_DIAS_DIAGNOSTICO_TRATAMIENTO": # Declared difference: it starts at the diagnosis after the biopsy report, so # it never has more patients; a treatment that same day counts, as 0 days. assert a[0]["initial-population"] <= b[0]["initial-population"], where assert a[0]["measure-observation"] <= a[0]["initial-population"], where continue if name == "CACU_DIAS_TOMA_DIAGNOSTICO": # Declared difference: only a diagnosis before her first colposcopy counts, so # there are never more observations than the current platform's. assert all(a[0][k] <= b[0][k] for k in b[0]), where continue if name in RESTATED_STATUS: mine, was = old.pop("estatus_seguimiento", {}), dict(b[3]) theirs_status = was.pop("estatus_seguimiento", {}) assert sum(v["initial-population"] for v in mine.values()) == sum( v["initial-population"] for v in theirs_status.values() ), where assert a[0] == b[0] and old == was, where else: assert a[0] == b[0] and old == 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 # Models: one training run gives a version of each, with its two generated reports; # none is promoted without the clinical validation. wait_for(api, ok(api.post("/models/cacu/train", json={"as_of": REFERENCE_CUTOFF}))["run_id"]) names = [m["name"] for m in ok(api.get("/models/cacu"))] assert set(names) == set(current) for name in names: (version,) = ok(api.get(f"/models/cacu/{name}/versions")) assert version["reports"] == ["interpretability", "technical_validation"] for metric in ("n_train", "n_test"): was = current[name]["version"]["metrics"][metric] if name in HPV_GATED: assert version["metrics"][metric] <= was, (name, metric) else: assert version["metrics"][metric] == was, (name, metric) assert api.post(f"/models/cacu/{name}/versions/1/promote").status_code == 409 files = {"file": ("validacion.pdf", b"%PDF-1.4 clinical validation", "application/pdf")} ok(api.post(f"/models/cacu/{name}/versions/1/reports/clinical_validation", files=files)) assert ok(api.post(f"/models/cacu/{name}/versions/1/promote")) == {"champion": 1} # Risks: the champions score their cohorts with the current models' predictions. wait_for(api, ok(api.post("/models/cacu/score"))["run_id"]) for name in names: risks = pd.DataFrame( q( "select person_id, index_date, horizon_years, probability, ci_low, ci_high " f"from gold.cacu_risk where model = 'cacu.{name}'" ), columns=[ "person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high", ], ) risks["pac_id"] = risks["person_id"].map(patient) expected = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet") if name == "cin2_pim_post_colposcopy": # fixed: scored at her own index cohort = q( "select person_id, index_date from gold.cacu_cohort_post_colposcopy " "where excluded_by is null" ) assert set(map(tuple, risks[["person_id", "index_date"]].astype(str).values)) == { (p, str(d)) for p, d in cohort } continue if name in HPV_GATED: # nobody the current platform did not score assert set(zip(risks["pac_id"], risks["horizon_years"], strict=False)) <= set( zip(expected["pac_id"], expected["horizonte_anios"], strict=False) ), name continue both = risks.merge( expected, left_on=["pac_id", "horizon_years"], right_on=["pac_id", "horizonte_anios"], how="outer", indicator=True, ) assert (both["_merge"] == "both").all(), name for ours, theirs in [ ("probability", "probabilidad"), ("ci_low", "ic_bajo"), ("ci_high", "ic_alto"), ]: if theirs in both: np.testing.assert_allclose(both[ours].astype(float), both[theirs], rtol=1e-6) # The risk band now has the surveillance cohort's scored members. 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"), ] 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"]), }, } 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", ) shown["estatus"] = "POST_COLPOSCOPIA" status = item["estatus"]["codigo"] # Declared difference: after colposcopy only once she has a cytology taken after it. if status == "POST_COLPOSCOPIA" and shown["estatus"] == "PRE_COLPOSCOPIA": status = "PRE_COLPOSCOPIA" assert shown == {**{k: item[k] for k in shown}, "estatus": status} # 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)] == []