Expose CaCu stages and follow-up filters

Adapted from 1b5fa74 and subsequent CaCu integration, including Edgar Hinojosas changes d6f79ef and f7faab7.

Co-authored-by: edgar <edgar.hinojosas@uanl.edu.mx>
This commit is contained in:
Angel Capetillo Zavala
2026-11-30 16:01:16 -06:00
parent 2808f955c4
commit a8268b0492
3 changed files with 147 additions and 12 deletions
+70 -7
View File
@@ -56,8 +56,15 @@ STRATA = {"age_group": "grupo_edad", "follow_up_status": "estatus_seguimiento",
"result": "citologia_alto_grado"} # fmt: skip
CATEGORY = {"CACU_EU7": "resultado", "CACU_CONFIRMACION_CITOLOGIA": "biopsia_grado"}
# Measures with no legacy reference fixture: checked by invariants.
NEW_MEASURES = {"CACU_VPH_GENOTIPO", "CACU_BIOPSIA_RESULTADOS", "CACU_BIOPSIA_SOLICITUD_CONFIRMACION",
"CACU_TIEMPO_DIAGNOSTICO_CIE10", "CACU_VPP_COLPOSCOPIA", "CACU_VPP_BIOPSIA"}
NEW_MEASURES = {
"CACU_VPH",
"CACU_VPH_GENOTIPO",
"CACU_BIOPSIA_RESULTADOS",
"CACU_BIOPSIA_SOLICITUD_CONFIRMACION",
"CACU_TIEMPO_DIAGNOSTICO_CIE10",
"CACU_VPP_COLPOSCOPIA",
"CACU_VPP_BIOPSIA",
}
NEW_STRATA = {"screening_round", "result_initial", "result_subsequent"} # of CACU_EU7
RESULTS = set(CODES) | set(CODES.values()) | {"ASC-US", "ASC-H", "AGC", "CIS", "adenocarcinoma"}
@@ -69,7 +76,9 @@ def _count(stratum: dict, key: str, code: str = "initial-population") -> int:
def _check_eu7_rounds(populations: dict, strata: dict, where: tuple) -> None:
"""The screening rounds partition the evaluated patients, and each round's results do too."""
rounds = strata.get("screening_round", {})
assert sum(c["initial-population"] for c in rounds.values()) == populations["initial-population"], where
assert (
sum(c["initial-population"] for c in rounds.values()) == populations["initial-population"]
), where
assert set(rounds) <= {"initial", "subsequent", "SIN_DATO"}, where
for rnd in ("initial", "subsequent"):
results = strata.get(f"result_{rnd}", {})
@@ -82,7 +91,10 @@ def _check_ppv(populations: dict, score, extensions: dict, strata: dict, where:
total, den = populations["numerator"], populations["denominator"]
assert populations["initial-population"] == den and 0 <= total <= den, where
if den:
assert score == pytest.approx(total / den) and 0 <= extensions["ic-bajo"] <= score <= extensions["ic-alto"] <= 1, where
assert (
score == pytest.approx(total / den)
and 0 <= extensions["ic-bajo"] <= score <= extensions["ic-alto"] <= 1
), where
else:
assert score is None and not extensions, where
levels = strata.get("histology_level", {})
@@ -96,6 +108,13 @@ def _check_ppv(populations: dict, score, extensions: dict, strata: dict, where:
assert nested == sorted(nested, reverse=True), where
for cell in cytology.values():
assert 0 <= cell["numerator"] <= cell["denominator"] <= den, where
hpv = strata.get("referral_hpv", {})
assert set(hpv) <= {"positive", "negative", "hpv_16", "hpv_18", "SIN_DATO"}, where
for cell in hpv.values():
assert 0 <= cell["numerator"] <= cell["denominator"] <= den, where
# a patient is in "no data" or in a result of her referring cytology, never both
decided = sum(_count(hpv, g, "denominator") for g in ("SIN_DATO", "positive", "negative"))
assert decided == den, where
rounds = strata.get("screening_round", {})
assert sum(c["denominator"] for c in rounds.values()) == den, where
assert set(rounds) <= {"initial", "subsequent", "SIN_DATO"}, where
@@ -160,12 +179,46 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path)
if measure["name"].startswith("CACU_VPP_"):
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
"event-cutoff": CAPTURED_ON} # fmt: skip
reports = [e for b in pages(api, "/cacu/fhir/MeasureReport", params) for e in b["entry"]]
reports = [
e for b in pages(api, "/cacu/fhir/MeasureReport", params) for e in b["entry"]
]
assert len(reports) == len(PERIODS), measure["name"]
for entry in reports:
populations, score, extensions, strata = _report(entry, measure["name"])
_check_ppv(populations, score, extensions, strata,
(measure["name"], entry["resource"]["period"]["start"]))
_check_ppv(
populations,
score,
extensions,
strata,
(measure["name"], entry["resource"]["period"]["start"]),
)
if measure["name"] == "CACU_VPH": # the patients' latest HPV sample, one each
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
"event-cutoff": CAPTURED_ON} # fmt: skip
for b in pages(api, "/cacu/fhir/MeasureReport", params):
for entry in b["entry"]:
populations, _, _, strata = _report(entry, measure["name"])
where = (measure["name"], entry["resource"]["period"]["start"])
total = populations["initial-population"]
category = strata.get(
"banda", {}
) # _report names the category so; none: nobody
assert set(category) <= {"positive", "negative"}, where
assert sum(c["initial-population"] for c in category.values()) == total, (
where
)
for name in ("hpv_16", "hpv_18"):
assert set(strata.get(name, {})) <= {"positive", "negative"}, where
assert (
sum(c["initial-population"] for c in strata.get(name, {}).values())
<= total
), where
rounds = sum(
c["initial-population"]
for k in ("hpv_initial", "hpv_subsequent")
for c in strata.get(k, {}).values()
)
assert rounds <= total, where
continue
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
"event-cutoff": CAPTURED_ON} # fmt: skip
@@ -269,6 +322,16 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path)
# 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]]
# The stages of each cytology's route, known by the cut-off, are the report's extensions.
stage_params = [("subject", ",".join(f"Patient/{p}" for p in people)), ("stage-cutoff", cutoff)]
stage_reports = [e["resource"] for b in pages(api, "/cacu/fhir/DiagnosticReport", stage_params)
for e in b["entry"]] # fmt: skip
stages = [x["url"].rsplit("/", 1)[1] for r in stage_reports for x in r.get("extension", [])
if "/stage-" in x["url"]] # fmt: skip
known = {
f"stage-{s}-{k}" for s in ("colposcopy", "biopsy", "diagnosis") for k in ("state", "date")
}
assert stages and set(stages) <= known
resources = served(api, "/cacu/fhir", PERIODS, people)
errors, warnings = validate(resources, tmp_path)
print(f"HL7 validator: {len(warnings)} warnings")