TEA follow-up: Patient search with TEA filters and $eeg-summary
Use _patient_rows and shared Query declarations for follow-up selection. Validate filters with an empty row before reading candidates, and use doseq for repeated values in paging links. Keep operation routes out of the metadata scan for read and search interactions. Use _follow_up_gate to compare the 29 captured queries by normalized record number, scalar counts and metrics.
This commit is contained in:
@@ -8,6 +8,7 @@ The hospital (2 GB) is kept outside git; its path is TEA_HOSPITAL (default
|
|||||||
~/isssteleon-data), and its hash is the manifest's.
|
~/isssteleon-data), and its hash is the manifest's.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import gzip
|
||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
@@ -16,6 +17,7 @@ import time
|
|||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from datetime import date
|
from datetime import date
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from urllib.parse import parse_qsl
|
||||||
|
|
||||||
import dagster as dg
|
import dagster as dg
|
||||||
import pytest
|
import pytest
|
||||||
@@ -332,12 +334,80 @@ def _association_gate(api, platform):
|
|||||||
assert ref == pytest.approx(row["rap_probabilidad_referencia"], abs=1e-4), key
|
assert ref == pytest.approx(row["rap_probabilidad_referencia"], abs=1e-4), key
|
||||||
|
|
||||||
|
|
||||||
|
def _follow_up_gate(api, platform):
|
||||||
|
with gzip.open(REFERENCE / "follow_up.json.gz", "rt") as file:
|
||||||
|
reference = json.load(file)
|
||||||
|
persons = {
|
||||||
|
int(number.removeprefix("N")): person
|
||||||
|
for person, number in platform.query(
|
||||||
|
"select distinct person_id, record_number from bronze.staged__identity"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
params_map = {
|
||||||
|
"etapa": "tea-step", "status": "follow-up-status", "resultado-eeg": "tea-eeg-result",
|
||||||
|
"modelo": "tea-model", "grupo-edad": "tea-age-group", "sexo": "tea-sex",
|
||||||
|
"mchat": "tea-mchat", "css": "tea-css",
|
||||||
|
} # fmt: skip
|
||||||
|
values = {
|
||||||
|
**CODES, "NEUROPEDIATRIA": "neurology", "anormal": "abnormal",
|
||||||
|
"sin-eeg-valido": "no_valid_eeg",
|
||||||
|
"si": "yes",
|
||||||
|
} # fmt: skip
|
||||||
|
counts = {
|
||||||
|
"con_eeg_valido": "valid", "sin_eeg_valido": "not_valid",
|
||||||
|
"normales": "normal", "anormales": "abnormal",
|
||||||
|
} # fmt: skip
|
||||||
|
for query, expected in reference.items():
|
||||||
|
params = []
|
||||||
|
for name, value in parse_qsl(query):
|
||||||
|
if name == "date":
|
||||||
|
dates = {"ge": "follow-up-start", "le": "follow-up-cutoff"}
|
||||||
|
params.append((dates[value[:2]], value[2:]))
|
||||||
|
else:
|
||||||
|
params.append((params_map[name], values.get(value, value)))
|
||||||
|
resources = [entry["resource"] for entry in expected["episodes"]["body"].get("entry", [])]
|
||||||
|
patients = {
|
||||||
|
f"Patient/{r['id']}": persons[int(next(
|
||||||
|
identifier["value"].removeprefix("N-") for identifier in r["identifier"]
|
||||||
|
if identifier["system"].endswith("/expediente")
|
||||||
|
))]
|
||||||
|
for r in resources if r["resourceType"] == "Patient"
|
||||||
|
} # fmt: skip
|
||||||
|
children = {
|
||||||
|
patients[r["patient"]["reference"]]
|
||||||
|
for r in resources if r["resourceType"] == "EpisodeOfCare"
|
||||||
|
} # fmt: skip
|
||||||
|
bundles = pages(api, "/tea/fhir/Patient", params)
|
||||||
|
assert {entry["resource"]["id"] for bundle in bundles
|
||||||
|
for entry in bundle.get("entry", [])} == children, query # fmt: skip
|
||||||
|
|
||||||
|
parameters = {}
|
||||||
|
alterations = {}
|
||||||
|
for parameter in expected["summary"]["body"]["parameter"]:
|
||||||
|
name = parameter["name"]
|
||||||
|
if name == "por_alteracion":
|
||||||
|
parts = {p["name"]: p for p in parameter["part"]}
|
||||||
|
metric = METRICS[parts["alteracion"]["valueCode"].upper()]
|
||||||
|
alterations[metric] = parts["pacientes"]["valueInteger"]
|
||||||
|
else:
|
||||||
|
parameters[counts[name]] = parameter["valueInteger"]
|
||||||
|
found = ok(api.get("/tea/fhir/Patient/$eeg-summary", params=params))
|
||||||
|
assert found["resourceType"] == "Parameters", query
|
||||||
|
assert {p["name"]: p["valueInteger"] for p in found["parameter"]
|
||||||
|
if p["name"] != "by_alteration"} == parameters, query # fmt: skip
|
||||||
|
assert {
|
||||||
|
p["part"][0]["valueCode"]: p["part"][1]["valueInteger"]
|
||||||
|
for p in found["parameter"] if p["name"] == "by_alteration"
|
||||||
|
} == alterations, query # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
def test_tea_from_the_hospital_to_indicators(api, scored_hospital, monkeypatch):
|
def test_tea_from_the_hospital_to_indicators(api, scored_hospital, monkeypatch):
|
||||||
_association_gate(api, scored_hospital)
|
_association_gate(api, scored_hospital)
|
||||||
|
|
||||||
# Indicators, from the platform's own EEG verdicts and, for M30, the alterations the
|
# Indicators, from the platform's own EEG verdicts and, for M30, the alterations the
|
||||||
# promoted curves found (as the current platform's were captured: curves trained).
|
# promoted curves found (as the current platform's were captured: curves trained).
|
||||||
indicators(api)
|
indicators(api)
|
||||||
|
_follow_up_gate(api, scored_hospital)
|
||||||
|
|
||||||
# The EEG pages: every study with its verdict, and a valid one's metrics with their scores.
|
# The EEG pages: every study with its verdict, and a valid one's metrics with their scores.
|
||||||
listed = ok(api.get("/tea/eegs"))
|
listed = ok(api.get("/tea/eegs"))
|
||||||
|
|||||||
+137
-37
@@ -5,6 +5,7 @@ counting a few thousand rows (measures) and ordering the follow-up list."""
|
|||||||
|
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from typing import Annotated, Any
|
from typing import Annotated, Any
|
||||||
|
from urllib.parse import urlencode
|
||||||
|
|
||||||
from dagster_graphql import DagsterGraphQLClient
|
from dagster_graphql import DagsterGraphQLClient
|
||||||
from fastapi import APIRouter, Body, Depends, HTTPException, Query, Request
|
from fastapi import APIRouter, Body, Depends, HTTPException, Query, Request
|
||||||
@@ -12,6 +13,7 @@ from fastapi.responses import Response
|
|||||||
from fhir.resources.R4B.bundle import Bundle
|
from fhir.resources.R4B.bundle import Bundle
|
||||||
from fhir.resources.R4B.capabilitystatement import CapabilityStatement
|
from fhir.resources.R4B.capabilitystatement import CapabilityStatement
|
||||||
from fhir.resources.R4B.operationoutcome import OperationOutcome
|
from fhir.resources.R4B.operationoutcome import OperationOutcome
|
||||||
|
from fhir.resources.R4B.parameters import Parameters
|
||||||
from fhir.resources.R4B.resource import Resource
|
from fhir.resources.R4B.resource import Resource
|
||||||
|
|
||||||
from core import catalog
|
from core import catalog
|
||||||
@@ -73,7 +75,9 @@ def bundle(request: Request, matches: list[Resource], total: int, count: int, of
|
|||||||
base = str(request.base_url).rstrip("/") + request.url.path.rsplit("/", 1)[0]
|
base = str(request.base_url).rstrip("/") + request.url.path.rsplit("/", 1)[0]
|
||||||
|
|
||||||
def link(relation: str, at: int) -> dict:
|
def link(relation: str, at: int) -> dict:
|
||||||
url = request.url.include_query_params(**(applied or {}), _offset=at, _count=count)
|
params = {**(applied or {}), "_offset": at, "_count": count}
|
||||||
|
query = [(k, v) for k, v in request.query_params.multi_items() if k not in params]
|
||||||
|
url = request.url.replace(query=urlencode([*query, *params.items()], doseq=True))
|
||||||
return {"relation": relation, "url": str(url)}
|
return {"relation": relation, "url": str(url)}
|
||||||
|
|
||||||
links = [link("self", offset)]
|
links = [link("self", offset)]
|
||||||
@@ -95,6 +99,52 @@ def _sliced(found: list, count: int, offset: int) -> list:
|
|||||||
# --- Patient ---------------------------------------------------------------------------------
|
# --- Patient ---------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
_WINDOW = Query(
|
||||||
|
None,
|
||||||
|
alias="follow-up-window",
|
||||||
|
description="months: the domain's follow-up list over that window up to the cut-off",
|
||||||
|
)
|
||||||
|
_START = Query(
|
||||||
|
None,
|
||||||
|
alias="follow-up-start",
|
||||||
|
description="explicit window start that overrides follow-up-window",
|
||||||
|
)
|
||||||
|
_CUTOFF = Query(None, alias="follow-up-cutoff", description="default: the last day with data")
|
||||||
|
_STATUS = Query(None, alias="follow-up-status")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/Patient/$eeg-summary", responses=_OK, response_class=Response)
|
||||||
|
def eeg_summary(
|
||||||
|
request: Request,
|
||||||
|
domain: Domain,
|
||||||
|
window: int | None = _WINDOW,
|
||||||
|
start: date | None = _START,
|
||||||
|
cutoff: date | None = _CUTOFF,
|
||||||
|
status: str | None = _STATUS,
|
||||||
|
) -> Response:
|
||||||
|
"""EEG counts for the follow-up list. Without a window or start, use the whole history."""
|
||||||
|
fu = _clinical(domain)
|
||||||
|
if not hasattr(fu, "summary"):
|
||||||
|
return outcome(404, f"no EEG summary for {domain.value}")
|
||||||
|
at = _cutoff(domain, cutoff)
|
||||||
|
try:
|
||||||
|
rows, _, _ = _patient_rows(request, domain, fu, at, window, start, cutoff, status,
|
||||||
|
whole_history=True) # fmt: skip
|
||||||
|
except ValueError as exc:
|
||||||
|
return outcome(422, str(exc))
|
||||||
|
counts = fu.summary(rows)
|
||||||
|
parameters = [
|
||||||
|
{"name": name, "valueInteger": counts[name]}
|
||||||
|
for name in ("valid", "not_valid", "normal", "abnormal")
|
||||||
|
]
|
||||||
|
for entry in counts["by_alteration"]:
|
||||||
|
parameters.append({"name": "by_alteration", "part": [
|
||||||
|
{"name": "alteration", "valueCode": entry["alteration"]},
|
||||||
|
{"name": "patients", "valueInteger": entry["patients"]},
|
||||||
|
]}) # fmt: skip
|
||||||
|
return fhir(Parameters(parameter=parameters))
|
||||||
|
|
||||||
|
|
||||||
@router.get("/Patient/{id}", responses=_OK, response_class=Response)
|
@router.get("/Patient/{id}", responses=_OK, response_class=Response)
|
||||||
def read_patient(domain: Domain, id: str) -> Response:
|
def read_patient(domain: Domain, id: str) -> Response:
|
||||||
fu = _clinical(domain)
|
fu = _clinical(domain)
|
||||||
@@ -131,15 +181,10 @@ def search_patient(
|
|||||||
request: Request,
|
request: Request,
|
||||||
domain: Domain,
|
domain: Domain,
|
||||||
_id: str | None = Query(None, alias="_id"),
|
_id: str | None = Query(None, alias="_id"),
|
||||||
window: int | None = Query(
|
window: int | None = _WINDOW,
|
||||||
None,
|
start: date | None = _START,
|
||||||
alias="follow-up-window",
|
cutoff: date | None = _CUTOFF,
|
||||||
description="months: the domain's follow-up list over that window up to the cut-off",
|
status: str | None = _STATUS,
|
||||||
),
|
|
||||||
cutoff: date | None = Query(
|
|
||||||
None, alias="follow-up-cutoff", description="default: the last day with data"
|
|
||||||
),
|
|
||||||
status: str | None = Query(None, alias="follow-up-status"),
|
|
||||||
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}"),
|
||||||
@@ -147,49 +192,93 @@ def search_patient(
|
|||||||
_count: int | None = Query(None),
|
_count: int | None = Query(None),
|
||||||
_offset: int = Query(0),
|
_offset: int = Query(0),
|
||||||
) -> Response:
|
) -> Response:
|
||||||
"""Patients; with `follow-up-window`, the domain's follow-up list at the cut-off,
|
"""Patients, or the domain's follow-up list selected by window or start.
|
||||||
filtered by status and in reading order, with what the list shows of each patient
|
|
||||||
included."""
|
For TEA, a cutoff or a TEA filter also selects the follow-up list. Patients without
|
||||||
|
follow-up episodes appear only in the plain search.
|
||||||
|
"""
|
||||||
fu = _clinical(domain)
|
fu = _clinical(domain)
|
||||||
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
|
||||||
persons_rows = reads.rows(domain.value, "persons")
|
try:
|
||||||
if window is None:
|
rows, listed, applied = _patient_rows(
|
||||||
rows = [{**r, "status": fu.status(r, at)} for r in persons_rows]
|
request, domain, fu, at, window, start, cutoff, status, sort, _id
|
||||||
if _id:
|
)
|
||||||
rows = [r for r in rows if r["person_id"] in _id.split(",")]
|
except ValueError as exc:
|
||||||
else:
|
return outcome(422, str(exc))
|
||||||
if window not in fu.WINDOWS:
|
|
||||||
raise HTTPException(422, f"follow-up-window is one of {fu.WINDOWS}")
|
|
||||||
if sort not in fu.SORTS:
|
|
||||||
raise HTTPException(422, f"_sort is one of {fu.SORTS}")
|
|
||||||
start = window_start(at, window)
|
|
||||||
params = {"start": start.isoformat(), "cutoff": at.isoformat()}
|
|
||||||
person = {r["person_id"]: r for r in persons_rows}
|
|
||||||
rows = [
|
|
||||||
{**person[r["person_id"]], **r}
|
|
||||||
for r in fu.listed(reads.rows(domain.value, "follow_up", **params), start, at)
|
|
||||||
]
|
|
||||||
if status:
|
|
||||||
rows = [r for r in rows if r["status"] in status.split(",")]
|
|
||||||
persons = [r["person_id"] for r in rows]
|
persons = [r["person_id"] for r in rows]
|
||||||
risks: dict[str, list[dict]] = {}
|
risks: dict[str, list[dict]] = {}
|
||||||
if window is not None and sort != "-recent" or "RiskAssessment:subject" in revinclude:
|
if listed and sort != "-recent" or "RiskAssessment:subject" in revinclude:
|
||||||
for r in reads.rows(domain.value, "risk", persons=persons):
|
for r in reads.rows(domain.value, "risk", persons=persons):
|
||||||
risks.setdefault(r["person_id"], []).append(r)
|
risks.setdefault(r["person_id"], []).append(r)
|
||||||
if window is not None:
|
if listed:
|
||||||
rows = fu.ordered(rows, sort, risks, horizon)
|
rows = fu.ordered(rows, sort, risks, horizon)
|
||||||
page = _sliced(rows, count, offset)
|
page = _sliced(rows, count, offset)
|
||||||
mine = {r["person_id"] for r in page}
|
mine = {r["person_id"] for r in page}
|
||||||
included = _included(domain, revinclude, include, sorted(mine), at,
|
included = _included(domain, revinclude, include, sorted(mine), at,
|
||||||
{p: v for p, v in risks.items() if p in mine}) # fmt: skip
|
{p: v for p, v in risks.items() if p in mine}) # fmt: skip
|
||||||
applied = {"follow-up-cutoff": at.isoformat()} if window is not None else None
|
|
||||||
patients = [f.patient(r, fu.STATUS_SYSTEM) for r in _with_identity(domain, page)]
|
patients = [f.patient(r, fu.STATUS_SYSTEM) for r in _with_identity(domain, page)]
|
||||||
return bundle(request, patients, len(rows), count, offset, included,
|
return bundle(request, patients, len(rows), count, offset, included,
|
||||||
applied) # fmt: skip
|
applied) # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def _patient_rows(
|
||||||
|
request: Request,
|
||||||
|
domain: Domain,
|
||||||
|
fu,
|
||||||
|
at: date,
|
||||||
|
window: int | None,
|
||||||
|
start: date | None,
|
||||||
|
cutoff: date | None,
|
||||||
|
status: str | None,
|
||||||
|
sort: str = "-recent",
|
||||||
|
_id: str | None = None,
|
||||||
|
*,
|
||||||
|
whole_history: bool = False,
|
||||||
|
) -> tuple[list[dict], bool, dict]:
|
||||||
|
filters = {
|
||||||
|
name: request.query_params.getlist(name)
|
||||||
|
for name in getattr(fu, "FILTERS", ())
|
||||||
|
if name in request.query_params
|
||||||
|
}
|
||||||
|
if filters:
|
||||||
|
fu.matches({}, filters) # Validate values even when the selection has no rows.
|
||||||
|
listed = (
|
||||||
|
whole_history
|
||||||
|
or start is not None
|
||||||
|
or window is not None
|
||||||
|
or bool(filters)
|
||||||
|
or (hasattr(fu, "FILTERS") and cutoff is not None)
|
||||||
|
)
|
||||||
|
persons = reads.rows(domain.value, "persons")
|
||||||
|
applied = {}
|
||||||
|
if listed:
|
||||||
|
if sort not in fu.SORTS:
|
||||||
|
raise HTTPException(422, f"_sort is one of {fu.SORTS}")
|
||||||
|
if start is None and window is not None:
|
||||||
|
if window not in fu.WINDOWS:
|
||||||
|
raise HTTPException(422, f"follow-up-window is one of {fu.WINDOWS}")
|
||||||
|
start = window_start(at, window)
|
||||||
|
start = start or date.min
|
||||||
|
params = {"start": start.isoformat(), "cutoff": at.isoformat()}
|
||||||
|
person = {r["person_id"]: r for r in persons}
|
||||||
|
rows = [
|
||||||
|
{**person[r["person_id"]], **r}
|
||||||
|
for r in fu.listed(reads.rows(domain.value, "follow_up", **params), start, at)
|
||||||
|
]
|
||||||
|
applied = {"follow-up-cutoff": at.isoformat(), **filters}
|
||||||
|
else:
|
||||||
|
rows = [{**r, "status": fu.status(r, at)} for r in persons]
|
||||||
|
if _id:
|
||||||
|
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 filters:
|
||||||
|
rows = [r for r in rows if fu.matches(r, filters)]
|
||||||
|
return rows, listed, applied
|
||||||
|
|
||||||
|
|
||||||
def _included(domain: Domain, revinclude: list[str], include: list[str], persons: list[str],
|
def _included(domain: Domain, revinclude: list[str], include: list[str], persons: list[str],
|
||||||
at: date, risks: dict[str, list[dict]]) -> list[Resource]: # fmt: skip
|
at: date, risks: dict[str, list[dict]]) -> list[Resource]: # fmt: skip
|
||||||
unknown = set(revinclude) - set(REVINCLUDES) | set(include) - {"DiagnosticReport:result"}
|
unknown = set(revinclude) - set(REVINCLUDES) | set(include) - {"DiagnosticReport:result"}
|
||||||
@@ -437,7 +526,8 @@ def metadata(request: Request, domain: Domain) -> Response:
|
|||||||
"""What this base serves: built from the routes above, so it cannot drift from them."""
|
"""What this base serves: built from the routes above, so it cannot drift from them."""
|
||||||
resources: dict[str, dict] = {}
|
resources: dict[str, dict] = {}
|
||||||
system: list[dict] = []
|
system: list[dict] = []
|
||||||
clinical = part(domain, "follow_up") is not None
|
fu = part(domain, "follow_up")
|
||||||
|
clinical = fu is not None
|
||||||
for route in router.routes:
|
for route in router.routes:
|
||||||
path = route.path.removeprefix(router.prefix)
|
path = route.path.removeprefix(router.prefix)
|
||||||
if not path: # the base itself: the FHIR door
|
if not path: # the base itself: the FHIR door
|
||||||
@@ -448,10 +538,15 @@ def metadata(request: Request, domain: Domain) -> Response:
|
|||||||
if kind == "metadata" or (kind != "Measure" and kind != "MeasureReport"
|
if kind == "metadata" or (kind != "Measure" and kind != "MeasureReport"
|
||||||
and not clinical): # fmt: skip
|
and not clinical): # fmt: skip
|
||||||
continue
|
continue
|
||||||
|
if rest and rest[0].startswith("$"):
|
||||||
|
continue
|
||||||
entry = resources.setdefault(kind, {"type": kind, "interaction": [], "searchParam": []})
|
entry = resources.setdefault(kind, {"type": kind, "interaction": [], "searchParam": []})
|
||||||
if kind == "Patient" and not rest:
|
if kind == "Patient" and not rest:
|
||||||
entry |= {"searchInclude": ["DiagnosticReport:result"],
|
entry |= {"searchInclude": ["DiagnosticReport:result"],
|
||||||
"searchRevInclude": list(REVINCLUDES)} # fmt: skip
|
"searchRevInclude": list(REVINCLUDES)} # fmt: skip
|
||||||
|
entry["searchParam"] += [
|
||||||
|
{"name": name, "type": spec[0]} for name, spec in getattr(fu, "FILTERS", {}).items()
|
||||||
|
]
|
||||||
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
|
||||||
@@ -479,4 +574,9 @@ def metadata(request: Request, domain: Domain) -> Response:
|
|||||||
return fhir(statement)
|
return fhir(statement)
|
||||||
|
|
||||||
|
|
||||||
_STANDARD = {"_id": "token", "subject": "reference", "measure": "reference"}
|
_STANDARD = {
|
||||||
|
"_id": "token",
|
||||||
|
"subject": "reference",
|
||||||
|
"measure": "reference",
|
||||||
|
"follow-up-start": "date",
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user