TEA on its new staging: silver load, ten measures answered on request with the status at the period's end, several groups and column strata, and FHIR R4 endpoints for measures, follow-up and patient summary
This commit is contained in:
@@ -0,0 +1,360 @@
|
||||
"""A domain's FHIR R4 endpoint, `/<domain>/fhir/`: its measures and, for TEA, its patients' screening.
|
||||
|
||||
GET metadata CapabilityStatement
|
||||
GET Measure, Measure/<id> the measures (dbt's definitions)
|
||||
GET Measure/<id>/$evaluate-measure one period: periodStart and periodEnd, or `periodo`
|
||||
GET MeasureReport?measure=&periodo=|period= several periods (one report each), with `tipo-periodo`
|
||||
POST Measure/$recalcular queues the domain's recomputation
|
||||
GET CodeSystem, CodeSystem/<id>, ValueSet/<id> the project's code systems
|
||||
GET EpisodeOfCare, EpisodeOfCare/$resumen-eeg TEA's follow-up list and its EEG summary (DEV only)
|
||||
GET Patient/<pseudonym>/$resumen-tea TEA's patient summary (DEV only)
|
||||
|
||||
Every question of a measure takes `corte_evento` and `corte_conocimiento` as in `webapi.kpis`. Errors are
|
||||
`OperationOutcome`s. Patient data are served only in DEV, on simulated data, each resource tagged `simulado`.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from flask import Blueprint, request
|
||||
from werkzeug.exceptions import HTTPException
|
||||
|
||||
from webapi.fhir.common import FHIR_VERSION, canonical, entry, fhir, outcome, page, searchset, simulated_data
|
||||
from webapi.fhir.measures import fhir_id, labels, measure_report, measure_resource, measure_url
|
||||
from webapi.fhir.terminology import code_systems, metric_value_set
|
||||
from webapi.kpis import ANSWERS, _date, _datetime, _last_load, definitions_of, scoring_of
|
||||
from webapi.metrics import Question, UndecidedRule
|
||||
|
||||
TEA_SEARCH = ("status", "date", "etapa", "fecha-etapa", "grupo-edad", "mchat", "css", "resultado-eeg", "alteracion")
|
||||
|
||||
|
||||
def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients: bool = False,
|
||||
now: Callable[[], datetime] = lambda: datetime.now(timezone.utc)) -> Blueprint:
|
||||
"""The blueprint of a domain, to register with `url_prefix="/<domain>/fhir"`. `repositories` is the domain's
|
||||
`persistance.<domain>` module; `with_patients` adds TEA's patient routes (only in DEV)."""
|
||||
blueprint = Blueprint(f"{project}_fhir", __name__)
|
||||
titles = labels(manifest)
|
||||
patients = with_patients and project == "tea"
|
||||
|
||||
def definitions() -> dict:
|
||||
"""The domain's measures by their FHIR id; `definition()` also takes the dbt id."""
|
||||
every = {fhir_id(d): d for d in definitions_of(project, manifest).values()}
|
||||
if project == "tea":
|
||||
from webapi.fhir.tea import alterations_validated
|
||||
|
||||
if not alterations_validated():
|
||||
every = {k: d for k, d in every.items() if not d.meta.get("requiere_validacion")}
|
||||
return every
|
||||
|
||||
def definition_of(measure_id: str):
|
||||
return definitions().get(measure_id.replace("_", "-"))
|
||||
|
||||
def measure(definition) -> dict:
|
||||
title, description = titles.get(definition.metric, (definition.measure_id, ""))
|
||||
return measure_resource(definition, title, description)
|
||||
|
||||
@blueprint.app_errorhandler(HTTPException)
|
||||
def http_error(error: HTTPException):
|
||||
"""Under `/<domain>/fhir/`, an error is an `OperationOutcome`, also for a route that doesn't exist there;
|
||||
elsewhere, Flask's own answer."""
|
||||
if "/fhir/" not in request.path and not request.path.endswith("/fhir"):
|
||||
return error
|
||||
code = {404: "not-found", 405: "not-supported"}.get(error.code, "exception")
|
||||
return outcome(error.code, code, error.description or error.name)
|
||||
|
||||
@blueprint.get("/metadata")
|
||||
def capability_statement():
|
||||
resources = [
|
||||
{"type": "Measure", "interaction": [{"code": "read"}, {"code": "search-type"}],
|
||||
"operation": [{"name": "evaluate-measure", "definition": "http://hl7.org/fhir/OperationDefinition/Measure-evaluate-measure"},
|
||||
{"name": "recalcular", "definition": canonical("OperationDefinition/recalcular")}]},
|
||||
{"type": "MeasureReport", "interaction": [{"code": "search-type"}],
|
||||
"searchParam": [{"name": n, "type": t} for n, t in (("measure", "reference"), ("period", "date"),
|
||||
("periodo", "token"), ("tipo-periodo", "token"))]},
|
||||
{"type": "CodeSystem", "interaction": [{"code": "read"}, {"code": "search-type"}]},
|
||||
]
|
||||
if patients:
|
||||
resources += [
|
||||
{"type": "EpisodeOfCare", "interaction": [{"code": "search-type"}],
|
||||
"searchParam": [{"name": n, "definition": canonical(f"SearchParameter/episode-{n}"),
|
||||
"type": "date" if n in ("date", "fecha-etapa") else
|
||||
"number" if n in ("mchat", "css") else "token"} for n in TEA_SEARCH],
|
||||
"searchInclude": ["*"],
|
||||
"operation": [{"name": "resumen-eeg", "definition": canonical("OperationDefinition/resumen-eeg")}]},
|
||||
{"type": "Patient", "operation": [{"name": "resumen-tea",
|
||||
"definition": canonical("OperationDefinition/resumen-tea")}]},
|
||||
{"type": "ValueSet", "interaction": [{"code": "read"}]},
|
||||
]
|
||||
return fhir({"resourceType": "CapabilityStatement", "status": "active", "date": now().date().isoformat(),
|
||||
"kind": "instance", "fhirVersion": FHIR_VERSION, "format": ["application/fhir+json"],
|
||||
"implementation": {"description": f"ISSSTELEON, {project.upper()}", "url": request.url_root},
|
||||
"rest": [{"mode": "server", "resource": resources}]})
|
||||
|
||||
@blueprint.get("/Measure")
|
||||
def measures():
|
||||
found = [measure(d) for _, d in sorted(definitions().items())]
|
||||
if url := request.args.get("url"):
|
||||
found = [m for m in found if m["url"] == url]
|
||||
count, offset = page()
|
||||
return fhir(searchset([entry(m) for m in found[offset:offset + count]], len(found), count, offset))
|
||||
|
||||
@blueprint.get("/Measure/<measure_id>")
|
||||
def read_measure(measure_id: str):
|
||||
definition = definition_of(measure_id)
|
||||
if definition is None:
|
||||
return outcome(404, "not-found", f"no hay un indicador {measure_id!r}")
|
||||
return fhir(measure(definition))
|
||||
|
||||
def ask(definition, period, event_cutoff, knowledge_cutoff):
|
||||
question = Question(definition.url, period.periodo_id, event_cutoff, knowledge_cutoff)
|
||||
answer_of, _ = ANSWERS[scoring_of(definition)]
|
||||
result = answer_of(project, definition, question, parameters=repositories.def_parametro_repository,
|
||||
periods=repositories.dim_periodo_repository, history=repositories.history_repository,
|
||||
queries=repositories.dbt_query_repository)
|
||||
return measure_report(definition, question, result, period, now())
|
||||
|
||||
def cutoffs():
|
||||
return (_date(request.args.get("corte_evento")),
|
||||
_datetime(request.args.get("corte_conocimiento")) or _last_load(repositories))
|
||||
|
||||
@blueprint.get("/Measure/<measure_id>/$evaluate-measure")
|
||||
def evaluate_measure(measure_id: str):
|
||||
definition = definition_of(measure_id)
|
||||
if definition is None:
|
||||
return outcome(404, "not-found", f"no hay un indicador {measure_id!r}")
|
||||
try:
|
||||
event_cutoff, knowledge_cutoff = cutoffs()
|
||||
period = _period_asked(repositories)
|
||||
except ValueError as error:
|
||||
return outcome(400, "invalid", str(error))
|
||||
except LookupError as error:
|
||||
return outcome(404, "not-found", str(error))
|
||||
try:
|
||||
return fhir(ask(definition, period, event_cutoff, knowledge_cutoff))
|
||||
except UndecidedRule as error:
|
||||
return outcome(409, "business-rule", str(error))
|
||||
|
||||
@blueprint.get("/MeasureReport")
|
||||
def measure_reports():
|
||||
asked = request.args.get("measure", "")
|
||||
by_url = {measure_url(d): d for d in definitions().values()}
|
||||
definition = by_url.get(asked.split("|")[0]) or definition_of(asked)
|
||||
if definition is None:
|
||||
return outcome(400, "required", "falta `measure` (el canónico o el id de un indicador)")
|
||||
try:
|
||||
event_cutoff, knowledge_cutoff = cutoffs()
|
||||
periods = _periods_searched(repositories)
|
||||
count, offset = page()
|
||||
except ValueError as error:
|
||||
return outcome(400, "invalid", str(error))
|
||||
except LookupError as error:
|
||||
return outcome(404, "not-found", str(error))
|
||||
try:
|
||||
reports = [ask(definition, p, event_cutoff, knowledge_cutoff) for p in periods[offset:offset + count]]
|
||||
except UndecidedRule as error:
|
||||
return outcome(409, "business-rule", str(error))
|
||||
return fhir(searchset([entry(r) for r in reports], len(periods), count, offset))
|
||||
|
||||
@blueprint.post("/Measure/$recalcular")
|
||||
def recompute():
|
||||
from webapi.recomputation import RecomputationQueue
|
||||
|
||||
RecomputationQueue().request_run(project)
|
||||
return outcome(202, "informational", f"se pidió recalcular los indicadores de {project}", severity="information")
|
||||
|
||||
@blueprint.get("/CodeSystem")
|
||||
def code_system_search():
|
||||
systems = list(code_systems(project).values())
|
||||
return fhir(searchset([entry(s) for s in systems], len(systems), len(systems) or 1, 0))
|
||||
|
||||
@blueprint.get("/CodeSystem/<system_id>")
|
||||
def read_code_system(system_id: str):
|
||||
system = code_systems(project).get(system_id)
|
||||
return fhir(system) if system else outcome(404, "not-found", f"no hay un sistema de códigos {system_id!r}")
|
||||
|
||||
if patients:
|
||||
_patient_routes(blueprint, repositories, now)
|
||||
return blueprint
|
||||
|
||||
|
||||
def _period_asked(repositories):
|
||||
"""The `dim_periodo` row the question names: `periodo`, or `periodStart` and `periodEnd` (inclusive)."""
|
||||
if periodo := request.args.get("periodo"):
|
||||
period = repositories.dim_periodo_repository.get(periodo)
|
||||
if period is None:
|
||||
raise LookupError(f"no hay un periodo {periodo!r}")
|
||||
return period
|
||||
start, end = request.args.get("periodStart"), request.args.get("periodEnd")
|
||||
if not (start and end):
|
||||
raise ValueError("falta el periodo: `periodStart` y `periodEnd`, o `periodo`")
|
||||
start, end = date.fromisoformat(start), date.fromisoformat(end)
|
||||
for period in repositories.dim_periodo_repository.list(limit=10000, inicio=start):
|
||||
if period.fin - timedelta(days=1) == end:
|
||||
return period
|
||||
raise LookupError(f"no hay un periodo de {start} a {end}")
|
||||
|
||||
|
||||
def _periods_searched(repositories) -> list:
|
||||
"""The periods of a `MeasureReport` search: `periodo` (comma-separated ids), or the periods of `tipo-periodo`
|
||||
within `period=ge…` and `period=le…`."""
|
||||
if ids := [p for p in request.args.get("periodo", "").split(",") if p]:
|
||||
periods = [repositories.dim_periodo_repository.get(i) for i in ids]
|
||||
if missing := [i for i, p in zip(ids, periods) if p is None]:
|
||||
raise LookupError(f"no hay un periodo {missing[0]!r}")
|
||||
return periods
|
||||
kind = request.args.get("tipo-periodo")
|
||||
if not kind:
|
||||
raise ValueError("falta `periodo` o `tipo-periodo` con `period`")
|
||||
low, high = date.min, date.max
|
||||
for value in request.args.getlist("period"):
|
||||
if value.startswith("ge"):
|
||||
low = date.fromisoformat(value[2:])
|
||||
elif value.startswith("le"):
|
||||
high = date.fromisoformat(value[2:])
|
||||
else:
|
||||
raise ValueError(f"`period` admite ge y le: {value!r}")
|
||||
found = repositories.dim_periodo_repository.list(limit=10000, tipo=kind)
|
||||
return sorted((p for p in found if p.inicio >= low and p.fin - timedelta(days=1) <= high), key=lambda p: p.inicio)
|
||||
|
||||
|
||||
def _bound(name: str) -> tuple[float | None, float | None]:
|
||||
"""A number search parameter's bounds: `mchat=ge8&mchat=le20`, or one exact value."""
|
||||
low = high = None
|
||||
for value in request.args.getlist(name):
|
||||
if value.startswith("ge"):
|
||||
low = float(value[2:])
|
||||
elif value.startswith("le"):
|
||||
high = float(value[2:])
|
||||
else:
|
||||
low = high = float(value)
|
||||
return low, high
|
||||
|
||||
|
||||
def _dates(name: str) -> tuple[date | None, date | None]:
|
||||
low = high = None
|
||||
for value in request.args.getlist(name):
|
||||
if value.startswith("ge"):
|
||||
low = date.fromisoformat(value[2:])
|
||||
elif value.startswith("le"):
|
||||
high = date.fromisoformat(value[2:])
|
||||
else:
|
||||
low = high = date.fromisoformat(value)
|
||||
return low, high
|
||||
|
||||
|
||||
def _patient_routes(blueprint: Blueprint, repositories, now) -> None:
|
||||
from webapi.fhir import tea
|
||||
|
||||
queries = repositories.dbt_query_repository
|
||||
|
||||
def matching():
|
||||
"""The episodes the search's parameters select, at its cut-off (`date=le…`, by default today)."""
|
||||
unknown = [k for k in request.args if not k.startswith("_") and k not in TEA_SEARCH]
|
||||
if unknown:
|
||||
raise ValueError(f"parámetro de búsqueda no admitido: {unknown[0]!r}")
|
||||
if request.args.get("alteracion") and not tea.alterations_validated():
|
||||
raise PermissionError("las alteraciones del EEG no se muestran hasta validar sus referencias")
|
||||
since, cutoff = _dates("date")
|
||||
cutoff = cutoff or now().date()
|
||||
stage_from, stage_to = _dates("fecha-etapa")
|
||||
mchat, css = _bound("mchat"), _bound("css")
|
||||
|
||||
def within(value, bounds):
|
||||
low, high = bounds
|
||||
return value is not None and (low is None or value >= low) and (high is None or value <= high)
|
||||
|
||||
found = []
|
||||
for e in tea.episodes(queries, cutoff):
|
||||
stage = e.stage
|
||||
if since is not None and e.finished and stage[1] < since:
|
||||
continue
|
||||
if (status := request.args.get("status")) and status != ("finished" if e.finished else "active"):
|
||||
continue
|
||||
if (etapa := request.args.get("etapa")) and (stage is None or stage[0] not in etapa.split(",")):
|
||||
continue
|
||||
if (stage_from or stage_to) and (stage is None or not within(stage[1].toordinal(), (
|
||||
stage_from and stage_from.toordinal(), stage_to and stage_to.toordinal()))):
|
||||
continue
|
||||
if (group := request.args.get("grupo-edad")) and e.child["grupo_edad"] not in group.split(","):
|
||||
continue
|
||||
if request.args.getlist("mchat") and not within(e.child["mchat"], mchat):
|
||||
continue
|
||||
if request.args.getlist("css") and not within(e.child["css_ados2"], css):
|
||||
continue
|
||||
if result := request.args.get("resultado-eeg"):
|
||||
shown = e.eeg_result if tea.alterations_validated() else (
|
||||
"sin-eeg-valido" if e.eeg_result == "sin-eeg-valido" else "valido")
|
||||
if shown not in result.split(","):
|
||||
continue
|
||||
if (alteration := request.args.get("alteracion")) and alteration not in e.alterations():
|
||||
continue
|
||||
found.append(e)
|
||||
return sorted(found, key=lambda e: e.pseudonym)
|
||||
|
||||
@blueprint.get("/EpisodeOfCare")
|
||||
def episodes_of_care():
|
||||
try:
|
||||
found = matching()
|
||||
count, offset = page()
|
||||
except ValueError as error:
|
||||
return tea_outcome(400, "invalid", error)
|
||||
except PermissionError as error:
|
||||
return tea_outcome(403, "forbidden", error)
|
||||
simulated = simulated_data()
|
||||
shown = found[offset:offset + count]
|
||||
entries = [entry(tea.episode_of_care(e, simulated)) for e in shown]
|
||||
if request.args.get("_include"):
|
||||
entries += [entry(r, "include") for e in shown for r in _included(tea, queries, e, simulated)]
|
||||
return fhir(searchset(entries, len(found), count, offset))
|
||||
|
||||
@blueprint.get("/EpisodeOfCare/$resumen-eeg")
|
||||
def eeg_summary():
|
||||
try:
|
||||
found = matching()
|
||||
except ValueError as error:
|
||||
return tea_outcome(400, "invalid", error)
|
||||
except PermissionError as error:
|
||||
return tea_outcome(403, "forbidden", error)
|
||||
valid = [e for e in found if e.eeg_result != "sin-eeg-valido"]
|
||||
parameters = [{"name": "con_eeg_valido", "valueInteger": len(valid)},
|
||||
{"name": "sin_eeg_valido", "valueInteger": len(found) - len(valid)}]
|
||||
if tea.alterations_validated():
|
||||
by_alteration: dict[str, int] = {}
|
||||
for e in valid:
|
||||
for code in e.alterations():
|
||||
by_alteration[code] = by_alteration.get(code, 0) + 1
|
||||
parameters += [{"name": "normales", "valueInteger": sum(e.eeg_result == "normal" for e in valid)},
|
||||
{"name": "anormales", "valueInteger": sum(e.eeg_result == "anormal" for e in valid)},
|
||||
*({"name": "por_alteracion", "part": [{"name": "alteracion", "valueCode": code},
|
||||
{"name": "pacientes", "valueInteger": n}]}
|
||||
for code, n in sorted(by_alteration.items()))]
|
||||
return fhir({"resourceType": "Parameters", "parameter": parameters})
|
||||
|
||||
@blueprint.get("/Patient/<pseudonym>/$resumen-tea")
|
||||
def patient_summary(pseudonym: str):
|
||||
pac_id = tea.patient_of(queries, pseudonym)
|
||||
if pac_id is None:
|
||||
return outcome(404, "not-found", f"no hay un paciente {pseudonym!r}")
|
||||
return fhir(tea.patient_summary(queries, pac_id, now().date(), simulated_data()))
|
||||
|
||||
@blueprint.get("/ValueSet/tea-alteracion")
|
||||
def alteration_types():
|
||||
return fhir(metric_value_set())
|
||||
|
||||
|
||||
def tea_outcome(status: int, code: str, error: Exception):
|
||||
return outcome(status, code, str(error))
|
||||
|
||||
|
||||
def _included(tea, queries, e, simulated: bool) -> list[dict]:
|
||||
"""What an episode's search includes: its patient, its steps, its M-CHAT, its diagnosis and its study EEG."""
|
||||
from sqlalchemy import select
|
||||
|
||||
persons = tea._rows(queries, select(tea.PERSONS).where(tea.PERSONS.c.pac_id == e.child["pac_id"]))
|
||||
resources = [tea.patient(e.child["pac_id"], persons[0]["fecha_nacimiento"] if persons else None, simulated),
|
||||
tea.care_plan(e, simulated)]
|
||||
resources += [r for r in (tea.mchat_observation(e, simulated), tea.condition(e, simulated)) if r]
|
||||
if (eeg := e.study_eeg()) is not None:
|
||||
resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated)
|
||||
return resources
|
||||
@@ -0,0 +1,93 @@
|
||||
"""What every FHIR R4 answer of the WebApi shares: the media type, errors as `OperationOutcome`, search bundles with
|
||||
their paging links, the simulated-data tag and the project's canonical URLs."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from flask import Response, request
|
||||
|
||||
FHIR_VERSION = "4.0.1"
|
||||
MEDIA_TYPE = "application/fhir+json"
|
||||
BASE = "https://isssteleon.org/fhir"
|
||||
CODE_SYSTEM = f"{BASE}/CodeSystem"
|
||||
VALUE_SET = f"{BASE}/ValueSet"
|
||||
STRUCTURE = f"{BASE}/StructureDefinition"
|
||||
SIMULATED = {"system": f"{CODE_SYSTEM}/etiqueta", "code": "simulado", "display": "Datos simulados"}
|
||||
MAX_COUNT = 200
|
||||
DEFAULT_COUNT = 50
|
||||
|
||||
|
||||
def fhir(resource: dict, status: int = 200) -> Response:
|
||||
"""A resource as the answer, in FHIR's JSON media type."""
|
||||
return Response(json.dumps(resource, ensure_ascii=False), status=status, mimetype=MEDIA_TYPE)
|
||||
|
||||
|
||||
def outcome(status: int, code: str, diagnostics: str, severity: str = "error") -> Response:
|
||||
"""An error as an `OperationOutcome` (`code` from FHIR's issue-type), with the HTTP status it goes with."""
|
||||
return fhir({"resourceType": "OperationOutcome",
|
||||
"issue": [{"severity": severity, "code": code, "diagnostics": diagnostics}]}, status)
|
||||
|
||||
|
||||
def canonical(path: str) -> str:
|
||||
"""The absolute canonical of a project resource: `Measure/<id>`, `CodeSystem/<id>`…"""
|
||||
return f"{BASE}/{path}"
|
||||
|
||||
|
||||
def coding(system: str, code: str, display: str | None = None) -> dict:
|
||||
return {"system": system, "code": code, **({"display": display} if display else {})}
|
||||
|
||||
|
||||
def concept(system: str, code: str, display: str | None = None, text: str | None = None) -> dict:
|
||||
return {"coding": [coding(system, code, display)], **({"text": text} if text else {})}
|
||||
|
||||
|
||||
def tagged(resource: dict, simulated: bool) -> dict:
|
||||
"""The resource with the simulated-data tag in its `meta`, when its data are simulated."""
|
||||
if simulated:
|
||||
resource.setdefault("meta", {}).setdefault("tag", []).append(SIMULATED)
|
||||
return resource
|
||||
|
||||
|
||||
def simulated_data() -> bool:
|
||||
"""Patient data are simulated in the DEV deployment (`DEV_REVISION`), the only one that serves them."""
|
||||
return bool(os.environ.get("DEV_REVISION"))
|
||||
|
||||
|
||||
def page() -> tuple[int, int]:
|
||||
"""`_count` (at most `MAX_COUNT`) and `_offset` of the search. `ValueError` if one isn't a number."""
|
||||
count = int(request.args.get("_count", DEFAULT_COUNT))
|
||||
offset = int(request.args.get("_offset", 0))
|
||||
if count < 0 or offset < 0:
|
||||
raise ValueError("`_count` y `_offset` no pueden ser negativos")
|
||||
return min(count, MAX_COUNT), offset
|
||||
|
||||
|
||||
def searchset(entries: list[dict], total: int, count: int, offset: int) -> dict:
|
||||
"""A `searchset` Bundle with the page's entries, the total and the `self`, `next` and `previous` links."""
|
||||
def link(relation: str, at: int) -> dict:
|
||||
args = [(k, v) for k, v in request.args.items(multi=True) if k not in ("_count", "_offset")]
|
||||
return {"relation": relation, "url": f"{request.base_url}?{urlencode([*args, ('_count', count), ('_offset', at)])}"}
|
||||
|
||||
links = [link("self", offset)]
|
||||
if offset + count < total:
|
||||
links.append(link("next", offset + count))
|
||||
if offset > 0:
|
||||
links.append(link("previous", max(0, offset - count)))
|
||||
return {"resourceType": "Bundle", "type": "searchset", "total": total, "link": links, "entry": entries}
|
||||
|
||||
|
||||
def fhir_base() -> str:
|
||||
"""This request's FHIR endpoint, `…/<domain>/fhir/`: what a `fullUrl` is relative to."""
|
||||
url = request.base_url
|
||||
return url[:url.index("/fhir/") + len("/fhir/")] if "/fhir/" in url else url.rstrip("/") + "/"
|
||||
|
||||
|
||||
def entry(resource: dict, mode: str | None = "match") -> dict:
|
||||
"""A Bundle entry: its `fullUrl` when the resource has an id, and its search mode in a searchset."""
|
||||
item = {"resource": resource}
|
||||
if "id" in resource:
|
||||
item = {"fullUrl": f"{fhir_base()}{resource['resourceType']}/{resource['id']}", **item}
|
||||
if mode:
|
||||
item["search"] = {"mode": mode}
|
||||
return item
|
||||
@@ -0,0 +1,194 @@
|
||||
"""A domain's measures as FHIR R4 `Measure` resources, and their answers as `MeasureReport`s.
|
||||
|
||||
The definitions are dbt's (`webapi.kpis.definitions_of`); the `Measure` carries what the indicator page needs from
|
||||
each metric's `meta` (title, description, scoring, populations, strata, period types, figures and category labels as
|
||||
extensions). A report names its measure by the absolute canonical the `Measure` carries; each group and stratifier
|
||||
has a code; a composition (C2) is a `cohort` whose categories are a stratifier, and with strata, each stratum holds
|
||||
its category as a `component`. A duration reports the units without a value as their own population.
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from webapi.compositions import CompositionAnswer, CompositionDefinition
|
||||
from webapi.durations import OBSERVATION, DurationAnswer, DurationDefinition
|
||||
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, canonical, concept
|
||||
from webapi.metrics import EVENT_CUTOFF, HISTORY_ENTRY, KNOWLEDGE_CUTOFF, POPULATION_SYSTEM, Answer, Counts
|
||||
|
||||
SCORING_SYSTEM = "http://terminology.hl7.org/CodeSystem/measure-scoring"
|
||||
IMPROVEMENT_SYSTEM = "http://terminology.hl7.org/CodeSystem/measure-improvement-notation"
|
||||
GROUP_SYSTEM = f"{CODE_SYSTEM}/grupo-medida"
|
||||
STRATIFIER_SYSTEM = f"{CODE_SYSTEM}/estratificador"
|
||||
EXCLUDED = "measure-population-exclusion"
|
||||
FIGURES = f"{STRUCTURE}/figuras"
|
||||
PERIOD_TYPES = f"{STRUCTURE}/tipos-periodo"
|
||||
CATEGORY_LABEL = f"{STRUCTURE}/categoria"
|
||||
CONTRACT = f"{STRUCTURE}/contrato"
|
||||
REQUIRES_VALIDATION = f"{STRUCTURE}/requiere-validacion"
|
||||
POPULATION_LABELS = {
|
||||
"initial-population": "Unidades del periodo", "numerator": "Numerador", "denominator": "Denominador",
|
||||
"denominator-exclusion": "Excluidos del denominador", "measure-observation": "Unidades con valor",
|
||||
EXCLUDED: "Unidades sin valor",
|
||||
}
|
||||
|
||||
|
||||
def scoring(definition) -> str:
|
||||
"""The FHIR scoring: a composition is a `cohort` (its categories are a stratifier)."""
|
||||
if isinstance(definition, CompositionDefinition):
|
||||
return "cohort"
|
||||
return "continuous-variable" if isinstance(definition, DurationDefinition) else "proportion"
|
||||
|
||||
|
||||
def labels(manifest: Path) -> dict[str, tuple[str, str]]:
|
||||
"""Each metric's (title, description) in the manifest: `meta.titulo` when the label had to differ."""
|
||||
metrics = json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values()
|
||||
return {m["name"]: (m["config"].get("meta", {}).get("titulo") or m["label"], (m.get("description") or "").strip())
|
||||
for m in metrics}
|
||||
|
||||
|
||||
def fhir_id(definition) -> str:
|
||||
"""The measure's id as FHIR allows one (letters, digits, `-` and `.`): `M21_diagnosticados_con_eeg` ->
|
||||
`M21-diagnosticados-con-eeg`."""
|
||||
return definition.measure_id.replace("_", "-")
|
||||
|
||||
|
||||
def measure_url(definition) -> str:
|
||||
return canonical(f"Measure/{fhir_id(definition)}")
|
||||
|
||||
|
||||
def _populations(definition) -> list[dict]:
|
||||
"""Each population with the dbt metric that counts it as its criteria."""
|
||||
if scoring(definition) == "proportion":
|
||||
metrics = {**{c: definition.denominator.metric for c in definition.denominator.codes},
|
||||
**{c: definition.numerator.metric for c in definition.numerator.codes},
|
||||
**({c: definition.exclusion.metric for c in definition.exclusion.codes}
|
||||
if getattr(definition, "exclusion", None) else {})}
|
||||
else:
|
||||
codes = ["initial-population"] if scoring(definition) == "cohort" else ["initial-population", OBSERVATION,
|
||||
EXCLUDED]
|
||||
metrics = {c: definition.metric for c in codes}
|
||||
return [{"code": concept(POPULATION_SYSTEM, c), "description": POPULATION_LABELS.get(c, c),
|
||||
"criteria": {"language": "text/x-dbt-metric", "expression": metric}} for c, metric in metrics.items()]
|
||||
|
||||
|
||||
def measure_resource(definition, title: str, description: str) -> dict:
|
||||
"""The `Measure` of a definition: one group per group it publishes, each with its populations and strata."""
|
||||
meta = getattr(definition, "meta", {}) or {}
|
||||
strata = [{"code": concept(STRATIFIER_SYSTEM, s.name, text=s.spec.get("etiqueta", s.name))}
|
||||
for s in definition.strata]
|
||||
if isinstance(definition, CompositionDefinition):
|
||||
strata.insert(0, {"code": concept(STRATIFIER_SYSTEM, definition.category.value)})
|
||||
groups = [{"code": concept(GROUP_SYSTEM, definition.group), "population": _populations(definition),
|
||||
**({"stratifier": strata} if strata else {})}]
|
||||
groups += [{"code": concept(GROUP_SYSTEM, g.name, g.label), "population": _populations(definition)}
|
||||
for g in getattr(definition, "groups", ())]
|
||||
extensions = [{"url": CONTRACT, "valueCode": meta.get("contrato", "")},
|
||||
*({"url": PERIOD_TYPES, "valueCode": t} for t in meta.get("tipos_periodo", ())),
|
||||
*({"url": FIGURES, "valueString": f} for f in meta.get("figuras", ()))]
|
||||
category = meta.get("categoria", {})
|
||||
extensions += [{"url": CATEGORY_LABEL, "extension": [
|
||||
{"url": "codigo", "valueCode": code}, {"url": "etiqueta", "valueString": spec["etiqueta"]},
|
||||
{"url": "color", "valueString": spec["color"]}]} for code, spec in category.get("etiquetas", {}).items()]
|
||||
if meta.get("requiere_validacion"):
|
||||
extensions.append({"url": REQUIRES_VALIDATION, "valueCode": meta["requiere_validacion"]})
|
||||
resource = {
|
||||
"resourceType": "Measure", "id": fhir_id(definition), "url": measure_url(definition),
|
||||
"version": definition.version, "name": definition.metric, "title": title, "status": "active",
|
||||
"description": description or title, "extension": [e for e in extensions if e.get("valueCode", True)],
|
||||
"scoring": concept(SCORING_SYSTEM, scoring(definition)), "group": groups,
|
||||
}
|
||||
if definition.basis:
|
||||
resource["subjectCodeableConcept"] = concept(f"{CODE_SYSTEM}/unidad", definition.basis)
|
||||
if definition.improvement_notation:
|
||||
resource["improvementNotation"] = concept(IMPROVEMENT_SYSTEM, definition.improvement_notation)
|
||||
return resource
|
||||
|
||||
|
||||
def _count(code: str, n: int) -> dict:
|
||||
return {"code": concept(POPULATION_SYSTEM, code), "count": n}
|
||||
|
||||
|
||||
def _proportion_cells(definition, counts: Counts, excluded: int | None = None) -> dict:
|
||||
cells = {"population": [*(_count(c, counts.denominator) for c in definition.denominator.codes),
|
||||
*(_count(c, counts.numerator) for c in definition.numerator.codes)]}
|
||||
if excluded is not None and getattr(definition, "exclusion", None):
|
||||
cells["population"] += [_count(c, excluded) for c in definition.exclusion.codes]
|
||||
if counts.proportion is not None:
|
||||
cells["measureScore"] = {"value": counts.proportion}
|
||||
return cells
|
||||
|
||||
|
||||
def _label(spec: dict, value: str) -> str | None:
|
||||
"""A stratum value's label, when the stratum's `valores` maps values to labels."""
|
||||
labels_of = spec.get("valores")
|
||||
return labels_of.get(value) if isinstance(labels_of, dict) else None
|
||||
|
||||
|
||||
def _stratum_value(stratifier: str, value: str, display: str | None = None) -> dict:
|
||||
return concept(f"{CODE_SYSTEM}/{stratifier.replace('_', '-')}", value, display)
|
||||
|
||||
|
||||
def _groups(definition, result) -> list[dict]:
|
||||
if isinstance(result, CompositionAnswer):
|
||||
group = {"code": concept(GROUP_SYSTEM, definition.group), "population": [_count("initial-population",
|
||||
result.total)]}
|
||||
labels_of = {c: s["etiqueta"] for c, s in definition.meta.get("categoria", {}).get("etiquetas", {}).items()}
|
||||
category = definition.category.value
|
||||
stratifiers = [{"code": [concept(STRATIFIER_SYSTEM, category)], "stratum": [
|
||||
{"value": _stratum_value(category, c, labels_of.get(c)), "population": [_count("initial-population", n)]}
|
||||
for c, n in sorted(result.categories.items())]}]
|
||||
for name, by_value in result.strata.items():
|
||||
stratifiers.append({"code": [concept(STRATIFIER_SYSTEM, name), concept(STRATIFIER_SYSTEM, category)],
|
||||
"stratum": [{"component": [
|
||||
{"code": concept(STRATIFIER_SYSTEM, name), "value": _stratum_value(name, v)},
|
||||
{"code": concept(STRATIFIER_SYSTEM, category), "value": _stratum_value(category, c)},
|
||||
], "population": [_count("initial-population", n)]}
|
||||
for v, cs in sorted(by_value.items()) for c, n in sorted(cs.items())]})
|
||||
group["stratifier"] = stratifiers
|
||||
return [group]
|
||||
if isinstance(result, DurationAnswer):
|
||||
group = {"code": concept(GROUP_SYSTEM, definition.group), "population": [
|
||||
_count("initial-population", result.initial), _count(OBSERVATION, result.n),
|
||||
_count(EXCLUDED, result.excluded)]}
|
||||
if result.median is not None:
|
||||
group["measureScore"] = {"value": result.median, "unit": "d", "extension": [
|
||||
{"url": f"{STRUCTURE}/q1", "valueDecimal": result.q1},
|
||||
{"url": f"{STRUCTURE}/q3", "valueDecimal": result.q3}]}
|
||||
return [group]
|
||||
assert isinstance(result, Answer)
|
||||
spec_of = {s.name: s.spec for s in definition.strata}
|
||||
group = {"code": concept(GROUP_SYSTEM, definition.group), **_proportion_cells(definition, result.total,
|
||||
result.excluded)}
|
||||
if result.strata:
|
||||
group["stratifier"] = [{"code": [concept(STRATIFIER_SYSTEM, name, text=spec_of[name].get("etiqueta"))],
|
||||
"stratum": [{"value": _stratum_value(name, value, _label(spec_of[name], value)),
|
||||
**_proportion_cells(definition, c)}
|
||||
for value, c in sorted(values.items())]}
|
||||
for name, values in result.strata.items()]
|
||||
groups = [group]
|
||||
labels_of = {g.name: g.label for g in getattr(definition, "groups", ())}
|
||||
groups += [{"code": concept(GROUP_SYSTEM, name, labels_of.get(name)), **_proportion_cells(definition, counts)}
|
||||
for name, counts in result.groups.items()]
|
||||
return groups
|
||||
|
||||
|
||||
def measure_report(definition, question, result, period, generated_at: datetime) -> dict:
|
||||
"""An answer as a FHIR R4 `MeasureReport` (summary), naming its measure by its absolute canonical."""
|
||||
cutoff = getattr(result, "event_cutoff", None) or question.event_cutoff
|
||||
extensions = [{"url": HISTORY_ENTRY, "valueInteger": result.report_id}]
|
||||
if cutoff is not None:
|
||||
extensions.append({"url": EVENT_CUTOFF, "valueDate": cutoff.isoformat()})
|
||||
if question.knowledge_cutoff is not None:
|
||||
extensions.append({"url": KNOWLEDGE_CUTOFF, "valueDateTime": question.knowledge_cutoff.isoformat()})
|
||||
report = {
|
||||
"resourceType": "MeasureReport", "id": f"{fhir_id(definition)}-{result.report_id}", "status": "complete",
|
||||
"type": "summary", "measure": f"{measure_url(definition)}|{definition.version}",
|
||||
"date": generated_at.isoformat(),
|
||||
# FHIR's end is inclusive; a period of `dim_periodo` ends the day before `fin`.
|
||||
"period": {"start": period.inicio.isoformat(), "end": (period.fin - timedelta(days=1)).isoformat()},
|
||||
"extension": extensions, "group": _groups(definition, result),
|
||||
}
|
||||
if definition.improvement_notation:
|
||||
report["improvementNotation"] = concept(IMPROVEMENT_SYSTEM, definition.improvement_notation)
|
||||
return report
|
||||
@@ -0,0 +1,352 @@
|
||||
"""TEA's patients as FHIR R4 resources: the follow-up list as `EpisodeOfCare`s and the patient summary.
|
||||
|
||||
Read from dbt's views (`tea_seguimiento`, `tea_paciente_*`), which hold dates, not states: every state here is taken
|
||||
at a date, the cut-off. A child's screening is an `EpisodeOfCare` from its first M-CHAT to its first good EEG, its
|
||||
stage the furthest step reached by the cut-off (`type`, with its date as an extension), its pending steps a
|
||||
`CarePlan`. The EEG the study uses is the child's first good EEG by the cut-off; without one, the latest, as not
|
||||
valid. `Patient.id` is the salted pseudonym: `pac_id` never leaves.
|
||||
|
||||
Until the domain expert validates the reference ranges, every alteration stays hidden (`alterations_validated`):
|
||||
the alteration filter, the abnormal/normal split, and the metric and electrode observations.
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import column, select, table
|
||||
|
||||
from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, concept, tagged
|
||||
from webapi.follow_up.listing import seudonimo
|
||||
|
||||
STEPS = (("SOLO_MCHAT", "fecha_mchat", "M-CHAT"), ("PSICOLOGIA", "fecha_psicologia", "Evaluación psicológica"),
|
||||
("NEUROPEDIATRIA", "fecha_neuropediatria", "Evaluación neuropediátrica"),
|
||||
("EEG", "fecha_eeg", "EEG de buena calidad"))
|
||||
CRITERIA = (("calidad_amplitud", "Canales con amplitud extrema", "canales"),
|
||||
("calidad_alta_frecuencia", "Ruido de alta frecuencia", "canales"),
|
||||
("calidad_correlacion", "Baja correlación entre canales", "canales"),
|
||||
("calidad_sin_senal", "Canales planos o sin señal", "canales"),
|
||||
("calidad_linea", "Ruido de la línea eléctrica", "dB"))
|
||||
ALTERED = ("aumentado", "disminuido")
|
||||
INTERPRETATION = "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation"
|
||||
ABSENT = "http://terminology.hl7.org/CodeSystem/data-absent-reason"
|
||||
ICD10 = "http://hl7.org/fhir/sid/icd-10"
|
||||
CATALOG = f"{CODE_SYSTEM}/tea-catalogo"
|
||||
STAGE_DATE = f"{STRUCTURE}/fecha-etapa"
|
||||
AGE_GROUP = f"{STRUCTURE}/grupo-edad"
|
||||
DEFAULT_SALT = "dev-simulado"
|
||||
|
||||
FOLLOW_UP = table("tea_seguimiento", *map(column, (
|
||||
"pac_id", "grupo_edad", "fecha_mchat", "mchat", "fecha_psicologia", "css_ados2", "modulo_ados2",
|
||||
"fecha_neuropediatria", "fecha_tea", "fecha_sin_tea", "fecha_eeg")))
|
||||
EEGS = table("tea_paciente_eegs", *map(column, (
|
||||
"procedimiento_id", "pac_id", "fecha_eeg", "con_sueno", "canales", "duracion_min", "calidad", "valido",
|
||||
*(c for name, _, _ in CRITERIA for c in (name, f"{name}_bueno")))))
|
||||
METRICS = table("tea_paciente_eeg_metricas", *map(column, (
|
||||
"procedimiento_id", "pac_id", "metrica", "valor", "grupo_edad_eeg", "ref_min", "ref_max", "valor_z", "estado")))
|
||||
ELECTRODES = table("tea_paciente_eeg_electrodos", *map(column, ("procedimiento_id", "pac_id", "metrica", "electrodo",
|
||||
"valor")))
|
||||
ADOS2 = table("tea_paciente_ados2", *map(column, (
|
||||
"procedimiento_id", "pac_id", "fecha_ados2", "modulo", "algoritmo", "css", "clasificacion", "dominio", "reactivo",
|
||||
"etiqueta", "puntaje", "puntaje_algoritmo")))
|
||||
PERSONS = table("persona", column("pac_id"), column("fecha_nacimiento"))
|
||||
|
||||
|
||||
def alterations_validated() -> bool:
|
||||
"""Whether the domain expert validated the reference ranges, effect texts and quality thresholds
|
||||
(`TEA_ALTERACIONES_VALIDADAS=1`): until then no alteration is shown."""
|
||||
return os.environ.get("TEA_ALTERACIONES_VALIDADAS", "") in ("1", "true", "si")
|
||||
|
||||
|
||||
def salt() -> str:
|
||||
return os.environ.get("SEGUIMIENTO_SAL", DEFAULT_SALT)
|
||||
|
||||
|
||||
def _date(value) -> date | None:
|
||||
if value is None or isinstance(value, date):
|
||||
return value
|
||||
return date.fromisoformat(str(value)[:10])
|
||||
|
||||
|
||||
def _rows(queries, query) -> list[dict]:
|
||||
columns, rows = queries.rows(query)
|
||||
return [dict(zip(columns, row)) for row in rows]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Episode:
|
||||
"""A child's screening at the cut-off: its follow-up row, the steps reached, the study's EEG and its metrics."""
|
||||
|
||||
child: dict
|
||||
cutoff: date
|
||||
eegs: list[dict]
|
||||
metrics: list[dict]
|
||||
|
||||
@property
|
||||
def pseudonym(self) -> str:
|
||||
return seudonimo(self.child["pac_id"], salt())
|
||||
|
||||
def reached(self) -> list[tuple[str, date, str]]:
|
||||
steps = []
|
||||
for code, field, label in STEPS:
|
||||
when = _date(self.child[field])
|
||||
if when is None or when > self.cutoff:
|
||||
break
|
||||
steps.append((code, when, label))
|
||||
return steps
|
||||
|
||||
@property
|
||||
def stage(self) -> tuple[str, date] | None:
|
||||
steps = self.reached()
|
||||
return (steps[-1][0], steps[-1][1]) if steps else None
|
||||
|
||||
@property
|
||||
def finished(self) -> bool:
|
||||
return any(code == "EEG" for code, _, _ in self.reached())
|
||||
|
||||
@property
|
||||
def pending(self) -> list[str]:
|
||||
done = {code for code, _, _ in self.reached()}
|
||||
return [label for code, _, label in STEPS if code not in done]
|
||||
|
||||
@property
|
||||
def diagnosis(self) -> bool | None:
|
||||
"""True with a F84.0 note by the cut-off, False with only notes without it, None without a note."""
|
||||
if (_date(self.child["fecha_tea"]) or date.max) <= self.cutoff:
|
||||
return True
|
||||
if (_date(self.child["fecha_sin_tea"]) or date.max) <= self.cutoff:
|
||||
return False
|
||||
return None
|
||||
|
||||
def study_eeg(self) -> dict | None:
|
||||
"""The first good EEG by the cut-off; without one, the latest by then (not valid)."""
|
||||
known = sorted((e for e in self.eegs if (_date(e["fecha_eeg"]) or date.max) <= self.cutoff),
|
||||
key=lambda e: (_date(e["fecha_eeg"]), e["procedimiento_id"]))
|
||||
good = [e for e in known if e["valido"] == 1]
|
||||
return good[0] if good else (known[-1] if known else None)
|
||||
|
||||
def alterations(self) -> list[str]:
|
||||
eeg = self.study_eeg()
|
||||
if eeg is None or eeg["valido"] != 1:
|
||||
return []
|
||||
return sorted(m["metrica"] for m in self.metrics
|
||||
if m["procedimiento_id"] == eeg["procedimiento_id"] and m["estado"] in ALTERED)
|
||||
|
||||
@property
|
||||
def eeg_result(self) -> str:
|
||||
eeg = self.study_eeg()
|
||||
if eeg is None or eeg["valido"] != 1:
|
||||
return "sin-eeg-valido"
|
||||
return "anormal" if self.alterations() else "normal"
|
||||
|
||||
|
||||
def episodes(queries, cutoff: date) -> list[Episode]:
|
||||
"""Every child of the cohort who entered the screening by the cut-off, with its EEGs and their metrics."""
|
||||
eegs, metrics = _rows(queries, select(EEGS)), _rows(queries, select(METRICS))
|
||||
by_child = {}
|
||||
for child in _rows(queries, select(FOLLOW_UP)):
|
||||
if (_date(child["fecha_mchat"]) or date.max) <= cutoff:
|
||||
by_child[child["pac_id"]] = Episode(child, cutoff, [], [])
|
||||
for eeg in eegs:
|
||||
if eeg["pac_id"] in by_child:
|
||||
by_child[eeg["pac_id"]].eegs.append(eeg)
|
||||
for metric in metrics:
|
||||
if metric["pac_id"] in by_child:
|
||||
by_child[metric["pac_id"]].metrics.append(metric)
|
||||
return list(by_child.values())
|
||||
|
||||
|
||||
def patient_of(queries, pseudonym: str) -> int | None:
|
||||
"""The `pac_id` behind a pseudonym, among the cohort's children."""
|
||||
for child in _rows(queries, select(FOLLOW_UP.c.pac_id)):
|
||||
if seudonimo(child["pac_id"], salt()) == pseudonym:
|
||||
return child["pac_id"]
|
||||
return None
|
||||
|
||||
|
||||
# --- resources -------------------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def patient(pac_id: int, birth: date | None, simulated: bool) -> dict:
|
||||
resource = {"resourceType": "Patient", "id": seudonimo(pac_id, salt())}
|
||||
if birth is not None:
|
||||
resource["birthDate"] = _date(birth).strftime("%Y-%m")
|
||||
return tagged(resource, simulated)
|
||||
|
||||
|
||||
def episode_of_care(e: Episode, simulated: bool) -> dict:
|
||||
stage = e.stage
|
||||
resource = {
|
||||
"resourceType": "EpisodeOfCare", "id": e.pseudonym, "status": "finished" if e.finished else "active",
|
||||
"patient": {"reference": f"Patient/{e.pseudonym}"},
|
||||
"period": {"start": _date(e.child["fecha_mchat"]).isoformat(),
|
||||
**({"end": stage[1].isoformat()} if e.finished else {})},
|
||||
"extension": [{"url": AGE_GROUP, "valueCoding": {"system": f"{CODE_SYSTEM}/grupo-edad",
|
||||
"code": e.child["grupo_edad"]}}],
|
||||
}
|
||||
if stage is not None:
|
||||
resource["type"] = [concept(f"{CODE_SYSTEM}/paso", stage[0])]
|
||||
resource["extension"].append({"url": STAGE_DATE, "valueDate": stage[1].isoformat()})
|
||||
return tagged(resource, simulated)
|
||||
|
||||
|
||||
def care_plan(e: Episode, simulated: bool) -> dict:
|
||||
"""The episode's steps, each `completed` with its date or `not-started`."""
|
||||
done = {code: when for code, when, _ in e.reached()}
|
||||
activities = [{"detail": {
|
||||
"code": concept(f"{CODE_SYSTEM}/paso", code, text=label),
|
||||
"status": "completed" if code in done else "not-started",
|
||||
**({"scheduledString": done[code].isoformat()} if code in done else {})}} for code, _, label in STEPS]
|
||||
return tagged({"resourceType": "CarePlan", "id": f"pasos-{e.pseudonym}", "status": "active" if not e.finished
|
||||
else "completed", "intent": "plan", "subject": {"reference": f"Patient/{e.pseudonym}"},
|
||||
"extension": [{"url": f"{STRUCTURE}/episodio", "valueReference": {
|
||||
"reference": f"EpisodeOfCare/{e.pseudonym}"}}],
|
||||
"activity": activities}, simulated)
|
||||
|
||||
|
||||
def mchat_observation(e: Episode, simulated: bool) -> dict | None:
|
||||
if e.child["mchat"] is None:
|
||||
return None
|
||||
return tagged({"resourceType": "Observation", "id": f"mchat-{e.pseudonym}", "status": "final",
|
||||
"code": concept(CATALOG, "mchat.puntaje", "M-CHAT-R/F: puntaje total"),
|
||||
"subject": {"reference": f"Patient/{e.pseudonym}"},
|
||||
"effectiveDateTime": _date(e.child["fecha_mchat"]).isoformat(),
|
||||
"valueInteger": int(e.child["mchat"])}, simulated)
|
||||
|
||||
|
||||
def condition(e: Episode, simulated: bool) -> dict | None:
|
||||
if not e.diagnosis:
|
||||
return None
|
||||
return tagged({"resourceType": "Condition", "id": f"tea-{e.pseudonym}",
|
||||
"code": concept(ICD10, "F84.0", "Autismo en la niñez"),
|
||||
"subject": {"reference": f"Patient/{e.pseudonym}"},
|
||||
"recordedDate": _date(e.child["fecha_tea"]).isoformat()}, simulated)
|
||||
|
||||
|
||||
def quality_observations(eeg: dict, pseudonym: str, simulated: bool) -> list[dict]:
|
||||
observations = []
|
||||
for name, label, unit in CRITERIA:
|
||||
if eeg[name] is None:
|
||||
continue
|
||||
value = ({"valueInteger": int(eeg[name])} if unit == "canales"
|
||||
else {"valueQuantity": {"value": float(eeg[name]), "unit": unit}})
|
||||
observations.append(tagged({
|
||||
"resourceType": "Observation", "id": f"{name.replace('_', '-')}-{eeg['procedimiento_id']}",
|
||||
"status": "final", "code": concept(CATALOG, f"eeg.{name}", label),
|
||||
"subject": {"reference": f"Patient/{pseudonym}"}, "effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
|
||||
**value, "interpretation": [concept(f"{CODE_SYSTEM}/calidad", "BUENO" if eeg[f"{name}_bueno"] else "MALO")],
|
||||
}, simulated))
|
||||
return observations
|
||||
|
||||
|
||||
def metric_observations(eeg: dict, metrics: list[dict], electrodes: list[dict], pseudonym: str,
|
||||
simulated: bool) -> list[dict]:
|
||||
"""One `Observation` per metric (value, reference for the age at the EEG, H/L/N, the z-score as a component, or
|
||||
why it couldn't be evaluated) and one per metric with a component per electrode."""
|
||||
from webapi.fhir.terminology import TEA_EEG
|
||||
|
||||
observations = []
|
||||
for m in sorted((m for m in metrics if m["procedimiento_id"] == eeg["procedimiento_id"]), key=lambda m: m["metrica"]):
|
||||
spec = TEA_EEG["metricas"].get(m["metrica"], {"etiqueta": m["metrica"], "unidad": ""})
|
||||
code = concept(f"{CODE_SYSTEM}/tea-eeg-metrica", m["metrica"], spec["etiqueta"])
|
||||
resource = {"resourceType": "Observation", "id": f"{m['metrica'].replace('_', '-')}-{eeg['procedimiento_id']}",
|
||||
"status": "final", "code": code, "subject": {"reference": f"Patient/{pseudonym}"},
|
||||
"effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat()}
|
||||
if m["valor"] is None or m["valor_z"] is None:
|
||||
resource["dataAbsentReason"] = concept(ABSENT, "not-performed" if m["valor"] is None else "unknown")
|
||||
else:
|
||||
resource["valueQuantity"] = {"value": float(m["valor"]), "unit": spec["unidad"]}
|
||||
resource["interpretation"] = [concept(INTERPRETATION, {"aumentado": "H", "disminuido": "L"}.get(
|
||||
m["estado"], "N"))]
|
||||
resource["component"] = [{"code": concept(f"{CODE_SYSTEM}/puntaje", "z", "Puntaje z"),
|
||||
"valueQuantity": {"value": round(float(m["valor_z"]), 2)}}]
|
||||
if m["ref_min"] is not None:
|
||||
resource["referenceRange"] = [{"low": {"value": float(m["ref_min"]), "unit": spec["unidad"]},
|
||||
"high": {"value": float(m["ref_max"]), "unit": spec["unidad"]},
|
||||
"text": f"Grupo de edad al EEG: {m['grupo_edad_eeg']}"}]
|
||||
observations.append(tagged(resource, simulated))
|
||||
at = [x for x in electrodes if x["procedimiento_id"] == eeg["procedimiento_id"] and x["metrica"] == m["metrica"]]
|
||||
if at:
|
||||
observations.append(tagged({
|
||||
"resourceType": "Observation", "id": f"electrodos-{m['metrica'].replace('_', '-')}-{eeg['procedimiento_id']}",
|
||||
"status": "final", "code": code, "subject": {"reference": f"Patient/{pseudonym}"},
|
||||
"effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
|
||||
"component": [{"code": concept(f"{CODE_SYSTEM}/electrodo-10-20", x["electrodo"]),
|
||||
"valueQuantity": {"value": float(x["valor"])}}
|
||||
for x in sorted(at, key=lambda x: x["electrodo"])]}, simulated))
|
||||
return observations
|
||||
|
||||
|
||||
def eeg_resources(eeg: dict, pseudonym: str, metrics: list[dict], electrodes: list[dict], simulated: bool) -> list[dict]:
|
||||
"""The recording as a `Procedure` and its result as a `DiagnosticReport` with its observations; a bad EEG has
|
||||
no result beyond its quality, and the alterations stay out until validated."""
|
||||
quality = quality_observations(eeg, pseudonym, simulated)
|
||||
altered = (metric_observations(eeg, metrics, electrodes, pseudonym, simulated)
|
||||
if eeg["valido"] == 1 and alterations_validated() else [])
|
||||
procedure = tagged({"resourceType": "Procedure", "id": f"eeg-{eeg['procedimiento_id']}", "status": "completed",
|
||||
"code": concept(CATALOG, "eeg", "Electroencefalograma"),
|
||||
"subject": {"reference": f"Patient/{pseudonym}"},
|
||||
"performedDateTime": _date(eeg["fecha_eeg"]).isoformat()}, simulated)
|
||||
report = {"resourceType": "DiagnosticReport", "id": f"eeg-{eeg['procedimiento_id']}", "status": "final",
|
||||
"code": concept(CATALOG, "eeg", "Electroencefalograma"), "subject": {"reference": f"Patient/{pseudonym}"},
|
||||
"effectiveDateTime": _date(eeg["fecha_eeg"]).isoformat(),
|
||||
"result": [{"reference": f"Observation/{o['id']}"} for o in quality + altered],
|
||||
"conclusionCode": [concept(f"{CODE_SYSTEM}/calidad", eeg["calidad"])]}
|
||||
if eeg["duracion_min"] is not None or eeg["canales"] is not None:
|
||||
report["extension"] = [e for e in (
|
||||
{"url": f"{STRUCTURE}/duracion-min", "valueDecimal": float(eeg["duracion_min"])}
|
||||
if eeg["duracion_min"] is not None else None,
|
||||
{"url": f"{STRUCTURE}/canales", "valueInteger": int(eeg["canales"])} if eeg["canales"] is not None else None,
|
||||
) if e]
|
||||
if eeg["valido"] != 1:
|
||||
report["conclusion"] = "EEG de mala calidad: no es válido para el estudio."
|
||||
return [procedure, tagged(report, simulated), *quality, *altered]
|
||||
|
||||
|
||||
def ados2_observation(rows: list[dict], pseudonym: str, simulated: bool) -> dict | None:
|
||||
"""The first ADOS-2 as one `Observation`: module, algorithm, CSS, classification, the two domain totals and the
|
||||
items, each item with its algorithm score."""
|
||||
if not rows:
|
||||
return None
|
||||
first = min(rows, key=lambda r: (_date(r["fecha_ados2"]) or date.max, r["procedimiento_id"]))
|
||||
items = [r for r in rows if r["procedimiento_id"] == first["procedimiento_id"] and r["reactivo"]]
|
||||
components = []
|
||||
if first["modulo"]:
|
||||
components.append({"code": concept(CATALOG, "ados2.modulo", "Módulo"),
|
||||
"valueCodeableConcept": concept(CATALOG, f"ados2.modulo.{first['modulo']}")})
|
||||
if first["algoritmo"]:
|
||||
components.append({"code": concept(CATALOG, "ados2.algoritmo", "Algoritmo"), "valueString": first["algoritmo"]})
|
||||
if first["css"] is not None:
|
||||
components.append({"code": concept(CATALOG, "ados2.css", "Puntaje de severidad (CSS)"),
|
||||
"valueInteger": int(first["css"])})
|
||||
if first["clasificacion"]:
|
||||
components.append({"code": concept(CATALOG, "ados2.clasificacion", "Clasificación"),
|
||||
"valueCodeableConcept": concept(CATALOG, f"ados2.clasificacion.{first['clasificacion']}")})
|
||||
for domain, label in (("SA", "Afecto social"), ("RRB", "Comportamiento restringido y repetitivo")):
|
||||
total = sum(int(r["puntaje_algoritmo"]) for r in items if r["dominio"] == domain)
|
||||
components.append({"code": concept(f"{CODE_SYSTEM}/ados2-dominio", domain, label), "valueInteger": total})
|
||||
components += [{"code": concept(CATALOG, r["reactivo"], r["etiqueta"]), "valueInteger": int(r["puntaje"]),
|
||||
"extension": [{"url": f"{STRUCTURE}/puntaje-algoritmo", "valueInteger": int(r["puntaje_algoritmo"])},
|
||||
{"url": f"{STRUCTURE}/dominio", "valueCode": r["dominio"]}]}
|
||||
for r in sorted(items, key=lambda r: r["reactivo"])]
|
||||
return tagged({"resourceType": "Observation", "id": f"ados2-{first['procedimiento_id']}", "status": "final",
|
||||
"code": concept(CATALOG, "ados2", "ADOS-2"), "subject": {"reference": f"Patient/{pseudonym}"},
|
||||
"effectiveDateTime": _date(first["fecha_ados2"]).isoformat(), "component": components}, simulated)
|
||||
|
||||
|
||||
def patient_summary(queries, pac_id: int, today: date, simulated: bool) -> dict:
|
||||
"""The `$resumen-tea` collection: the patient, its first ADOS-2 and the EEG the study uses, as of today."""
|
||||
pseudonym = seudonimo(pac_id, salt())
|
||||
persons = _rows(queries, select(PERSONS).where(PERSONS.c.pac_id == pac_id))
|
||||
resources = [patient(pac_id, persons[0]["fecha_nacimiento"] if persons else None, simulated)]
|
||||
ados2 = ados2_observation(_rows(queries, select(ADOS2).where(ADOS2.c.pac_id == pac_id)), pseudonym, simulated)
|
||||
resources += [ados2] if ados2 else []
|
||||
(child,) = _rows(queries, select(FOLLOW_UP).where(FOLLOW_UP.c.pac_id == pac_id)) or [None]
|
||||
if child is not None:
|
||||
e = Episode(child, today, _rows(queries, select(EEGS).where(EEGS.c.pac_id == pac_id)),
|
||||
_rows(queries, select(METRICS).where(METRICS.c.pac_id == pac_id)))
|
||||
eeg = e.study_eeg()
|
||||
if eeg is not None:
|
||||
electrodes = _rows(queries, select(ELECTRODES).where(ELECTRODES.c.pac_id == pac_id))
|
||||
resources += eeg_resources(eeg, pseudonym, e.metrics, electrodes, simulated)
|
||||
return {"resourceType": "Bundle", "type": "collection", "entry": [{"resource": r} for r in resources]}
|
||||
@@ -0,0 +1,53 @@
|
||||
# TEA's EEG vocabulary for the FHIR answers: what each metric's alteration may mean (`efectos`, by state), and where
|
||||
# each 10-20 electrode sits on the map the WebApp draws (x to the right, y forward, both from -1 to 1).
|
||||
# The effect texts are placeholders pending the domain expert's review, like the reference ranges in dbt's var `tea`.
|
||||
|
||||
[metricas.ritmo_posterior]
|
||||
etiqueta = "Ritmo posterior"
|
||||
unidad = "Hz"
|
||||
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
|
||||
efectos.disminuido = ["Ritmo más lento de lo esperado para la edad.", "Posible relación con retraso en la maduración cortical."]
|
||||
|
||||
[metricas.husos_sueno_n2]
|
||||
etiqueta = "Husos de sueño N2"
|
||||
unidad = "husos/min"
|
||||
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
|
||||
efectos.disminuido = ["Posible relación con alteraciones del sueño.", "Posible efecto en la consolidación de la memoria y el aprendizaje."]
|
||||
|
||||
[metricas.husos_sueno_n3]
|
||||
etiqueta = "Husos de sueño N3"
|
||||
unidad = "husos/min"
|
||||
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
|
||||
efectos.disminuido = ["Posible relación con alteraciones del sueño.", "Posible efecto en la consolidación de la memoria y el aprendizaje."]
|
||||
|
||||
[metricas.picos_paroxisticos]
|
||||
etiqueta = "Picos paroxísticos"
|
||||
unidad = "picos/min"
|
||||
efectos.aumentado = ["Actividad paroxística mayor de la esperada.", "Correlacionar con la clínica."]
|
||||
|
||||
[metricas.gradiente_anteroposterior]
|
||||
etiqueta = "Gradiente anteroposterior"
|
||||
unidad = "razón posterior/anterior"
|
||||
efectos.aumentado = ["Hallazgo de significado incierto; correlacionar con la clínica."]
|
||||
efectos.disminuido = ["Organización anteroposterior menos marcada de lo esperado.", "Posible relación con retraso en la maduración cortical."]
|
||||
|
||||
[electrodos]
|
||||
Fp1 = [-0.25, 0.77]
|
||||
Fp2 = [0.25, 0.77]
|
||||
F7 = [-0.65, 0.47]
|
||||
F3 = [-0.33, 0.4]
|
||||
Fz = [0.0, 0.38]
|
||||
F4 = [0.33, 0.4]
|
||||
F8 = [0.65, 0.47]
|
||||
T3 = [-0.8, 0.0]
|
||||
C3 = [-0.4, 0.0]
|
||||
Cz = [0.0, 0.0]
|
||||
C4 = [0.4, 0.0]
|
||||
T4 = [0.8, 0.0]
|
||||
T5 = [-0.65, -0.47]
|
||||
P3 = [-0.33, -0.4]
|
||||
Pz = [0.0, -0.38]
|
||||
P4 = [0.33, -0.4]
|
||||
T6 = [0.65, -0.47]
|
||||
O1 = [-0.25, -0.77]
|
||||
O2 = [0.25, -0.77]
|
||||
@@ -0,0 +1,74 @@
|
||||
"""The project's code systems as FHIR R4 `CodeSystem` resources, generated from what defines them: the domain's
|
||||
catalog (`core/catalogos/<domain>.toml`: studies, results and their values), TEA's screening stages and diagnostic
|
||||
results, and TEA's EEG metrics with their effect texts (`tea_eeg.toml`)."""
|
||||
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
from webapi.fhir.common import CODE_SYSTEM, canonical
|
||||
from webapi.orchestration.reference.catalogs import ruta_de_catalogo
|
||||
|
||||
TEA_EEG = tomllib.loads((Path(__file__).parent / "tea_eeg.toml").read_text(encoding="utf-8"))
|
||||
STAGES = (("SOLO_MCHAT", "Solo M-CHAT"), ("PSICOLOGIA", "Hasta evaluación psicológica"),
|
||||
("NEUROPEDIATRIA", "Hasta evaluación neuropediátrica"), ("EEG", "Con EEG"))
|
||||
DIAGNOSES = (("EN_PROCESO", "En proceso"), ("SIN_TEA", "Nota sin F84.0"), ("CONFIRMADO", "Diagnóstico confirmado"))
|
||||
QUALITY = (("BUENO", "Bueno"), ("MALO", "Malo"), ("SIN_ANALIZAR", "Sin analizar"))
|
||||
|
||||
|
||||
def _code_system(id_: str, title: str, concepts: list[dict], *, hierarchy: bool = False) -> dict:
|
||||
resource = {"resourceType": "CodeSystem", "id": id_, "url": f"{CODE_SYSTEM}/{id_}", "name": id_.replace("-", "_"),
|
||||
"title": title, "status": "active", "content": "complete", "concept": concepts}
|
||||
if hierarchy:
|
||||
resource["hierarchyMeaning"] = "part-of"
|
||||
return resource
|
||||
|
||||
|
||||
def catalog(domain: str) -> dict:
|
||||
"""The domain's catalog: each study, its results under it and each coded result's values under the result."""
|
||||
studies = tomllib.loads(ruta_de_catalogo(domain).read_text(encoding="utf-8"))
|
||||
concepts = []
|
||||
for study_id, study in studies.items():
|
||||
results = []
|
||||
for name, result in study.get("resultados", {}).items():
|
||||
values = [{"code": f"{study_id}.{name}.{v['valor']}", "display": v["etiqueta"]}
|
||||
for v in result.get("valores", ())]
|
||||
results.append({"code": f"{study_id}.{name}", "display": result["etiqueta"],
|
||||
**({"concept": values} if values else {})})
|
||||
concepts.append({"code": study_id, "display": study["etiqueta"], **({"concept": results} if results else {})})
|
||||
return _code_system(f"{domain}-catalogo", f"Catálogo de {domain.upper()}", concepts, hierarchy=True)
|
||||
|
||||
|
||||
def tea_code_systems() -> dict[str, dict]:
|
||||
metrics = [{"code": code, "display": spec["etiqueta"], "property": [
|
||||
{"code": "unidad", "valueString": spec["unidad"]},
|
||||
*({"code": f"efecto-{state}", "valueString": text} for state, texts in spec.get("efectos", {}).items()
|
||||
for text in texts)]} for code, spec in TEA_EEG["metricas"].items()]
|
||||
systems = [
|
||||
_code_system("paso", "Etapa del tamizaje de TEA", [{"code": c, "display": d} for c, d in STAGES]),
|
||||
_code_system("estado", "Resultado diagnóstico de TEA", [{"code": c, "display": d} for c, d in DIAGNOSES]),
|
||||
_code_system("calidad", "Calidad del EEG", [{"code": c, "display": d} for c, d in QUALITY]),
|
||||
{**_code_system("tea-eeg-metrica", "Métricas del EEG", metrics),
|
||||
"property": [{"code": "unidad", "type": "string"}, {"code": "efecto-aumentado", "type": "string"},
|
||||
{"code": "efecto-disminuido", "type": "string"}]},
|
||||
_code_system("electrodo-10-20", "Electrodos del sistema 10-20",
|
||||
[{"code": e, "display": e} for e in TEA_EEG["electrodos"]]),
|
||||
_code_system("grupo-edad", "Grupo de edad al primer M-CHAT", [
|
||||
{"code": "16_23", "display": "16 a 23 meses"}, {"code": "24_29", "display": "24 a 29 meses"},
|
||||
{"code": "30_36", "display": "30 a 36 meses"}, {"code": "sin_dato", "display": "Sin dato"}]),
|
||||
]
|
||||
return {s["id"]: s for s in systems}
|
||||
|
||||
|
||||
def code_systems(domain: str) -> dict[str, dict]:
|
||||
"""Every code system the domain's FHIR endpoint serves, by id."""
|
||||
systems = {f"{domain}-catalogo": catalog(domain)}
|
||||
if domain == "tea":
|
||||
systems.update(tea_code_systems())
|
||||
return systems
|
||||
|
||||
|
||||
def metric_value_set() -> dict:
|
||||
"""The alteration types: the EEG metrics' `ValueSet`."""
|
||||
return {"resourceType": "ValueSet", "id": "tea-alteracion", "url": canonical("ValueSet/tea-alteracion"),
|
||||
"name": "tea_alteracion", "title": "Tipos de alteración del EEG", "status": "active",
|
||||
"compose": {"include": [{"system": f"{CODE_SYSTEM}/tea-eeg-metrica"}]}}
|
||||
Reference in New Issue
Block a user