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:
+75
-4
@@ -18,6 +18,7 @@ from fhir.resources.R4B.resource import Resource
|
||||
from core import catalog
|
||||
from core import fhir as f
|
||||
from core import measures as m
|
||||
from core.cacu.stages import stage_facts
|
||||
from core.domains import Domain, measures, part
|
||||
from core.follow_up import window_start
|
||||
from core.pipeline import ID_PATTERN
|
||||
@@ -149,6 +150,21 @@ def _matches(row: dict, name: str | None, identifier: str | None) -> bool:
|
||||
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)
|
||||
def search_patient(
|
||||
request: Request,
|
||||
@@ -169,6 +185,20 @@ def search_patient(
|
||||
identifier: str | None = Query(
|
||||
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>"),
|
||||
horizon: float | None = Query(None, alias="risk-horizon", description="years"),
|
||||
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
|
||||
included."""
|
||||
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)
|
||||
at = _cutoff(domain, cutoff)
|
||||
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(",")]
|
||||
if status:
|
||||
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:
|
||||
found = {r["person_id"] for r in _with_identity(domain, rows)
|
||||
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(",")]
|
||||
|
||||
|
||||
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]:
|
||||
"""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] = []
|
||||
stages = _stages(domain, persons, at)
|
||||
report_facts = _clinical(domain).REPORT_FACTS
|
||||
for study in catalog.of_domain(domain.value):
|
||||
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):
|
||||
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":
|
||||
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)
|
||||
return found
|
||||
|
||||
@@ -298,17 +364,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)
|
||||
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, 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)
|
||||
|
||||
@@ -412,6 +479,8 @@ def search_measure_report(
|
||||
) -> 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 an 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()]
|
||||
@@ -490,6 +559,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 AGE_PARAMETERS:
|
||||
continue
|
||||
if name.startswith("_") and name != "_id":
|
||||
continue
|
||||
declared = f.SEARCH_PARAMETERS.get(name)
|
||||
|
||||
+2
-1
@@ -3,7 +3,7 @@ from fastapi.exception_handlers import http_exception_handler
|
||||
from starlette.exceptions import HTTPException
|
||||
|
||||
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
|
||||
|
||||
app = FastAPI(
|
||||
@@ -19,6 +19,7 @@ app.include_router(review.router)
|
||||
app.include_router(runs.router)
|
||||
app.include_router(models.router)
|
||||
app.include_router(eeg.router)
|
||||
app.include_router(exports.router)
|
||||
app.include_router(fhir.router)
|
||||
app.include_router(users.router) # sign-in for the web app; no route requires it
|
||||
|
||||
|
||||
Reference in New Issue
Block a user