89 lines
5.0 KiB
Python
89 lines
5.0 KiB
Python
"""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, TEA's EEG metrics with their effect texts (`tea_eeg.toml`), and the EEG analysis's quality checks, under
|
|
the analysis's own code system with the catalog's labels."""
|
|
|
|
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 eeg_checks() -> dict:
|
|
"""The EEG analysis's quality checks (`CriterioEeg`), under the code system its validation report uses, each with
|
|
the catalog's label of its `eeg.calidad_<check>` result."""
|
|
from core.tea.enums import CriterioEeg
|
|
from tea.validation.fhir import SYSTEM
|
|
|
|
results = tomllib.loads(ruta_de_catalogo("tea").read_text(encoding="utf-8"))["eeg"]["resultados"]
|
|
concepts = [{"code": c.value, "display": results[f"calidad_{c.value.replace('-', '_')}"]["etiqueta"]}
|
|
for c in CriterioEeg]
|
|
return {**_code_system("tea-eeg-criterio", "Reglas de calidad del EEG", concepts), "url": SYSTEM}
|
|
|
|
|
|
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-normal", "type": "string"},
|
|
{"code": "efecto-aumentado", "type": "string"}, {"code": "efecto-disminuido", "type": "string"}]},
|
|
eeg_checks(),
|
|
_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"}]}}
|