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:
+48
-4
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user