CaCu FHIR: follow-up search and filters, stage extensions, and the referral PPV contract test

Patient search accepts follow-up age bounds and a partial name or identifier over the
whole query. Diagnostic reports carry the stage states and dates up to a cut-off. The
integration test expects the referral PPV measures and the screening-round strata of the
cytology distribution, and checks their counts, intervals and nesting.
This commit is contained in:
Angel Capetillo Zavala
2026-11-27 18:42:48 -06:00
parent 9c89c9e10d
commit 1b5fa748af
2 changed files with 109 additions and 5 deletions
+61 -1
View File
@@ -55,6 +55,50 @@ CODES = { # platform code -> the current platform's
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_STRATA = {"screening_round", "result_initial", "result_subsequent"} # of CACU_EU7
RESULTS = set(CODES) | set(CODES.values()) | {"ASC-US", "ASC-H", "AGC", "CIS", "adenocarcinoma"}
def _count(stratum: dict, key: str, code: str = "initial-population") -> int:
return stratum.get(key, {}).get(code, 0)
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 set(rounds) <= {"initial", "subsequent", "SIN_DATO"}, where
for rnd in ("initial", "subsequent"):
results = strata.get(f"result_{rnd}", {})
assert sum(c["initial-population"] for c in results.values()) == _count(rounds, rnd), where
assert set(results) <= RESULTS, where
def _check_ppv(populations: dict, score, extensions: dict, strata: dict, where: tuple) -> None:
"""A referral PPV: counts of patients, one denominator, nested numerators and groups."""
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
else:
assert score is None and not extensions, where
levels = strata.get("histology_level", {})
if den:
assert set(levels) == {"LIEBG+", "LIEAG+", "invasive"}, where
assert all(c["denominator"] == den for c in levels.values()), where
low, high, invasive = (levels[k]["numerator"] for k in ("LIEBG+", "LIEAG+", "invasive"))
assert total == low >= high >= invasive >= 0, where
cytology = strata.get("referral_cytology", {})
nested = [_count(cytology, g, "denominator") for g in ("ASCUS+", "LSIL+", "HSIL+")]
assert nested == sorted(nested, reverse=True), where
for cell in cytology.values():
assert 0 <= cell["numerator"] <= cell["denominator"] <= 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
def _patients(q) -> dict[str, int]:
@@ -107,7 +151,20 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path)
# (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")
published = {e["resource"]["name"] for e in measures["entry"]}
assert published == set(reference) | NEW_MEASURES
for measure in [e["resource"] for e in measures["entry"]]:
if measure["name"] not in reference: # New measures have no legacy fixture.
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"]]
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"]))
continue
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
"event-cutoff": CAPTURED_ON} # fmt: skip
found = [e for b in pages(api, "/cacu/fhir/MeasureReport", params) for e in b["entry"]]
@@ -116,7 +173,10 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path)
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
legacy = {k: v for k, v in a[3].items() if name != "CACU_EU7" or k not in NEW_STRATA}
assert a[0] == b[0] and legacy == b[3], where
if name == "CACU_EU7": # the new round breakdowns leave every legacy figure as it was
_check_eu7_rounds(a[0], a[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
+48 -4
View File
@@ -140,6 +140,9 @@ def search_patient(
None, alias="follow-up-cutoff", description="default: the last day with data"
),
status: str | None = Query(None, alias="follow-up-status"),
age_min: int | None = Query(None, alias="follow-up-age-min", ge=0, le=150),
age_max: int | None = Query(None, alias="follow-up-age-max", ge=0, le=150),
search: str | None = Query(None, alias="follow-up-search", max_length=200),
sort: str = Query("-recent", alias="_sort", description="-recent or -risk-<outcome>"),
horizon: float | None = Query(None, alias="risk-horizon", description="years"),
revinclude: list[str] = Query([], alias="_revinclude", description=f"any of {REVINCLUDES}"),
@@ -151,6 +154,8 @@ def search_patient(
filtered by status and in reading order, with what the list shows of each patient
included."""
fu = _clinical(domain)
if domain.value != "cacu" and (age_min is not None or age_max is not None or search):
raise HTTPException(422, "age and text filters are available for CaCu only")
count, offset = _page(_count, _offset)
at = _cutoff(domain, cutoff)
horizon = fu.DEFAULT_HORIZON if horizon is None else horizon
@@ -173,6 +178,23 @@ def search_patient(
]
if status:
rows = [r for r in rows if r["status"] in status.split(",")]
if age_min is not None and age_max is not None and age_min > age_max:
raise HTTPException(422, "minimum age exceeds maximum age")
if age_min is not None or age_max is not None:
def age(row):
try:
birth = date.fromisoformat(str(row.get("birth_date")))
if birth > at:
return None
return at.year - birth.year - ((at.month, at.day) < (birth.month, birth.day))
except (ValueError, TypeError):
return None
rows = [r for r in rows if (n := age(r)) is not None
and (age_min is None or n >= age_min) and (age_max is None or n <= age_max)]
if search and (query := " ".join(search.split()).casefold()):
identities = _with_identity(domain, rows)
rows = [r for r in identities if any(query in " ".join(str(v).split()).casefold()
for v in [r["person_id"], *r["names"], *(i[1] for i in r["identifiers"])])]
persons = [r["person_id"] for r in rows]
risks: dict[str, list[dict]] = {}
if window is not None and sort != "-recent" or "RiskAssessment:subject" in revinclude:
@@ -223,6 +245,18 @@ 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
by `at`: its DiagnosticReport (or Encounter) and Observations, in date order."""
found: list[Resource] = []
stage_map = {}
if domain.value == 'cacu' and persons:
from core.cacu.stages import stage_facts
params = {'persons': persons, 'cutoff': at}
samples = reads.rows('cacu', 'stage_samples', **params)
biopsies = reads.rows('cacu', 'stage_biopsies', **params)
events = reads.rows('cacu', 'stage_events', **params)
for sample in samples:
person = sample['person_id']
stage_map[(person, str(sample['sample_date'])[:10])] = stage_facts(
sample, [b for b in biopsies if b['person_id'] == person],
[e for e in events if e['person_id'] == person], at)
report_facts = _clinical(domain).REPORT_FACTS
for study in catalog.of_domain(domain.value):
spec = catalog.studies()[study]
@@ -235,6 +269,11 @@ def _studies(domain: Domain, persons: list[str], at: str) -> list[Resource]:
for row in reads.instances(study, persons, at):
days = facts.get((row["person_id"], str(row[first])[:10]))
extra = [] if days is None else [f.ext("days-to-diagnosis", "integer", int(days))]
if study == 'cervical_cytology' and domain.value == 'cacu':
for stage, (state, day) in stage_map.get((row['person_id'], str(row[first])[:10]), {}).items():
extra.append(f.ext(f'stage-{stage}-state', 'code', state))
if day:
extra.append(f.ext(f'stage-{stage}-date', 'date', day))
found += f.instance(study, f.known(study, row, at), extra)
return found
@@ -265,17 +304,18 @@ SUBJECT = "Patient/<id>, comma-separated"
@router.get("/DiagnosticReport", responses=_OK, response_class=Response)
def search_diagnostic_report(request: Request, domain: Domain,
subject: str | None = Query(None, description=SUBJECT),
cutoff: date | None = Query(None, alias="stage-cutoff"),
_count: int | None = Query(None),
_offset: int = Query(0)) -> Response: # fmt: skip
"""The domain's reports (each study of the catalog with a report), as known by the last
day with data."""
return _study_search("DiagnosticReport", request, domain, subject, _count, _offset)
return _study_search("DiagnosticReport", request, domain, subject, _count, _offset, cutoff)
def _study_search(kind: str, request, domain, subject, count, offset) -> Response:
def _study_search(kind: str, request, domain, subject, count, offset, cutoff=None) -> Response:
_clinical(domain)
count, offset = _page(count, offset)
persons, at = _subjects(subject), _cutoff(domain, None).isoformat()
persons, at = _subjects(subject), _cutoff(domain, cutoff).isoformat()
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)
@@ -371,13 +411,15 @@ def search_measure_report(
None, alias="as-of", description="count only what was known by then"
),
event_cutoff: date | None = Query(
None, alias="event-cutoff", description="durations count to this day"
None, alias="event-cutoff", description="count events through this day"
),
_count: int | None = Query(None),
_offset: int = Query(0),
) -> Response:
"""The measure's summary report for each period asked for, evaluated over gold."""
found = _measure(domain, measure.split("|")[0])
if as_of is not None and not found.supports_as_of:
raise HTTPException(422, "This measure cannot reconstruct knowledge at a historical as-of time")
count, offset = _page(_count, _offset)
try:
asked = [(p.strip(), m.Period.parse(p.strip())) for p in periods.split(",") if p.strip()]
@@ -455,6 +497,8 @@ def metadata(request: Request, domain: Domain) -> Response:
entry["interaction"].append({"code": "read" if rest else "search-type"})
for param in route.dependant.query_params:
name = param.alias
if domain.value != "cacu" and name in {"follow-up-age-min", "follow-up-age-max", "follow-up-search"}:
continue
if name.startswith("_") and name != "_id":
continue
declared = f.SEARCH_PARAMETERS.get(name)