71 lines
2.6 KiB
Python
71 lines
2.6 KiB
Python
from collections.abc import Iterable
|
|
from fhir.resources.R4B.conceptmap import ConceptMap
|
|
from core import catalog
|
|
|
|
GENDER = "http://hl7.org/fhir/administrative-gender"
|
|
BOOLEAN = "https://isssteleon.org/fhir/CodeSystem/boolean"
|
|
_GENDER_CODES = {"female", "male"}
|
|
_BOOLEAN_CODES = {"true", "false"}
|
|
|
|
|
|
def systems(field: str) -> dict[str, set[str] | None]:
|
|
found: dict[str, set[str] | None] = {}
|
|
if field == "sex":
|
|
found[GENDER] = _GENDER_CODES
|
|
for study in catalog.studies().values():
|
|
f = study.fields.get(field)
|
|
if f is None:
|
|
continue
|
|
if f.type == "boolean":
|
|
found[BOOLEAN] = _BOOLEAN_CODES
|
|
elif f.type == "code":
|
|
url = catalog.systems()[f.system].url
|
|
codes = set(f.codes) or None
|
|
known = found.get(url, set())
|
|
found[url] = None if codes is None or known is None else known | codes
|
|
return found
|
|
|
|
|
|
def problems(cm: ConceptMap) -> list[str]:
|
|
allowed: dict[str, set[str] | None] = {GENDER: _GENDER_CODES, BOOLEAN: _BOOLEAN_CODES}
|
|
for study in catalog.studies().values():
|
|
for name in study.fields:
|
|
allowed |= systems(name)
|
|
found = []
|
|
for group in cm.group or []:
|
|
if group.target not in allowed:
|
|
found.append(f"{group.target}: no platform field takes codes from it")
|
|
continue
|
|
codes = allowed[group.target]
|
|
for element in group.element:
|
|
for target in element.target or []:
|
|
if codes is not None and target.code not in codes:
|
|
found.append(f"{group.target}: {target.code} is not an allowed code")
|
|
return found
|
|
|
|
|
|
def table(maps: Iterable[ConceptMap], field: str) -> dict[str, str]:
|
|
targets = systems(field)
|
|
found = {}
|
|
for cm in maps:
|
|
for group in cm.group or []:
|
|
if group.target not in targets:
|
|
continue
|
|
for element in group.element:
|
|
for target in element.target or []:
|
|
if target.equivalence in ("equivalent", "equal", "wider", "subsumes"):
|
|
found[element.code.casefold()] = target.code
|
|
return found
|
|
|
|
|
|
def translate(maps: Iterable[ConceptMap], source: str, code: str) -> tuple[str, str] | None:
|
|
for cm in maps:
|
|
for group in cm.group or []:
|
|
if group.source != source:
|
|
continue
|
|
for element in group.element:
|
|
if element.code.casefold() == code.casefold():
|
|
for target in element.target or []:
|
|
return (group.target, target.code)
|
|
return None
|