TEA per-child FHIR resources: ADOS-2, EEG report, checks, metrics, Condition, RiskAssessment: routes and the per-child gate

This commit is contained in:
2026-11-30 01:14:13 -06:00
parent 3300ec3048
commit 983680ead3
2 changed files with 305 additions and 28 deletions
+69 -6
View File
@@ -3,6 +3,7 @@ uses, paging, and a CapabilityStatement built from these routes themselves. Reso
built by Core's mappers from the rows Persistance reads; nothing is computed here beyond
counting a few thousand rows (measures) and ordering the follow-up list."""
from collections import defaultdict
from datetime import date, datetime
from typing import Annotated, Any
from urllib.parse import urlencode
@@ -22,6 +23,7 @@ from core import measures as m
from core.domains import Domain, measures, part
from core.follow_up import window_start
from core.pipeline import ID_PATTERN
from core.tea import fhir as tea_fhir
from persistance import config_log, readers
from persistance import fhir as reads
from persistance import measures as measure_reads
@@ -209,7 +211,8 @@ def search_patient(
return outcome(422, str(exc))
persons = [r["person_id"] for r in rows]
risks: dict[str, list[dict]] = {}
if listed and sort != "-recent" or "RiskAssessment:subject" in revinclude:
if domain != Domain.TEA and (listed and sort != "-recent" or
"RiskAssessment:subject" in revinclude): # fmt: skip
for r in reads.rows(domain.value, "risk", persons=persons):
risks.setdefault(r["person_id"], []).append(r)
if listed:
@@ -281,7 +284,8 @@ def _patient_rows(
def _included(domain: Domain, revinclude: list[str], include: list[str], persons: list[str],
at: date, risks: dict[str, list[dict]]) -> list[Resource]: # fmt: skip
unknown = set(revinclude) - set(REVINCLUDES) | set(include) - {"DiagnosticReport:result"}
allowed = _revincludes(domain)
unknown = set(revinclude) - set(allowed) | set(include) - {"DiagnosticReport:result"}
if unknown:
raise HTTPException(422, f"cannot include {sorted(unknown)}")
found: list[Resource] = []
@@ -294,11 +298,21 @@ def _included(domain: Domain, revinclude: list[str], include: list[str], persons
kind = r.get_resource_type()
if (kind == "DiagnosticReport" and reports) or (kind == "Observation" and observations):
found.append(r)
if "Condition:subject" in revinclude:
found += [f.condition(r) for r in reads.rows(domain.value, "condition", persons=persons,
cutoff=at.isoformat())] # fmt: skip
if "RiskAssessment:subject" in revinclude:
found += _risk_assessments([r for p in persons for r in risks.get(p, [])])
if domain == Domain.TEA:
found += _tea_risks(persons, at.isoformat())
else:
found += _risk_assessments([r for p in persons for r in risks.get(p, [])])
return found
def _revincludes(domain: Domain) -> tuple[str, ...]:
return (*REVINCLUDES, "Condition:subject") if domain == Domain.TEA else REVINCLUDES
# --- clinical searches: by subject ----------------------------------------------------------
@@ -313,6 +327,11 @@ def _studies(domain: Domain, persons: list[str], at: str) -> list[Resource]:
by `at`: its DiagnosticReport (or Encounter) and Observations, in date order."""
found: list[Resource] = []
report_facts = _clinical(domain).REPORT_FACTS
if domain == Domain.TEA:
births = {
r["person_id"]: date.fromisoformat(f._day(r["birth_date"])) if r["birth_date"] else None
for r in reads.rows(domain.value, "births", persons=persons)
}
for study in catalog.of_domain(domain.value):
spec = catalog.studies()[study]
facts = {}
@@ -324,10 +343,51 @@ 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))]
found += f.instance(study, f.known(study, row, at), extra)
known = f.known(study, row, at)
found += f.instance(study, known, extra)
if domain == Domain.TEA and study == "ados2":
known["evaluation_date"] = date.fromisoformat(f._day(known["evaluation_date"]))
found.append(tea_fhir.ados2_observation(known, births.get(row["person_id"])))
if domain == Domain.TEA:
found += _tea_eeg_studies(persons, at)
return found
def _tea_eeg_studies(persons: list[str], at: str) -> list[Resource]:
def rows(kind):
return reads.rows("tea", kind, persons=persons, cutoff=at)
def key(row):
return row["person_id"], row["study_date"], row["edf"]
regions, results = defaultdict(list), defaultdict(list)
for row in rows("regions"):
regions[(*key(row), row["code"])].append(row)
for row in rows("checks"):
results[key(row)].append(tea_fhir.eeg_check(row))
for row in rows("metrics"):
results[key(row)].append(tea_fhir.eeg_metric(row, regions[(*key(row), row["code"])]))
found = []
for row in rows("eegs"):
observations = results[key(row)]
found.extend((tea_fhir.eeg_report(row, observations), *observations))
return found
def _tea_risks(persons: list[str], at: str) -> list[Resource]:
groups = defaultdict(list)
for row in reads.rows("tea", "association_scores", persons=persons, cutoff=at):
group = groups[row["person_id"]]
# The earliest scored EEG supplies the one set of predictions for this child.
if (
not group
or row["edf"] == group[0]["edf"]
and row["study_date"] == group[0]["study_date"]
):
group.append(row)
return [tea_fhir.association_risk(group) for group in groups.values()]
def _risk_assessments(rows: list[dict]) -> list[Resource]:
groups: dict[tuple, list[dict]] = {}
for r in rows:
@@ -344,7 +404,10 @@ def _clinical_search(kind: str, build, request, domain, subject, count, offset):
params["cutoff"] = _cutoff(domain, None).isoformat()
if kind == "procedure":
params["types"] = list(fu.PROCEDURES)
found = build(reads.rows(domain.value, kind, **params))
if kind == "risk" and domain == Domain.TEA:
found = _tea_risks(params["persons"], _cutoff(domain, None).isoformat())
else:
found = build(reads.rows(domain.value, kind, **params))
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
@@ -543,7 +606,7 @@ def metadata(request: Request, domain: Domain) -> Response:
entry = resources.setdefault(kind, {"type": kind, "interaction": [], "searchParam": []})
if kind == "Patient" and not rest:
entry |= {"searchInclude": ["DiagnosticReport:result"],
"searchRevInclude": list(REVINCLUDES)} # fmt: skip
"searchRevInclude": list(_revincludes(domain))} # fmt: skip
entry["searchParam"] += [
{"name": name, "type": spec[0]} for name, spec in getattr(fu, "FILTERS", {}).items()
]