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 "result": "citologia_alto_grado"} # fmt: skip
CATEGORY = {"CACU_EU7": "resultado", "CACU_CONFIRMACION_CITOLOGIA": "biopsia_grado"} CATEGORY = {"CACU_EU7": "resultado", "CACU_CONFIRMACION_CITOLOGIA": "biopsia_grado"}
# Measures with no legacy reference fixture: checked by invariants. # Measures with no legacy reference fixture: checked by invariants.
NEW_MEASURES = {"CACU_VPH_GENOTIPO", "CACU_BIOPSIA_RESULTADOS", "CACU_BIOPSIA_SOLICITUD_CONFIRMACION", NEW_MEASURES = {
"CACU_TIEMPO_DIAGNOSTICO_CIE10", "CACU_VPP_COLPOSCOPIA", "CACU_VPP_BIOPSIA"} "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 NEW_STRATA = {"screening_round", "result_initial", "result_subsequent"} # of CACU_EU7
RESULTS = set(CODES) | set(CODES.values()) | {"ASC-US", "ASC-H", "AGC", "CIS", "adenocarcinoma"} 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: 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.""" """The screening rounds partition the evaluated patients, and each round's results do too."""
rounds = strata.get("screening_round", {}) 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 assert set(rounds) <= {"initial", "subsequent", "SIN_DATO"}, where
for rnd in ("initial", "subsequent"): for rnd in ("initial", "subsequent"):
results = strata.get(f"result_{rnd}", {}) 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"] total, den = populations["numerator"], populations["denominator"]
assert populations["initial-population"] == den and 0 <= total <= den, where assert populations["initial-population"] == den and 0 <= total <= den, where
if den: 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: else:
assert score is None and not extensions, where assert score is None and not extensions, where
levels = strata.get("histology_level", {}) 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 assert nested == sorted(nested, reverse=True), where
for cell in cytology.values(): for cell in cytology.values():
assert 0 <= cell["numerator"] <= cell["denominator"] <= den, where 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", {}) rounds = strata.get("screening_round", {})
assert sum(c["denominator"] for c in rounds.values()) == den, where assert sum(c["denominator"] for c in rounds.values()) == den, where
assert set(rounds) <= {"initial", "subsequent", "SIN_DATO"}, 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_"): if measure["name"].startswith("CACU_VPP_"):
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS), params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
"event-cutoff": CAPTURED_ON} # fmt: skip "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"] assert len(reports) == len(PERIODS), measure["name"]
for entry in reports: for entry in reports:
populations, score, extensions, strata = _report(entry, measure["name"]) populations, score, extensions, strata = _report(entry, measure["name"])
_check_ppv(populations, score, extensions, strata, _check_ppv(
(measure["name"], entry["resource"]["period"]["start"])) 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 continue
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS), params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
"event-cutoff": CAPTURED_ON} # fmt: skip "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 # Every resource the API serves, every search paged to the end, passes the HL7
# validator (offline: structure, cardinality, profiles; no terminology server). # validator (offline: structure, cardinality, profiles; no terminology server).
people = [r["person"] for r in ours[:10]] 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) resources = served(api, "/cacu/fhir", PERIODS, people)
errors, warnings = validate(resources, tmp_path) errors, warnings = validate(resources, tmp_path)
print(f"HL7 validator: {len(warnings)} warnings") print(f"HL7 validator: {len(warnings)} warnings")
+75 -4
View File
@@ -18,6 +18,7 @@ from fhir.resources.R4B.resource import Resource
from core import catalog from core import catalog
from core import fhir as f from core import fhir as f
from core import measures as m from core import measures as m
from core.cacu.stages import stage_facts
from core.domains import Domain, measures, part from core.domains import Domain, measures, part
from core.follow_up import window_start from core.follow_up import window_start
from core.pipeline import ID_PATTERN from core.pipeline import ID_PATTERN
@@ -149,6 +150,21 @@ def _matches(row: dict, name: str | None, identifier: str | None) -> bool:
return True return True
AGE_PARAMETERS = {"follow-up-age-min", "follow-up-age-max"} # CaCu's list only
def _completed_years(row: dict, on: date) -> int | None:
"""Her age in completed years on `on`; none when her birth date is missing, partial,
invalid or after `on`."""
try:
born = date.fromisoformat(str(row.get("birth_date")))
except ValueError:
return None
if born > on:
return None
return on.year - born.year - ((on.month, on.day) < (born.month, born.day))
@router.get("/Patient", responses=_OK, response_class=Response) @router.get("/Patient", responses=_OK, response_class=Response)
def search_patient( def search_patient(
request: Request, request: Request,
@@ -169,6 +185,20 @@ def search_patient(
identifier: str | None = Query( identifier: str | None = Query(
None, description="[system|]value: a CURP or record number (case ignored)" None, description="[system|]value: a CURP or record number (case ignored)"
), ),
age_min: int | None = Query(
None,
alias="follow-up-age-min",
ge=0,
le=150,
description="CaCu: completed years at the cut-off",
),
age_max: int | None = Query(
None,
alias="follow-up-age-max",
ge=0,
le=150,
description="CaCu: completed years at the cut-off",
),
sort: str = Query("-recent", alias="_sort", description="-recent or -risk-<outcome>"), sort: str = Query("-recent", alias="_sort", description="-recent or -risk-<outcome>"),
horizon: float | None = Query(None, alias="risk-horizon", description="years"), horizon: float | None = Query(None, alias="risk-horizon", description="years"),
revinclude: list[str] = Query([], alias="_revinclude", description=f"any of {REVINCLUDES}"), revinclude: list[str] = Query([], alias="_revinclude", description=f"any of {REVINCLUDES}"),
@@ -180,6 +210,10 @@ def search_patient(
filtered by status and in reading order, with what the list shows of each patient filtered by status and in reading order, with what the list shows of each patient
included.""" included."""
fu = _clinical(domain) fu = _clinical(domain)
if domain.value != "cacu" and (age_min is not None or age_max is not None):
raise HTTPException(422, "the age filters are CaCu's")
if age_min is not None and age_max is not None and age_min > age_max:
raise HTTPException(422, "follow-up-age-min exceeds follow-up-age-max")
count, offset = _page(_count, _offset) count, offset = _page(_count, _offset)
at = _cutoff(domain, cutoff) at = _cutoff(domain, cutoff)
horizon = fu.DEFAULT_HORIZON if horizon is None else horizon horizon = fu.DEFAULT_HORIZON if horizon is None else horizon
@@ -202,6 +236,11 @@ def search_patient(
rows = [r for r in rows if r["person_id"] in _id.split(",")] rows = [r for r in rows if r["person_id"] in _id.split(",")]
if status: if status:
rows = [r for r in rows if r["status"] in status.split(",")] rows = [r for r in rows if r["status"] in status.split(",")]
if age_min is not None or age_max is not None: # before the page: it counts and slices these
ages = {r["person_id"]: _completed_years(r, at) for r in rows}
rows = [r for r in rows if (n := ages[r["person_id"]]) is not None
and (age_min is None or n >= age_min)
and (age_max is None or n <= age_max)] # fmt: skip
if name or identifier: if name or identifier:
found = {r["person_id"] for r in _with_identity(domain, rows) found = {r["person_id"] for r in _with_identity(domain, rows)
if _matches(r, name, identifier)} # fmt: skip if _matches(r, name, identifier)} # fmt: skip
@@ -252,10 +291,30 @@ def _subjects(subject: str | None) -> list[str]:
return [s.removeprefix("Patient/") for s in subject.split(",")] return [s.removeprefix("Patient/") for s in subject.split(",")]
def _stages(domain: Domain, persons: list[str], at: str) -> dict[tuple[str, str], dict]:
"""CaCu: for each cytology (person, sample day), the stages of its route known by `at`."""
if domain.value != "cacu" or not persons:
return {}
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)
return {
(s["person_id"], str(s["sample_date"])[:10]): stage_facts(
s,
[b for b in biopsies if b["person_id"] == s["person_id"]],
[e for e in events if e["person_id"] == s["person_id"]],
at,
)
for s in samples
}
def _studies(domain: Domain, persons: list[str], at: str) -> list[Resource]: 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 """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.""" by `at`: its DiagnosticReport (or Encounter) and Observations, in date order."""
found: list[Resource] = [] found: list[Resource] = []
stages = _stages(domain, persons, at)
report_facts = _clinical(domain).REPORT_FACTS report_facts = _clinical(domain).REPORT_FACTS
for study in catalog.of_domain(domain.value): for study in catalog.of_domain(domain.value):
spec = catalog.studies()[study] spec = catalog.studies()[study]
@@ -268,6 +327,13 @@ def _studies(domain: Domain, persons: list[str], at: str) -> list[Resource]:
for row in reads.instances(study, persons, at): for row in reads.instances(study, persons, at):
days = facts.get((row["person_id"], str(row[first])[:10])) days = facts.get((row["person_id"], str(row[first])[:10]))
extra = [] if days is None else [f.ext("days-to-diagnosis", "integer", int(days))] extra = [] if days is None else [f.ext("days-to-diagnosis", "integer", int(days))]
if study == "cervical_cytology":
for stage, (state, day) in stages.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) found += f.instance(study, f.known(study, row, at), extra)
return found return found
@@ -298,17 +364,18 @@ SUBJECT = "Patient/<id>, comma-separated"
@router.get("/DiagnosticReport", responses=_OK, response_class=Response) @router.get("/DiagnosticReport", responses=_OK, response_class=Response)
def search_diagnostic_report(request: Request, domain: Domain, def search_diagnostic_report(request: Request, domain: Domain,
subject: str | None = Query(None, description=SUBJECT), subject: str | None = Query(None, description=SUBJECT),
cutoff: date | None = Query(None, alias="stage-cutoff"),
_count: int | None = Query(None), _count: int | None = Query(None),
_offset: int = Query(0)) -> Response: # fmt: skip _offset: int = Query(0)) -> Response: # fmt: skip
"""The domain's reports (each study of the catalog with a report), as known by the last """The domain's reports (each study of the catalog with a report), as known by the last
day with data.""" day with data (CaCu: or by `stage-cutoff`, for the stages of each sample's route)."""
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) _clinical(domain)
count, offset = _page(count, offset) 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] 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) return bundle(request, _sliced(found, count, offset), len(found), count, offset)
@@ -412,6 +479,8 @@ def search_measure_report(
) -> Response: ) -> Response:
"""The measure's summary report for each period asked for, evaluated over gold.""" """The measure's summary report for each period asked for, evaluated over gold."""
found = _measure(domain, measure.split("|")[0]) 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 an as-of time")
count, offset = _page(_count, _offset) count, offset = _page(_count, _offset)
try: try:
asked = [(p.strip(), m.Period.parse(p.strip())) for p in periods.split(",") if p.strip()] asked = [(p.strip(), m.Period.parse(p.strip())) for p in periods.split(",") if p.strip()]
@@ -490,6 +559,8 @@ def metadata(request: Request, domain: Domain) -> Response:
entry["interaction"].append({"code": "read" if rest else "search-type"}) entry["interaction"].append({"code": "read" if rest else "search-type"})
for param in route.dependant.query_params: for param in route.dependant.query_params:
name = param.alias name = param.alias
if domain.value != "cacu" and name in AGE_PARAMETERS:
continue
if name.startswith("_") and name != "_id": if name.startswith("_") and name != "_id":
continue continue
declared = f.SEARCH_PARAMETERS.get(name) declared = f.SEARCH_PARAMETERS.get(name)
+2 -1
View File
@@ -3,7 +3,7 @@ from fastapi.exception_handlers import http_exception_handler
from starlette.exceptions import HTTPException from starlette.exceptions import HTTPException
from core.domains import Domain from core.domains import Domain
from webapi import eeg, fhir, ingest, models, review, runs, sources, users from webapi import eeg, exports, fhir, ingest, models, review, runs, sources, users
from webapi.auth import caller from webapi.auth import caller
app = FastAPI( app = FastAPI(
@@ -19,6 +19,7 @@ app.include_router(review.router)
app.include_router(runs.router) app.include_router(runs.router)
app.include_router(models.router) app.include_router(models.router)
app.include_router(eeg.router) app.include_router(eeg.router)
app.include_router(exports.router)
app.include_router(fhir.router) app.include_router(fhir.router)
app.include_router(users.router) # sign-in for the web app; no route requires it app.include_router(users.router) # sign-in for the web app; no route requires it